Search in sources :

Example 76 with Container

use of io.fabric8.maven.docker.model.Container in project fabric8 by jboss-fuse.

the class ContainerLifecycleCommandsTest method testStopGlobMatchingContainers.

@Test
public void testStopGlobMatchingContainers() throws Exception {
    // should stop c2 once
    // should not touch d1
    containers("c*", "c2");
    ContainerImpl c1 = newContainer("c1");
    ContainerImpl c2 = newContainer("c2");
    ContainerImpl c3 = newContainer("c3");
    ContainerImpl d1 = newContainer("d1");
    expect(this.fabricService.getContainers()).andReturn(new Container[] { c1, c3, c2, d1 }).once();
    expect(this.fabricService.adapt(CuratorFramework.class)).andReturn(this.curatorFramework);
    expect(this.fabricService.getContainers()).andReturn(new Container[] { c1, c3, c2, d1 }).once();
    this.fabricService.stopContainer(c1, false);
    expect(this.fabricService.adapt(CuratorFramework.class)).andReturn(this.curatorFramework);
    expect(this.fabricService.getContainers()).andReturn(new Container[] { c1, c3, c2, d1 }).once();
    this.fabricService.stopContainer(c3, false);
    expect(this.fabricService.adapt(CuratorFramework.class)).andReturn(this.curatorFramework);
    expect(this.fabricService.getContainers()).andReturn(new Container[] { c1, c3, c2, d1 }).once();
    this.fabricService.stopContainer(c2, false);
    replay(this.fabricService, this.commandSession);
    this.stop.execute(this.commandSession);
    verify(this.fabricService);
    String result = new String(this.result.toByteArray());
    assertThat(result.contains("Container 'c1' stopped successfully."), is(true));
    assertThat(result.contains("Container 'c2' stopped successfully."), is(true));
    assertThat(result.contains("Container 'c3' stopped successfully."), is(true));
}
Also used : Container(io.fabric8.api.Container) ContainerImpl(io.fabric8.internal.ContainerImpl) Test(org.junit.Test)

Example 77 with Container

use of io.fabric8.maven.docker.model.Container in project fabric8 by jboss-fuse.

the class FabricConfigAdminBridge method updateInternal.

/**
 * Method scheduled to run in separate thread - so be careful, as we may be running in deactivated SCR
 * component.
 * @throws Exception
 */
private synchronized void updateInternal() throws Exception {
    try {
        Container currentContainer = fabricService.get().getCurrentContainer();
        if (currentContainer == null) {
            LOGGER.warn("No current container yet so cannot update!");
            return;
        }
        Profile overlayProfile = null;
        try {
            overlayProfile = currentContainer.getOverlayProfile();
        } catch (RuntimeException e) {
            LOGGER.warn("No profile data yet so cannot update!");
            return;
        }
        Profile effectiveProfile = Profiles.getEffectiveProfile(fabricService.get(), overlayProfile);
        Map<String, Map<String, String>> configurations = effectiveProfile.getConfigurations();
        List<Configuration> zkConfigs = asList(configAdmin.get().listConfigurations("(" + FABRIC_ZOOKEEPER_PID + "=*)"));
        // Process all configurations but agent
        for (String pid : configurations.keySet()) {
            if (!pid.equals(Constants.AGENT_PID)) {
                Hashtable<String, Object> c = new Hashtable<String, Object>(configurations.get(pid));
                if (!updateConfig(zkConfigs, pid, c)) {
                    return;
                }
            }
        }
        // Process agent configuration last
        for (String pid : configurations.keySet()) {
            if (pid.equals(Constants.AGENT_PID)) {
                Hashtable<String, Object> c = new Hashtable<String, Object>(configurations.get(pid));
                c.put(Profile.HASH, String.valueOf(effectiveProfile.getProfileHash()));
                if (!updateConfig(zkConfigs, pid, c)) {
                    return;
                }
            }
        }
        for (Configuration config : zkConfigs) {
            LOGGER.info("Deleting configuration {}", config.getPid());
            fabricService.get().getPortService().unregisterPort(fabricService.get().getCurrentContainer(), config.getPid());
            if (!isValid()) {
                return;
            }
            config.delete();
        }
        // end of update
        Configuration fcab = configAdmin.get().getConfiguration(Constants.CONFIGADMIN_BRIDGE_PID, null);
        Hashtable<String, String> props = new Hashtable<>();
        props.put("lastUpdate", Long.toString(new Date().getTime()));
        fcab.update(props);
    } catch (IllegalStateException e) {
        handleException(e);
    }
}
Also used : Configuration(org.osgi.service.cm.Configuration) Hashtable(java.util.Hashtable) Profile(io.fabric8.api.Profile) Date(java.util.Date) Container(io.fabric8.api.Container) Map(java.util.Map)

