Search in sources :

Example 1 with Resolver

use of io.fabric8.patch.management.conflicts.Resolver in project fabric8 by jboss-fuse.

the class JoinAction method doExecute.

@Override
protected Object doExecute() throws Exception {
    if (nonManaged) {
        profile = "unmanaged";
    }
    String oldName = runtimeProperties.getRuntimeIdentity();
    if (System.getenv("OPENSHIFT_BROKER_HOST") != null && containerName != null) {
        System.err.println("Containers in OpenShift cannot be renamed");
        return null;
    }
    if (containerName == null) {
        containerName = oldName;
    }
    FabricValidations.validateContainerName(containerName);
    Configuration bootConfiguration = configAdmin.getConfiguration(BootstrapConfiguration.COMPONENT_PID, null);
    Configuration dataStoreConfiguration = configAdmin.getConfiguration(Constants.DATASTORE_PID, null);
    Configuration configZook = configAdmin.getConfiguration(Constants.ZOOKEEPER_CLIENT_PID, null);
    if (configZook.getProperties() != null && configZook.getProperties().get("zookeeper.url") != null) {
        System.err.println("This container is already connected to a fabric");
        return null;
    }
    Dictionary<String, Object> bootProperties = bootConfiguration.getProperties();
    if (bootProperties == null) {
        bootProperties = new Hashtable<>();
    }
    if (resolver != null) {
        bootProperties.put(ZkDefs.LOCAL_RESOLVER_PROPERTY, resolver);
    }
    if (manualIp != null) {
        bootProperties.put(ZkDefs.MANUAL_IP, manualIp);
    }
    if (bindAddress != null) {
        bootProperties.put(ZkDefs.BIND_ADDRESS, bindAddress);
    }
    zookeeperPassword = zookeeperPassword != null ? zookeeperPassword : ShellUtils.retrieveFabricZookeeperPassword(session);
    if (zookeeperPassword == null) {
        zookeeperPassword = promptForZookeeperPassword();
    }
    if (zookeeperPassword == null || zookeeperPassword.isEmpty()) {
        System.out.println("No password specified. Cannot join fabric ensemble.");
        return null;
    }
    ShellUtils.storeZookeeperPassword(session, zookeeperPassword);
    log.debug("Encoding ZooKeeper password.");
    String encodedPassword = PasswordEncoder.encode(zookeeperPassword);
    bootProperties.put(ZkDefs.MINIMUM_PORT, String.valueOf(minimumPort));
    bootProperties.put(ZkDefs.MAXIMUM_PORT, String.valueOf(maximumPort));
    Hashtable<String, Object> dataStoreProperties = new Hashtable<String, Object>();
    Configuration cfg = configAdmin.getConfiguration(Constants.DATASTORE_PID, null);
    Dictionary<String, Object> props = cfg.getProperties();
    if (props != null) {
        for (Enumeration<String> keys = cfg.getProperties().keys(); keys.hasMoreElements(); ) {
            String k = keys.nextElement();
            dataStoreProperties.put(k, cfg.getProperties().get(k));
        }
    }
    augmentDataStoreProperties(zookeeperPassword, dataStoreProperties);
    if (!containerName.equals(oldName)) {
        if (force || permissionToRenameContainer()) {
            if (!registerContainer(containerName, zookeeperPassword, profile, force)) {
                System.err.println("A container with the name: " + containerName + " is already member of the cluster. You can specify a different name as an argument.");
                return null;
            }
            bootProperties.put(SystemProperties.KARAF_NAME, containerName);
            // Ensure that if we bootstrap CuratorFramework via RuntimeProperties password is set before the URL.
            bootProperties.put("zookeeper.password", encodedPassword);
            bootProperties.put("zookeeper.url", zookeeperUrl);
            // Rename the container
            Path propsPath = runtimeProperties.getConfPath().resolve("system.properties");
            Properties systemProps = new Properties(propsPath.toFile());
            systemProps.put(SystemProperties.KARAF_NAME, containerName);
            // Also pass zookeeper information so that the container can auto-join after the restart.
            systemProps.put("zookeeper.url", zookeeperUrl);
            systemProps.put("zookeeper.password", encodedPassword);
            systemProps.save();
            System.setProperty("runtime.id", containerName);
            System.setProperty(SystemProperties.KARAF_NAME, containerName);
            System.setProperty("karaf.restart", "true");
            System.setProperty("karaf.restart.clean", "false");
            if (!nonManaged) {
                installBundles();
            }
            // it's only a(n almost certain) way of synchronizing CM and ManagedService.update()
            if (!OsgiUtils.updateCmConfigurationAndWait(bundleContext, bootConfiguration, bootProperties, 10, TimeUnit.SECONDS)) {
                log.warn("Timeout waiting for update of PID: {}", BootstrapConfiguration.COMPONENT_PID);
            }
            if (!OsgiUtils.updateCmConfigurationAndWait(bundleContext, dataStoreConfiguration, dataStoreProperties, 10, TimeUnit.SECONDS)) {
                log.warn("Timeout waiting for update of PID: {}", Constants.DATASTORE_PID);
            }
            // we don't want fileinstall to trigger ConfigAdmin update
            Bundle fileinstall = new BundleUtils(bundleContext).findBundle("org.apache.felix.fileinstall");
            if (fileinstall != null) {
                fileinstall.stop(Bundle.STOP_TRANSIENT);
            }
            persistConfiguration(configAdmin, Constants.DATASTORE_PID, dataStoreProperties);
            // Restart the container
            bundleContext.getBundle(0).stop();
            return null;
        } else {
            return null;
        }
    } else {
        bootConfiguration.update(bootProperties);
        dataStoreConfiguration.update(dataStoreProperties);
        persistConfiguration(configAdmin, Constants.DATASTORE_PID, dataStoreProperties);
        if (!registerContainer(containerName, zookeeperPassword, profile, force)) {
            System.err.println("A container with the name: " + containerName + " is already member of the cluster. You can specify a different name as an argument.");
            return null;
        }
        Configuration config = configAdmin.getConfiguration(Constants.ZOOKEEPER_CLIENT_PID, null);
        Hashtable<String, Object> properties = new Hashtable<String, Object>();
        properties.put("zookeeper.url", zookeeperUrl);
        properties.put("zookeeper.password", PasswordEncoder.encode(encodedPassword));
        config.setBundleLocation(null);
        config.update(properties);
        if (!nonManaged) {
            installBundles();
        }
        return null;
    }
}
Also used : ZkPath(io.fabric8.zookeeper.ZkPath) Path(java.nio.file.Path) Configuration(org.osgi.service.cm.Configuration) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) Hashtable(java.util.Hashtable) Bundle(org.osgi.framework.Bundle) SystemProperties(io.fabric8.api.SystemProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) Properties(org.apache.felix.utils.properties.Properties) BundleUtils(io.fabric8.utils.BundleUtils)

