Search in sources :

Example 31 with Feature

use of io.fabric8.agent.model.Feature 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 32 with Feature

use of io.fabric8.agent.model.Feature in project fabric8 by jboss-fuse.

the class VerifyFeatureResolutionMojo method verifyResolution.

private void verifyResolution(DownloadManager manager, Map<String, Feature> allFeatures, String feature, Hashtable<String, String> properties) throws MojoExecutionException {
    try {
        properties.put("feature.totest", feature);
        FakeSystemBundle systemBundle = getSystemBundleResource(getMetadata(properties, "metadata#"));
        FakeServiceReference profileHandlerSR = new FakeServiceReference(URLStreamHandlerService.class.getName(), "(url.handler.protocol=profile2)");
        systemBundle.setServiceReferences(URLStreamHandlerService.class.getName(), null, new ServiceReference[] { profileHandlerSR });
        systemBundle.setService(profileHandlerSR, new Object());
        Agent agent = new Agent(null, systemBundle, manager);
        agent.setOptions(EnumSet.of(io.fabric8.agent.service.Constants.Option.Simulate, io.fabric8.agent.service.Constants.Option.Silent));
        try {
            agent.provision(allFeatures, getPrefixedProperties(properties, "feature."), getPrefixedProperties(properties, "bundle."), getPrefixedProperties(properties, "req."), getPrefixedProperties(properties, "override."), getPrefixedProperties(properties, "optional."), getMetadata(properties, "metadata#"));
        } catch (Exception e) {
            Set<String> resources = new TreeSet<>(manager.getProviders().keySet());
            throw new MojoExecutionException("Feature resolution failed for " + feature + "\nMessage: " + e.toString() + "\nResources: " + toString(resources), e);
        }
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("Error verifying feature " + feature + "\nMessage: " + e.getMessage(), e);
    }
}
Also used : Agent(io.fabric8.agent.service.Agent) EnumSet(java.util.EnumSet) Set(java.util.Set) TreeSet(java.util.TreeSet) URLStreamHandlerService(org.osgi.service.url.URLStreamHandlerService) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) MultiException(io.fabric8.common.util.MultiException)

Example 33 with Feature

use of io.fabric8.agent.model.Feature in project fabric8 by jboss-fuse.

the class ProfileDisplayAction method displayProfile.

private void displayProfile(Profile profile) {
    PrintStream output = System.out;
    output.println("Profile id: " + profile.getId());
    output.println("Version   : " + profile.getVersion());
    output.println("Attributes: ");
    Map<String, String> props = profile.getAttributes();
    for (String key : props.keySet()) {
        output.println("\t" + key + ": " + props.get(key));
    }
    String versionId = profile.getVersion();
    String profileId = profile.getId();
    output.printf("Containers: %s\n", toString(fabricService.getAssociatedContainers(versionId, profileId)));
    ProfileService profileService = fabricService.adapt(ProfileService.class);
    if (overlay) {
        profile = profileService.getOverlayProfile(profile);
    }
    Map<String, Map<String, String>> configuration = new HashMap<>(profile.getConfigurations());
    Map<String, byte[]> resources = profile.getFileConfigurations();
    Map<String, String> agentConfiguration = profile.getConfiguration(Constants.AGENT_PID);
    List<String> agentProperties = new ArrayList<String>();
    List<String> systemProperties = new ArrayList<String>();
    List<String> configProperties = new ArrayList<String>();
    List<String> otherResources = new ArrayList<String>();
    for (Map.Entry<String, String> entry : agentConfiguration.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (value.contains(",")) {
            value = "\t" + value.replace(",", ",\n\t\t");
        }
        if (key.startsWith("system.")) {
            systemProperties.add("  " + key.substring("system.".length()) + " = " + value);
        } else if (key.startsWith("config.")) {
            configProperties.add("  " + key.substring("config.".length()) + " = " + value);
        } else if (!key.startsWith("feature.") && !key.startsWith("repository") && !key.startsWith("bundle.") && !key.startsWith("fab.") && !key.startsWith("override.") && !key.startsWith("attribute.")) {
            agentProperties.add("  " + key + " = " + value);
        }
    }
    if (configuration.containsKey(Constants.AGENT_PID)) {
        output.println("\nContainer settings");
        output.println("----------------------------");
        if (profile.getLibraries().size() > 0) {
            printConfigList("Libraries : ", output, profile.getLibraries());
        }
        if (profile.getRepositories().size() > 0) {
            printConfigList("Repositories : ", output, profile.getRepositories());
        }
        if (profile.getFeatures().size() > 0) {
            printConfigList("Features : ", output, profile.getFeatures());
        }
        if (profile.getBundles().size() > 0) {
            printConfigList("Bundles : ", output, profile.getBundles());
        }
        if (profile.getFabs().size() > 0) {
            printConfigList("Fabs : ", output, profile.getFabs());
        }
        if (profile.getOverrides().size() > 0) {
            printConfigList("Overrides : ", output, profile.getOverrides());
        }
        if (agentProperties.size() > 0) {
            printConfigList("Agent Properties : ", output, agentProperties);
        }
        if (systemProperties.size() > 0) {
            printConfigList("System Properties : ", output, systemProperties);
        }
        if (configProperties.size() > 0) {
            printConfigList("Config Properties : ", output, configProperties);
        }
        configuration.remove(Constants.AGENT_PID);
    }
    output.println("\nConfiguration details");
    output.println("----------------------------");
    for (Map.Entry<String, Map<String, String>> cfg : configuration.entrySet()) {
        output.println("PID: " + cfg.getKey());
        for (Map.Entry<String, String> values : cfg.getValue().entrySet()) {
            output.println("  " + values.getKey() + " " + values.getValue());
        }
        output.println("\n");
    }
    output.println("\nOther resources");
    output.println("----------------------------");
    for (Map.Entry<String, byte[]> resource : resources.entrySet()) {
        String name = resource.getKey();
        if (!name.endsWith(".properties")) {
            output.println("Resource: " + resource.getKey());
            if (displayResources) {
                output.println(new String(resource.getValue(), Charsets.UTF_8));
                output.println("\n");
            }
        }
    }
}
Also used : PrintStream(java.io.PrintStream) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ProfileService(io.fabric8.api.ProfileService) HashMap(java.util.HashMap) Map(java.util.Map)