Example 78 with Container

use of io.fabric8.maven.docker.model.Container in project fabric8 by jboss-fuse.

the class CloudContainerInstallationTask method install.

public CreateJCloudsContainerMetadata install() {
    LoginCredentials credentials = nodeMetadata.getCredentials();
    // For some cloud providers return do not allow shell access to root, so the user needs to be overrided.
    if (!Strings.isNullOrEmpty(options.getUser()) && credentials != null) {
        credentials = credentials.toBuilder().user(options.getUser()).build();
    } else {
        credentials = nodeMetadata.getCredentials();
    }
    String id = nodeMetadata.getId();
    Set<String> publicAddresses = nodeMetadata.getPublicAddresses();
    // Make a copy of the addresses, because we don't want to return back a guice implementation of Set.
    Set<String> copyOfPublicAddresses = new HashSet<String>();
    for (String publicAddress : publicAddresses) {
        copyOfPublicAddresses.add(publicAddress);
    }
    CreateJCloudsContainerMetadata jCloudsContainerMetadata = new CreateJCloudsContainerMetadata();
    jCloudsContainerMetadata.setCreateOptions(options);
    jCloudsContainerMetadata.setNodeId(nodeMetadata.getId());
    jCloudsContainerMetadata.setContainerName(containerName);
    jCloudsContainerMetadata.setPublicAddresses(copyOfPublicAddresses);
    jCloudsContainerMetadata.setHostname(nodeMetadata.getHostname());
    if (credentials != null) {
        jCloudsContainerMetadata.setIdentity(credentials.identity);
        jCloudsContainerMetadata.setCredential(credentials.credential);
    }
    String publicAddress = "";
    Properties addresses = new Properties();
    if (publicAddresses != null && !publicAddresses.isEmpty()) {
        publicAddress = publicAddresses.iterator().next();
        addresses.put(ZkDefs.PUBLIC_IP, publicAddress);
    }
    options.getSystemProperties().put(ContainerProviderUtils.ADDRESSES_PROPERTY_KEY, addresses);
    options.getMetadataMap().put(containerName, jCloudsContainerMetadata);
    // Setup firwall for node
    try {
        FirewallManager firewallManager = firewallManagerFactory.getFirewallManager(computeService);
        if (firewallManager.isSupported()) {
            listener.onStateChange("Configuring firewall.");
            String source = getOriginatingIp();
            Rule httpRule = Rule.create().source("0.0.0.0/0").destination(nodeMetadata).port(8181);
            firewallManager.addRules(httpRule);
            if (source != null) {
                Rule jmxRule = Rule.create().source(source).destination(nodeMetadata).ports(44444, 1099);
                Rule sshRule = Rule.create().source(source).destination(nodeMetadata).port(8101);
                Rule zookeeperRule = Rule.create().source(source).destination(nodeMetadata).port(2181);
                firewallManager.addRules(jmxRule, sshRule, zookeeperRule);
            }
            // where firewall configuration is shared among nodes of the same groups, e.g. EC2.
            if (!Strings.isNullOrEmpty(publicAddress)) {
                Rule zookeeperFromTargetRule = Rule.create().source(publicAddress + "/32").destination(nodeMetadata).port(2181);
                firewallManager.addRule(zookeeperFromTargetRule);
            }
        } else {
            listener.onStateChange(String.format("Skipping firewall configuration. Not supported for provider %s", options.getProviderName()));
        }
    } catch (FirewallNotSupportedOnProviderException e) {
        LOGGER.warn("Firewall manager not supported. Firewall will have to be manually configured.");
    } catch (IOException e) {
        LOGGER.warn("Could not lookup originating ip. Firewall will have to be manually configured.", e);
    } catch (Throwable t) {
        LOGGER.warn("Failed to setup firewall", t);
    }
    try {
        String script = buildInstallAndStartScript(containerName, options);
        listener.onStateChange(String.format("Installing fabric agent on container %s. It may take a while...", containerName));
        ExecResponse response = null;
        String uploadPath = "/tmp/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip";
        URL distributionURL = options.getProxyUri().resolve("io/fabric8/fabric8-karaf/" + FabricConstants.FABRIC_VERSION + "/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip").toURL();
        try {
            if (options.doUploadDistribution()) {
                uploadToNode(computeService.getContext(), nodeMetadata, credentials, distributionURL, uploadPath);
            }
            if (credentials != null) {
                response = computeService.runScriptOnNode(id, script, templateOptions.overrideLoginCredentials(credentials).runAsRoot(false));
            } else {
                response = computeService.runScriptOnNode(id, script, templateOptions);
            }
        } catch (AuthorizationException ex) {
            throw new Exception("Failed to connect to the container via ssh.");
        } catch (SshException ex) {
            throw new Exception("Failed to connect to the container via ssh.");
        }
        if (response != null && response.getOutput() != null) {
            if (response.getOutput().contains(ContainerProviderUtils.FAILURE_PREFIX)) {
                jCloudsContainerMetadata.setFailure(new Exception(ContainerProviderUtils.parseScriptFailure(response.getOutput())));
            }
            String overridenResolverValue = ContainerProviderUtils.parseResolverOverride(response.getOutput());
            if (overridenResolverValue != null) {
                jCloudsContainerMetadata.setOverridenResolver(overridenResolverValue);
                listener.onStateChange("Overriding resolver to " + overridenResolverValue + ".");
            }
        } else {
            jCloudsContainerMetadata.setFailure(new Exception("No response received for fabric install script."));
        }
    } catch (Throwable t) {
        jCloudsContainerMetadata.setFailure(t);
    }
    // Cleanup addresses.
    options.getSystemProperties().clear();
    return jCloudsContainerMetadata;
}
Also used : FirewallManager(io.fabric8.service.jclouds.firewall.FirewallManager) ExecResponse(org.jclouds.compute.domain.ExecResponse) AuthorizationException(org.jclouds.rest.AuthorizationException) FirewallNotSupportedOnProviderException(io.fabric8.service.jclouds.firewall.FirewallNotSupportedOnProviderException) IOException(java.io.IOException) SshException(org.jclouds.ssh.SshException) Properties(java.util.Properties) URL(java.net.URL) AuthorizationException(org.jclouds.rest.AuthorizationException) FirewallNotSupportedOnProviderException(io.fabric8.service.jclouds.firewall.FirewallNotSupportedOnProviderException) IOException(java.io.IOException) SshException(org.jclouds.ssh.SshException) LoginCredentials(org.jclouds.domain.LoginCredentials) Rule(io.fabric8.service.jclouds.firewall.Rule) HashSet(java.util.HashSet)