Example 2 with Resolver

use of io.fabric8.patch.management.conflicts.Resolver in project fabric8 by jboss-fuse.

the class Activator method updated.

public void updated(Dictionary<String, ?> config) {
    PropertyResolver propertyResolver;
    if (config == null) {
        propertyResolver = new PropertyResolver() {

            @Override
            public String get(String propertyName) {
                return m_bundleContext.getProperty(propertyName);
            }
        };
    } else {
        propertyResolver = new DictionaryPropertyResolver(config);
    }
    MavenConfiguration mavenConfig = new MavenConfigurationImpl(propertyResolver, PID);
    MavenResolver resolver = new AetherBasedResolver(mavenConfig);
    MavenResolver oldResolver = m_resolver.getAndSet(resolver);
    ServiceRegistration<MavenResolver> registration = m_bundleContext.registerService(MavenResolver.class, resolver, null);
    registration = m_resolverReg.getAndSet(registration);
    if (registration != null) {
        registration.unregister();
    }
    if (oldResolver != null) {
        try {
            oldResolver.close();
        } catch (IOException e) {
        // Ignore
        }
    }
}
Also used : MavenConfiguration(io.fabric8.maven.util.MavenConfiguration) MavenConfigurationImpl(io.fabric8.maven.util.MavenConfigurationImpl) MavenResolver(io.fabric8.maven.MavenResolver) DictionaryPropertyResolver(org.ops4j.util.property.DictionaryPropertyResolver) IOException(java.io.IOException) PropertyResolver(org.ops4j.util.property.PropertyResolver) DictionaryPropertyResolver(org.ops4j.util.property.DictionaryPropertyResolver)