Example 34 with Feature

use of io.fabric8.agent.model.Feature in project fabric8 by jboss-fuse.

the class FabricFeaturesServiceImpl method listInstalledFeatures.

@Override
public Feature[] listInstalledFeatures() {
    assertValid();
    Set<Feature> installed = new HashSet<Feature>();
    try {
        Map<String, Map<String, Feature>> allFeatures = getFeatures(installedRepositories);
        Profile overlayProfile = fabricService.get().getCurrentContainer().getOverlayProfile();
        Profile effectiveProfile = Profiles.getEffectiveProfile(fabricService.get(), overlayProfile);
        for (String featureName : effectiveProfile.getFeatures()) {
            try {
                Feature f;
                if (featureName.contains("/")) {
                    String[] parts = featureName.split("/");
                    String name = parts[0];
                    String version = parts[1];
                    f = allFeatures.get(name).get(version);
                } else {
                    TreeMap<String, Feature> versionMap = (TreeMap<String, Feature>) allFeatures.get(featureName);
                    f = versionMap.lastEntry().getValue();
                }
                addFeatures(f, installed);
            } catch (Throwable ex) {
                // may also throw java.lang.NoClassDefFoundError when
                // bundle wiring is no longer active - ignoring
                LOGGER.debug("Error while adding {} to the features list");
            }
        }
    } catch (IllegalStateException e) {
        if ("Client is not started".equals(e.getMessage())) {
            LOGGER.warn("Zookeeper connection not available. It's not yet possible to compute features.");
        }
    } catch (InvalidComponentException e) {
        LOGGER.info("FeaturesService was deactivated");
    } catch (Exception e) {
        LOGGER.error("Error retrieving features.", e);
    }
    return installed.toArray(new Feature[installed.size()]);
}
Also used : Feature(org.apache.karaf.features.Feature) Profile(io.fabric8.api.Profile) InvalidComponentException(io.fabric8.api.InvalidComponentException) InvalidComponentException(io.fabric8.api.InvalidComponentException)

Example 35 with Feature

use of io.fabric8.agent.model.Feature in project fabric8 by jboss-fuse.

the class FabricFeaturesServiceImpl method listFeatures.

@Override
public Feature[] listFeatures() throws Exception {
    assertValid();
    Set<Feature> allfeatures = new HashSet<Feature>();
    Repository[] repositories = listRepositories();
    for (Repository repository : repositories) {
        try {
            for (Feature feature : repository.getFeatures()) {
                if (!allfeatures.contains(feature)) {
                    allfeatures.add(feature);
                }
            }
        } catch (Exception ex) {
            LOGGER.debug("Could not load features from %s.", repository.getURI());
        }
    }
    return allfeatures.toArray(new Feature[allfeatures.size()]);
}
Also used : Repository(org.apache.karaf.features.Repository) Feature(org.apache.karaf.features.Feature) InvalidComponentException(io.fabric8.api.InvalidComponentException)

Aggregations

Test (org.junit.Test)20 HashMap (java.util.HashMap)18 FabricService (io.fabric8.api.FabricService)15 IOException (java.io.IOException)13 Feature (io.fabric8.agent.model.Feature)12 Container (io.fabric8.api.Container)11 Profile (io.fabric8.api.Profile)11 ArrayList (java.util.ArrayList)11 File (java.io.File)10 Map (java.util.Map)9 BundleContext (org.osgi.framework.BundleContext)9 HashSet (java.util.HashSet)8 URL (java.net.URL)7 BundleException (org.osgi.framework.BundleException)7 Repository (io.fabric8.agent.model.Repository)6 Version (io.fabric8.api.Version)6 LinkedHashSet (java.util.LinkedHashSet)6 Ignore (org.junit.Ignore)6 BundleInfo (io.fabric8.agent.model.BundleInfo)5 ContainerProxy (io.fabric8.itests.paxexam.support.ContainerProxy)5