Example 79 with Container

use of io.fabric8.maven.docker.model.Container in project fabric8 by jboss-fuse.

the class JcloudsContainerProvider method destroy.

@Override
public void destroy(Container container) {
    assertValid();
    CreateContainerMetadata metadata = container.getMetadata();
    if (!(metadata instanceof CreateJCloudsContainerMetadata)) {
        throw new IllegalStateException("Container doesn't have valid create container metadata type");
    } else {
        container.setProvisionResult(Container.PROVISION_DELETING);
        CreateJCloudsContainerMetadata jCloudsContainerMetadata = (CreateJCloudsContainerMetadata) metadata;
        CreateJCloudsContainerOptions options = jCloudsContainerMetadata.getCreateOptions();
        String nodeId = jCloudsContainerMetadata.getNodeId();
        ComputeService computeService = getOrCreateComputeService(options);
        computeService.destroyNode(nodeId);
    }
}
Also used : CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata) ComputeService(org.jclouds.compute.ComputeService)

Example 80 with Container

use of io.fabric8.maven.docker.model.Container in project fabric8 by jboss-fuse.

the class JcloudsContainerProvider method stop.

@Override
public void stop(Container container) {
    assertValid();
    CreateContainerMetadata metadata = container.getMetadata();
    if (!(metadata instanceof CreateJCloudsContainerMetadata)) {
        throw new IllegalStateException("Container doesn't have valid create container metadata type");
    } else {
        CreateJCloudsContainerMetadata jCloudsContainerMetadata = (CreateJCloudsContainerMetadata) metadata;
        CreateJCloudsContainerOptions options = jCloudsContainerMetadata.getCreateOptions();
        try {
            ComputeService computeService = getOrCreateComputeService(options);
            String nodeId = jCloudsContainerMetadata.getNodeId();
            Optional<RunScriptOptions> runScriptOptions = ToRunScriptOptions.withComputeService(computeService).apply(jCloudsContainerMetadata);
            String script = buildStopScript(container.getId(), options);
            ExecResponse response;
            container.setProvisionResult(Container.PROVISION_STOPPING);
            if (runScriptOptions.isPresent()) {
                response = computeService.runScriptOnNode(nodeId, script, runScriptOptions.get());
            } else {
                response = computeService.runScriptOnNode(nodeId, script);
            }
            if (response == null) {
                jCloudsContainerMetadata.setFailure(new Exception("No response received for fabric install script."));
            } else if (response.getOutput() != null && response.getOutput().contains(ContainerProviderUtils.FAILURE_PREFIX)) {
                jCloudsContainerMetadata.setFailure(new Exception(ContainerProviderUtils.parseScriptFailure(response.getOutput())));
            }
        } catch (Throwable t) {
            container.setProvisionResult(Container.PROVISION_STOPPED);
            jCloudsContainerMetadata.setFailure(t);
        }
    }
}
Also used : RunScriptOptions(org.jclouds.compute.options.RunScriptOptions) ToRunScriptOptions(io.fabric8.service.jclouds.functions.ToRunScriptOptions) ExecResponse(org.jclouds.compute.domain.ExecResponse) CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata) ComputeService(org.jclouds.compute.ComputeService) URISyntaxException(java.net.URISyntaxException) RunNodesException(org.jclouds.compute.RunNodesException) MalformedURLException(java.net.MalformedURLException)

Aggregations

Container (io.fabric8.api.Container)139 Test (org.junit.Test)75 FabricService (io.fabric8.api.FabricService)56 ArrayList (java.util.ArrayList)39 Container (io.fabric8.kubernetes.api.model.Container)38 IOException (java.io.IOException)38 Profile (io.fabric8.api.Profile)37 HashMap (java.util.HashMap)34 Map (java.util.Map)30 FabricException (io.fabric8.api.FabricException)27 BundleContext (org.osgi.framework.BundleContext)24 Version (io.fabric8.api.Version)23 File (java.io.File)23 HashSet (java.util.HashSet)20 LinkedList (java.util.LinkedList)17 PodSpec (io.fabric8.kubernetes.api.model.PodSpec)16 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)16 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)15 Pod (io.fabric8.kubernetes.api.model.Pod)12 List (java.util.List)12