Example 3 with Resolver

use of io.fabric8.patch.management.conflicts.Resolver in project fabric8 by jboss-fuse.

the class ProjectDeployerImpl method resolveProfileDeployments.

private DeployResults resolveProfileDeployments(ProjectRequirements requirements, FabricService fabric, Profile profile, ProfileBuilder builder, boolean mergeWithOldProfile) throws Exception {
    DependencyDTO rootDependency = requirements.getRootDependency();
    ProfileService profileService = fabricService.get().adapt(ProfileService.class);
    if (!mergeWithOldProfile) {
        // If we're not merging with the old profile, then create a dummy empty profile to merge with instead.
        ProfileBuilder emptyProfile = ProfileBuilder.Factory.create(profile.getVersion(), profile.getId()).setOverlay(true);
        profile = emptyProfile.getProfile();
    }
    if (rootDependency != null) {
        // as a hack lets just add this bundle in
        LOG.info("Got root: " + rootDependency);
        List<String> parentIds = profile.getParentIds();
        Profile overlay = profileService.getOverlayProfile(profile);
        String bundleUrl = rootDependency.toBundleUrlWithType();
        LOG.info("Using resolver to add extra features and bundles on " + bundleUrl);
        List<String> features = new ArrayList<String>(profile.getFeatures());
        List<String> bundles = new ArrayList<String>(profile.getBundles());
        List<String> optionals = new ArrayList<String>(profile.getOptionals());
        if (requirements.getFeatures() != null) {
            features.addAll(requirements.getFeatures());
        }
        if (requirements.getBundles() != null) {
            bundles.addAll(requirements.getBundles());
        }
        bundles.add(bundleUrl);
        LOG.info("Adding bundle: " + bundleUrl);
        // TODO we maybe should detect a karaf based container in a nicer way than this?
        boolean isKarafContainer = parentIds.contains("karaf") || parentIds.contains("containers-karaf");
        boolean addBundleDependencies = Objects.equal("bundle", rootDependency.getType()) || isKarafContainer;
        if (addBundleDependencies && requirements.isUseResolver()) {
            // lets build up a list of all current active features and bundles along with all discovered features
            List<Feature> availableFeatures = new ArrayList<Feature>();
            addAvailableFeaturesFromProfile(availableFeatures, fabric, overlay);
            Set<String> currentBundleLocations = new HashSet<>();
            currentBundleLocations.addAll(bundles);
            // lets add the current features
            DownloadManager downloadManager = DownloadManagers.createDownloadManager(fabric, executorService);
            Set<Feature> currentFeatures = AgentUtils.getFeatures(fabric, downloadManager, overlay);
            addBundlesFromProfile(currentBundleLocations, overlay);
            List<String> parentProfileIds = requirements.getParentProfiles();
            if (parentProfileIds != null) {
                for (String parentProfileId : parentProfileIds) {
                    Profile parentProfile = profileService.getProfile(profile.getVersion(), parentProfileId);
                    Profile parentOverlay = profileService.getOverlayProfile(parentProfile);
                    Set<Feature> parentFeatures = AgentUtils.getFeatures(fabric, downloadManager, parentOverlay);
                    currentFeatures.addAll(parentFeatures);
                    addAvailableFeaturesFromProfile(availableFeatures, fabric, parentOverlay);
                    addBundlesFromProfile(currentBundleLocations, parentOverlay);
                }
            }
            // lets add all known features from the known repositories
            for (DependencyDTO dependency : rootDependency.getChildren()) {
                if ("test".equals(dependency.getScope()) || "provided".equals(dependency.getScope())) {
                    continue;
                }
                if ("jar".equals(dependency.getType())) {
                    String match = getAllServiceMixBundles().get(dependency.getGroupId() + ":" + dependency.getArtifactId() + ":" + dependency.getVersion());
                    if (match != null) {
                        LOG.info("Replacing artifact " + dependency + " with servicemix bundle " + match);
                        String[] parts = match.split(":");
                        dependency.setGroupId(parts[0]);
                        dependency.setArtifactId(parts[1]);
                        dependency.setVersion(parts[2]);
                        dependency.setType("bundle");
                    }
                }
                String prefix = dependency.toBundleUrlWithoutVersion();
                Feature feature = findFeatureWithBundleLocationPrefix(currentFeatures, prefix);
                if (feature != null) {
                    LOG.info("Feature is already is in the profile " + feature.getId() + " for " + dependency.toBundleUrl());
                } else {
                    feature = findFeatureWithBundleLocationPrefix(availableFeatures, prefix);
                    if (feature != null) {
                        String name = feature.getName();
                        if (features.contains(name)) {
                            LOG.info("Feature is already added " + name + " for " + dependency.toBundleUrl());
                        } else {
                            LOG.info("Found a matching feature for bundle " + dependency.toBundleUrl() + ": " + feature.getId());
                            features.add(name);
                        }
                    } else {
                        String bundleUrlWithType = dependency.toBundleUrlWithType();
                        String foundBundleUri = findBundleUri(currentBundleLocations, prefix);
                        if (foundBundleUri != null) {
                            LOG.info("Bundle already included " + foundBundleUri + " for " + bundleUrlWithType);
                        } else {
                            boolean ignore = false;
                            String bundleWithoutMvnPrefix = getMavenCoords(bundleUrlWithType);
                            for (String ignoreBundlePrefix : RESOLVER_IGNORE_BUNDLE_PREFIXES) {
                                if (bundleWithoutMvnPrefix.startsWith(ignoreBundlePrefix)) {
                                    ignore = true;
                                    break;
                                }
                            }
                            if (ignore) {
                                LOG.info("Ignoring bundle: " + bundleUrlWithType);
                            } else {
                                boolean optional = dependency.isOptional();
                                LOG.info("Adding " + (optional ? "optional " : "") + " bundle: " + bundleUrlWithType);
                                if (optional) {
                                    optionals.add(bundleUrlWithType);
                                } else {
                                    bundles.add(bundleUrlWithType);
                                }
                            }
                        }
                    }
                }
            }
            // Modify the profile through the {@link ProfileBuilder}
            builder.setOptionals(optionals).setFeatures(features);
        }
        builder.setBundles(bundles);
    }
    profile = profileService.updateProfile(builder.getProfile());
    Integer minimumInstances = requirements.getMinimumInstances();
    if (minimumInstances != null) {
        FabricRequirements fabricRequirements = fabricService.get().getRequirements();
        ProfileRequirements profileRequirements = fabricRequirements.getOrCreateProfileRequirement(profile.getId());
        profileRequirements.setMinimumInstances(minimumInstances);
        fabricRequirements.setVersion(requirements.getVersion());
        fabricService.get().setRequirements(fabricRequirements);
    }
    // lets find a hawtio profile and version
    String profileUrl = findHawtioUrl(fabric);
    if (profileUrl == null) {
        profileUrl = "/";
    }
    if (!profileUrl.endsWith("/")) {
        profileUrl += "/";
    }
    String profilePath = Profiles.convertProfileIdToPath(profile.getId());
    profileUrl += "index.html#/wiki/branch/" + profile.getVersion() + "/view/fabric/profiles/" + profilePath;
    return new DeployResults(profile, profileUrl);
}
Also used : ProfileRequirements(io.fabric8.api.ProfileRequirements) DeployResults(io.fabric8.deployer.dto.DeployResults) ArrayList(java.util.ArrayList) DependencyDTO(io.fabric8.deployer.dto.DependencyDTO) ProfileBuilder(io.fabric8.api.ProfileBuilder) Feature(io.fabric8.agent.model.Feature) DownloadManager(io.fabric8.agent.download.DownloadManager) Profile(io.fabric8.api.Profile) ProfileService(io.fabric8.api.ProfileService) FabricRequirements(io.fabric8.api.FabricRequirements) HashSet(java.util.HashSet)

