Search in sources :

Example 6 with MultiException

use of io.fabric8.utils.MultiException in project fabric8 by jboss-fuse.

the class VerifyFeatureResolutionMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        Field field = URL.class.getDeclaredField("factory");
        field.setAccessible(true);
        field.set(null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    URL.setURLStreamHandlerFactory(new CustomBundleURLStreamHandlerFactory());
    System.setProperty("karaf.home", "target/karaf");
    System.setProperty("karaf.data", "target/karaf/data");
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(8);
    Hashtable<String, String> properties = new Hashtable<>();
    if (additionalMetadata != null) {
        try (Reader reader = new FileReader(additionalMetadata)) {
            Properties metadata = new Properties();
            metadata.load(reader);
            for (Enumeration<?> e = metadata.propertyNames(); e.hasMoreElements(); ) {
                Object key = e.nextElement();
                Object val = metadata.get(key);
                properties.put(key.toString(), val.toString());
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Unable to load additional metadata from " + additionalMetadata, e);
        }
    }
    DownloadManager manager;
    MavenResolver resolver;
    final Map<String, Repository> repositories;
    Map<String, Feature[]> repos = new HashMap<>();
    Map<String, Feature> allFeatures = new HashMap<>();
    try {
        resolver = MavenResolvers.createMavenResolver(null, properties, "org.ops4j.pax.url.mvn", repositorySystem);
        manager = DownloadManagers.createDownloadManager(resolver, executor);
        repositories = downloadRepositories(manager, descriptors).call();
        for (String repoUri : repositories.keySet()) {
            Feature[] features = repositories.get(repoUri).getFeatures();
            // Ack features to inline configuration files urls
            for (Feature feature : features) {
                for (BundleInfo bi : feature.getBundles()) {
                    String loc = bi.getLocation();
                    String nloc = null;
                    if (loc.contains("file:")) {
                        for (ConfigFile cfi : feature.getConfigurationFiles()) {
                            if (cfi.getFinalname().substring(1).equals(loc.substring(loc.indexOf("file:") + "file:".length()))) {
                                nloc = cfi.getLocation();
                            }
                        }
                    }
                    if (nloc != null) {
                        bi.setLocation(loc.substring(0, loc.indexOf("file:")) + nloc);
                    }
                }
                allFeatures.put(feature.getId(), feature);
            }
            repos.put(repoUri, features);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to load features descriptors", e);
    }
    List<Feature> featuresToTest = new ArrayList<>();
    if (verifyTransitive) {
        for (Feature[] features : repos.values()) {
            featuresToTest.addAll(Arrays.asList(features));
        }
    } else {
        for (String uri : descriptors) {
            featuresToTest.addAll(Arrays.asList(repos.get(uri)));
        }
    }
    if (features != null && !features.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for (String feature : features) {
            if (sb.length() > 0) {
                sb.append("|");
            }
            String p = feature.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*");
            sb.append(p);
            if (!feature.contains("/")) {
                sb.append("/.*");
            }
        }
        Pattern pattern = Pattern.compile(sb.toString());
        for (Iterator<Feature> iterator = featuresToTest.iterator(); iterator.hasNext(); ) {
            Feature feature = iterator.next();
            String id = feature.getName() + "/" + feature.getVersion();
            if (!pattern.matcher(id).matches()) {
                iterator.remove();
            }
        }
    }
    for (String fmk : framework) {
        properties.put("feature.framework." + fmk, fmk);
    }
    List<Throwable> failures = new ArrayList<>();
    for (Feature feature : featuresToTest) {
        try {
            String id = feature.getName() + "/" + feature.getVersion();
            manager = DownloadManagers.createDownloadManager(resolver, executor);
            verifyResolution(manager, allFeatures, id, properties);
            getLog().info("Verification of feature " + id + " succeeded");
        } catch (Exception e) {
            getLog().warn(e.getMessage());
            failures.add(e);
            if ("first".equals(fail)) {
                throw e;
            }
        }
    }
    if ("end".equals(fail) && !failures.isEmpty()) {
        throw new MojoExecutionException("Verification failures", new MultiException("Verification failures", failures));
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Reader(java.io.Reader) FileReader(java.io.FileReader) DeploymentAgent.getPrefixedProperties(io.fabric8.agent.DeploymentAgent.getPrefixedProperties) Properties(java.util.Properties) DownloadManager(io.fabric8.agent.download.DownloadManager) Feature(io.fabric8.agent.model.Feature) Field(java.lang.reflect.Field) BundleInfo(io.fabric8.agent.model.BundleInfo) FileReader(java.io.FileReader) Pattern(java.util.regex.Pattern) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ConfigFile(io.fabric8.agent.model.ConfigFile) Hashtable(java.util.Hashtable) IOException(java.io.IOException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) MultiException(io.fabric8.common.util.MultiException) Repository(io.fabric8.agent.model.Repository) MultiException(io.fabric8.common.util.MultiException)

Example 7 with MultiException

use of io.fabric8.utils.MultiException in project fabric8 by jboss-fuse.

the class AgentUtils method downloadRepositories.

public static Callable<Map<String, Repository>> downloadRepositories(DownloadManager manager, Set<String> uris) throws MultiException, InterruptedException, MalformedURLException {
    final Map<String, Repository> repositories = new HashMap<>();
    final Downloader downloader = manager.createDownloader();
    final File targetLocation = getDefaultKarafRepository();
    for (String uri : uris) {
        downloader.download(uri, new DownloadCallback() {

            @Override
            public void downloaded(StreamProvider provider) throws Exception {
                String uri = provider.getUrl();
                Repository repository = new Repository(URI.create(uri));
                repository.load(new FileInputStream(provider.getFile()), true);
                synchronized (repositories) {
                    repositories.put(uri, repository);
                }
                for (URI repo : repository.getRepositories()) {
                    downloader.download(repo.toASCIIString(), this);
                }
                Artifact artifact = Utils.mvnurlToArtifact(uri, true);
                if (artifact == null || artifact.getVersion() == null || !artifact.getVersion().endsWith("-SNAPSHOT")) {
                    // we need a feature repository to be available in ${karaf.home}/${karaf.default.repository}
                    // it makes patching much easier
                    // ENTESB-6931: don't store SNAPSHOT feature repositories in ${karaf.home}/${karaf.default.repository}
                    storeInDefaultKarafRepository(targetLocation, provider.getFile(), uri);
                }
            }
        });
    }
    return new Callable<Map<String, Repository>>() {

        @Override
        public Map<String, Repository> call() throws Exception {
            downloader.await();
            return repositories;
        }
    };
}
Also used : StreamProvider(io.fabric8.agent.download.StreamProvider) HashMap(java.util.HashMap) DownloadCallback(io.fabric8.agent.download.DownloadCallback) Downloader(io.fabric8.agent.download.Downloader) URI(java.net.URI) MalformedURLException(java.net.MalformedURLException) MultiException(io.fabric8.common.util.MultiException) FileInputStream(java.io.FileInputStream) Artifact(io.fabric8.patch.management.Artifact) Callable(java.util.concurrent.Callable) Repository(io.fabric8.agent.model.Repository) File(java.io.File)

Example 8 with MultiException

use of io.fabric8.utils.MultiException in project fabric8 by fabric8io.

the class Util method cleanupAllMatching.

public static void cleanupAllMatching(KubernetesClient client, Session session, List<Throwable> errors, List<KubernetesList> kubeConfigs) throws MultiException {
    String sessionNamespace = session.getNamespace();
    session.getLogger().info("Removing provisioned resources in namespace " + sessionNamespace);
    /**
     * Lets use a loop to ensure we really do delete all the matching resources
     */
    for (int i = 0; i < 10; i++) {
        for (KubernetesList list : kubeConfigs) {
            List<HasMetadata> items = list.getItems();
            if (items != null) {
                for (HasMetadata item : items) {
                    cleanupItem(client, session, item, errors);
                }
            }
        }
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList)

Example 9 with MultiException

use of io.fabric8.utils.MultiException in project fabric8 by fabric8io.

the class Util method displaySessionStatus.

public static void displaySessionStatus(KubernetesClient client, Session session) throws MultiException {
    if (client == null) {
        session.getLogger().warn("No KubernetesClient for session: " + session.getId());
        return;
    }
    if (client.isAdaptable(OpenShiftClient.class)) {
        OpenShiftClient oClient = client.adapt(OpenShiftClient.class);
        List<DeploymentConfig> deploymentConfigs = oClient.deploymentConfigs().inNamespace(session.getNamespace()).list().getItems();
        if (deploymentConfigs == null) {
            throw new MultiException("No deployment configs found in namespace" + session.getNamespace());
        }
        for (DeploymentConfig deploymentConfig : deploymentConfigs) {
            session.getLogger().info("Deployment config:" + KubernetesHelper.getName(deploymentConfig));
        }
    } else {
        List<Deployment> deployments = client.extensions().deployments().inNamespace(session.getNamespace()).list().getItems();
        if (deployments == null) {
            throw new MultiException("No deployments found in namespace" + session.getNamespace());
        }
        for (Deployment deployment : deployments) {
            session.getLogger().info("Deployment:" + KubernetesHelper.getName(deployment));
        }
    }
    List<Pod> pods = client.pods().inNamespace(session.getNamespace()).list().getItems();
    if (pods == null) {
        throw new MultiException("No pods found in namespace" + session.getNamespace());
    }
    for (Pod pod : pods) {
        session.getLogger().info("Pod:" + KubernetesHelper.getName(pod) + " Status:" + pod.getStatus());
    }
    List<Service> svcs = client.services().inNamespace(session.getNamespace()).list().getItems();
    if (svcs == null) {
        throw new MultiException("No services found in namespace" + session.getNamespace());
    }
    for (Service service : svcs) {
        session.getLogger().info("Service:" + KubernetesHelper.getName(service) + " IP:" + getPortalIP(service) + " Port:" + getPorts(service));
    }
}
Also used : Pod(io.fabric8.kubernetes.api.model.Pod) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) Service(io.fabric8.kubernetes.api.model.Service) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) MultiException(io.fabric8.utils.MultiException)

Example 10 with MultiException

use of io.fabric8.utils.MultiException in project fabric8 by fabric8io.

the class Util method cleanupAllResources.

public static void cleanupAllResources(KubernetesClient client, Session session, List<Throwable> errors) throws MultiException {
    String sessionNamespace = session.getNamespace();
    session.getLogger().info("Removing all resources in namespace " + sessionNamespace);
    /**
     * Lets use a loop to ensure we really do delete all the matching resources
     */
    for (int i = 0; i < 10; i++) {
        OpenShiftClient openShiftClient = new Controller(client).getOpenShiftClientOrNull();
        if (openShiftClient != null) {
            try {
                openShiftClient.deploymentConfigs().inNamespace(sessionNamespace).delete();
            } catch (KubernetesClientException e) {
                errors.add(e);
            }
            try {
                openShiftClient.routes().inNamespace(sessionNamespace).delete();
            } catch (KubernetesClientException e) {
                errors.add(e);
            }
        }
        try {
            client.extensions().deployments().inNamespace(sessionNamespace).delete();
        } catch (KubernetesClientException e) {
            errors.add(e);
        }
        try {
            client.extensions().replicaSets().inNamespace(sessionNamespace).delete();
        } catch (KubernetesClientException e) {
            errors.add(e);
        }
        try {
            client.replicationControllers().inNamespace(sessionNamespace).delete();
        } catch (KubernetesClientException e) {
            errors.add(e);
        }
        try {
            client.pods().inNamespace(sessionNamespace).delete();
        } catch (KubernetesClientException e) {
            errors.add(e);
        }
        try {
            client.extensions().ingresses().inNamespace(sessionNamespace).delete();
        } catch (KubernetesClientException e) {
            errors.add(e);
        }
        try {
            client.services().inNamespace(sessionNamespace).delete();
        } catch (KubernetesClientException e) {
            errors.add(e);
        }
        try {
            client.securityContextConstraints().withName(sessionNamespace).delete();
        } catch (KubernetesClientException e) {
            errors.add(e);
        }
        // lets see if there are any matching podList left
        List<Pod> filteredPods = notNullList(client.pods().inNamespace(sessionNamespace).list().getItems());
        if (filteredPods.isEmpty()) {
            return;
        } else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : Pod(io.fabric8.kubernetes.api.model.Pod) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Controller(io.fabric8.kubernetes.api.Controller) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)6 Downloader (io.fabric8.agent.download.Downloader)4 StreamProvider (io.fabric8.agent.download.StreamProvider)4 MultiException (io.fabric8.common.util.MultiException)4 Pod (io.fabric8.kubernetes.api.model.Pod)4 MultiException (io.fabric8.utils.MultiException)4 File (java.io.File)4 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 DownloadCallback (io.fabric8.agent.download.DownloadCallback)3 BundleInfo (io.fabric8.agent.model.BundleInfo)2 ConfigFile (io.fabric8.agent.model.ConfigFile)2 Feature (io.fabric8.agent.model.Feature)2 Repository (io.fabric8.agent.model.Repository)2 Logger (io.fabric8.arquillian.kubernetes.log.Logger)2 Util.cleanupSession (io.fabric8.arquillian.utils.Util.cleanupSession)2 Util.readAsString (io.fabric8.arquillian.utils.Util.readAsString)2 Controller (io.fabric8.kubernetes.api.Controller)2 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)2 KubernetesList (io.fabric8.kubernetes.api.model.KubernetesList)2