Example 4 with Resolver

use of io.fabric8.patch.management.conflicts.Resolver in project fabric8 by jboss-fuse.

the class AetherResolutionWithHintsTest method hintedResolution.

@Test
public void hintedResolution() throws Exception {
    final MavenConfigurationImpl mavenConfiguration = mavenConfiguration();
    mavenConfiguration.setSettings(settingsWithProxy());
    MavenResolver resolver = new AetherBasedResolver(mavenConfiguration);
    try {
        resolver.download("mvn:org.ops4j.pax.web/pax-web-api/1");
        fail("Resolution should fail");
    } catch (IOException e) {
        RepositoryException exception = ((AetherBasedResolver) resolver).findAetherException(e);
        assertNotNull(exception);
        assertTrue(exception instanceof ArtifactResolutionException);
        ArtifactResolutionException are = (ArtifactResolutionException) exception;
        assertThat(are.getResult().getExceptions().size(), equalTo(3));
        assertTrue("Non-retryable exception", are.getResult().getExceptions().get(0) instanceof ArtifactNotFoundException);
        assertTrue("Non-retryable exception", are.getResult().getExceptions().get(1) instanceof ArtifactNotFoundException);
        assertTrue("Retryable exception", are.getResult().getExceptions().get(2) instanceof ArtifactTransferException);
        assertFalse("Retryable exception", are.getResult().getExceptions().get(2) instanceof ArtifactNotFoundException);
        try {
            // try again with exception hint
            resolver.download("mvn:org.ops4j.pax.web/pax-web-api/1", e);
            fail("Resolution should fail");
        } catch (IOException e2) {
            exception = ((AetherBasedResolver) resolver).findAetherException(e2);
            assertNotNull(exception);
            assertTrue(exception instanceof ArtifactResolutionException);
            are = (ArtifactResolutionException) exception;
            assertThat(are.getResult().getExceptions().size(), equalTo(1));
            assertTrue("Retryable exception", are.getResult().getExceptions().get(0) instanceof ArtifactTransferException);
            assertFalse("Retryable exception", are.getResult().getExceptions().get(0) instanceof ArtifactNotFoundException);
        }
    } finally {
        resolver.close();
    }
}
Also used : ArtifactResolutionException(org.eclipse.aether.resolution.ArtifactResolutionException) MavenConfigurationImpl(io.fabric8.maven.util.MavenConfigurationImpl) ArtifactTransferException(org.eclipse.aether.transfer.ArtifactTransferException) MavenResolver(io.fabric8.maven.MavenResolver) RepositoryException(org.eclipse.aether.RepositoryException) IOException(java.io.IOException) ArtifactNotFoundException(org.eclipse.aether.transfer.ArtifactNotFoundException) Test(org.junit.Test)

Example 5 with Resolver

use of io.fabric8.patch.management.conflicts.Resolver in project fabric8 by jboss-fuse.

the class ContainerResolverSetAction method doExecute.

@Override
protected Object doExecute() throws Exception {
    if (containerIds == null || containerIds.isEmpty()) {
        if (all) {
            containerIds = new ArrayList<String>();
            for (Container container : fabricService.getContainers()) {
                containerIds.add(container.getId());
            }
        } else {
            System.out.println("No container has been specified. Assuming the current container.");
            containerIds = Arrays.asList(fabricService.getCurrentContainer().getId());
        }
    } else {
        if (all) {
            throw new IllegalArgumentException("Can not use --all with a list of containers simultaneously.");
        }
    }
    for (String containerId : containerIds) {
        Container container = fabricService.getContainer(containerId);
        container.setResolver(resolver);
        if (resolver.equalsIgnoreCase("manualip")) {
            if (manualIp != null && !manualIp.isEmpty()) {
                setData(getCurator(), ZkPath.CONTAINER_MANUAL_IP.getPath(containerId), manualIp);
            }
        }
    }
    return null;
}
Also used : Container(io.fabric8.api.Container)

Aggregations

File (java.io.File)23 MavenResolver (io.fabric8.maven.MavenResolver)22 Test (org.junit.Test)21 IOException (java.io.IOException)20 FabricService (io.fabric8.api.FabricService)10 Container (io.fabric8.api.Container)9 RuntimeProperties (io.fabric8.api.RuntimeProperties)7 HashMap (java.util.HashMap)7 PlaceholderResolver (io.fabric8.api.PlaceholderResolver)6 HashSet (java.util.HashSet)6 Hashtable (java.util.Hashtable)6 Metadata (org.apache.maven.artifact.repository.metadata.Metadata)6 Map (java.util.Map)5 DownloadManager (io.fabric8.agent.download.DownloadManager)4 AbstractRuntimeProperties (io.fabric8.api.scr.AbstractRuntimeProperties)4 MavenConfigurationImpl (io.fabric8.maven.util.MavenConfigurationImpl)4 FileInputStream (java.io.FileInputStream)4 URI (java.net.URI)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4