Search in sources :

Example 6 with CreateContainerOptions

use of io.fabric8.api.CreateContainerOptions in project fabric8 by jboss-fuse.

the class CreateSshContainerTest method testSshContainerProvider.

@Test
public void testSshContainerProvider() throws Throwable {
    Assume.assumeTrue(isReady());
    System.out.println(executeCommand("fabric:create -n --wait-for-provisioning"));
    // System.out.println(executeCommand("shell:info"));
    // System.out.println(executeCommand("fabric:info"));
    // System.out.println(executeCommand("fabric:profile-list"));
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class);
    try {
        FabricService fabricService = fabricProxy.getService();
        CreateContainerOptions options = CreateSshContainerOptions.builder().name("ssh1").host(host).port(Integer.parseInt(port)).username(username).password(password).build();
        CreateContainerMetadata[] metadata = fabricService.createContainers(options);
        assertNotNull(metadata);
        assertEquals(1, metadata.length);
        if (metadata[0].getFailure() != null) {
            throw metadata[0].getFailure();
        }
        assertTrue("Expected successful creation of remote ssh container", metadata[0].isSuccess());
        assertNotNull("Expected successful creation of remote ssh container", metadata[0].getContainer());
        Provision.containersStatus(Arrays.asList(metadata[0].getContainer()), "success", PROVISION_TIMEOUT);
        System.out.println(executeCommand("fabric:container-list -v"));
        System.out.println(executeCommand("fabric:container-resolver-list"));
        Container ssh1 = fabricService.getContainer("ssh1");
        assertTrue(ssh1.isAlive());
        createAndAssertChildContainer(fabricService, "ssh2", "ssh1", "default");
        // Stop & Start Remote Child
        Container ssh2 = fabricService.getContainer("ssh2");
        ssh2.stop();
        assertFalse(ssh2.isAlive());
        ssh2.start();
        Provision.containersStatus(Arrays.asList(ssh2), "success", PROVISION_TIMEOUT);
        assertTrue(ssh2.isAlive());
        ssh2.stop();
        // Try stopping and starting the remote container.
        ssh1.stop();
        assertFalse(ssh1.isAlive());
        System.out.println(executeCommand("fabric:container-list -v"));
        ssh1.start();
        Provision.containersStatus(Arrays.asList(ssh1), "success", PROVISION_TIMEOUT);
        System.out.println(executeCommand("fabric:container-list -v"));
        assertTrue(ssh1.isAlive());
    } finally {
        fabricProxy.close();
    }
}
Also used : Container(io.fabric8.api.Container) FabricService(io.fabric8.api.FabricService) CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata) CreateContainerOptions(io.fabric8.api.CreateContainerOptions) Test(org.junit.Test)

Example 7 with CreateContainerOptions

use of io.fabric8.api.CreateContainerOptions in project fabric8 by jboss-fuse.

the class FabricServiceImpl method createContainers.

@Override
public CreateContainerMetadata[] createContainers(CreateContainerOptions options, CreationStateListener listener) {
    assertValid();
    try {
        final ContainerProvider provider = getProvider(options.getProviderType());
        if (provider == null) {
            throw new FabricException("Unable to find a container provider supporting '" + options.getProviderType() + "'");
        }
        if (!provider.isValidProvider()) {
            throw new FabricException("The provider '" + options.getProviderType() + "' is not valid in current environment");
        }
        String originalName = options.getName();
        if (originalName == null || originalName.length() == 0) {
            throw new FabricException("A name must be specified when creating containers");
        }
        // Only allow containers with valid names to get created.
        FabricValidations.validateContainerName(originalName);
        if (listener == null) {
            listener = new NullCreationStateListener();
        }
        validateProfileDependencies(options);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        Map optionsMap = mapper.readValue(mapper.writeValueAsString(options), Map.class);
        String versionId = options.getVersion() != null ? options.getVersion() : dataStore.get().getDefaultVersion();
        Set<String> profileIds = options.getProfiles();
        if (profileIds == null || profileIds.isEmpty()) {
            profileIds = new LinkedHashSet<String>();
            profileIds.add("default");
        }
        optionsMap.put("version", versionId);
        optionsMap.put("profiles", profileIds);
        optionsMap.put("number", 0);
        // assign parent resolver if it's a child container, else assign global resolver policy
        if (bootstrapConfig != null) {
            String configuredGlobalResolver = bootstrapConfig.getGlobalResolver();
            if (!Strings.isNullOrEmpty(configuredGlobalResolver)) {
                optionsMap.put("globalResolver", configuredGlobalResolver);
                if (optionsMap.get("resolver") == null) {
                    if (optionsMap.get("parent") == null) {
                        optionsMap.put("resolver", configuredGlobalResolver);
                    }
                }
            }
        }
        final List<CreateContainerMetadata> metadatas = new CopyOnWriteArrayList<CreateContainerMetadata>();
        int orgNumber = options.getNumber();
        int number = Math.max(orgNumber, 1);
        if (orgNumber > 1) {
            originalName = originalName + "1";
        }
        final CountDownLatch latch = new CountDownLatch(number);
        Set<String> ignoreContainerNames = new HashSet<>();
        Container[] containers = getContainers();
        // check that there is no container with the given name
        for (Container container : containers) {
            if (container.getId().equals(options.getName())) {
                throw new IllegalArgumentException("A container with name " + options.getName() + " already exists.");
            }
        }
        for (int i = 1; i <= number; i++) {
            NameValidator validator = Containers.createNameValidator(containers, ignoreContainerNames);
            final String containerName = Containers.createUniqueContainerName(containers, originalName, validator);
            ignoreContainerNames.add(containerName);
            optionsMap.put("name", containerName);
            // Check if datastore configuration has been specified and fallback to current container settings.
            if (!hasValidDataStoreProperties(optionsMap)) {
                optionsMap.put("dataStoreProperties", profileRegistry.get().getDataStoreProperties());
            }
            Class cl = options.getClass().getClassLoader().loadClass(options.getClass().getName() + "$Builder");
            CreateContainerBasicOptions.Builder builder = (CreateContainerBasicOptions.Builder) mapper.readValue(mapper.writeValueAsString(optionsMap), cl);
            // We always want to pass the obfuscated version of the password to the container provider.
            builder = (CreateContainerBasicOptions.Builder) builder.zookeeperPassword(PasswordEncoder.encode(getZookeeperPassword()));
            final CreateContainerOptions containerOptions = builder.build();
            final CreationStateListener containerListener = listener;
            final FabricService fabricService = this;
            new Thread("Creating container " + containerName) {

                public void run() {
                    try {
                        if (dataStore.get().hasContainer(containerName)) {
                            CreateContainerBasicMetadata metadata = new CreateContainerBasicMetadata();
                            metadata.setContainerName(containerName);
                            metadata.setCreateOptions(containerOptions);
                            metadata.setFailure(new IllegalArgumentException("A container with name " + containerName + " already exists."));
                            metadatas.add(metadata);
                            return;
                        }
                        dataStore.get().createContainerConfig(containerOptions);
                        CreateContainerMetadata metadata = provider.create(containerOptions, containerListener);
                        if (metadata.isSuccess()) {
                            Container parent = containerOptions.getParent() != null ? getContainer(containerOptions.getParent()) : null;
                            // TODO: We need to make sure that this entries are somehow added even to ensemble servers.
                            if (!containerOptions.isEnsembleServer()) {
                                dataStore.get().createContainerConfig(metadata);
                            }
                            ContainerImpl container = new ContainerImpl(parent, metadata.getContainerName(), FabricServiceImpl.this);
                            metadata.setContainer(container);
                            LOGGER.info("The container " + metadata.getContainerName() + " has been successfully created");
                        } else {
                            LOGGER.warn("The creation of the container " + metadata.getContainerName() + " has failed", metadata.getFailure());
                            dataStore.get().deleteContainer(fabricService, containerOptions.getName());
                        }
                        metadatas.add(metadata);
                    } catch (Throwable t) {
                        CreateContainerBasicMetadata metadata = new CreateContainerBasicMetadata();
                        metadata.setContainerName(containerName);
                        metadata.setCreateOptions(containerOptions);
                        metadata.setFailure(t);
                        metadatas.add(metadata);
                        dataStore.get().deleteContainer(fabricService, containerOptions.getName());
                    } finally {
                        latch.countDown();
                    }
                }
            }.start();
        }
        if (!latch.await(30, TimeUnit.MINUTES)) {
            throw new FabricException("Timeout waiting for container creation");
        }
        return metadatas.toArray(new CreateContainerMetadata[metadatas.size()]);
    } catch (Exception e) {
        LOGGER.error("Failed to create containers " + e, e);
        throw FabricException.launderThrowable(e);
    }
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider) NullCreationStateListener(io.fabric8.api.NullCreationStateListener) NameValidator(io.fabric8.api.NameValidator) ProfileBuilder(io.fabric8.api.ProfileBuilder) FabricException(io.fabric8.api.FabricException) CreateContainerOptions(io.fabric8.api.CreateContainerOptions) Container(io.fabric8.api.Container) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata) CountDownLatch(java.util.concurrent.CountDownLatch) CreateContainerBasicMetadata(io.fabric8.api.CreateContainerBasicMetadata) ProfileDependencyException(io.fabric8.api.ProfileDependencyException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) NullCreationStateListener(io.fabric8.api.NullCreationStateListener) CreationStateListener(io.fabric8.api.CreationStateListener) FabricService(io.fabric8.api.FabricService) ContainerImpl(io.fabric8.internal.ContainerImpl) CreateContainerBasicOptions(io.fabric8.api.CreateContainerBasicOptions) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 8 with CreateContainerOptions

use of io.fabric8.api.CreateContainerOptions in project fabric8 by jboss-fuse.

the class FabricManager method changeCreateOptionsField.

@Override
public void changeCreateOptionsField(String containerId, String field, Object value) {
    CreateContainerMetadata<? extends CreateContainerOptions> metadata = getContainerMetaData(containerId);
    if (metadata == null) {
        return;
    }
    CreateContainerOptions options = metadata.getCreateOptions();
    if (options == null) {
        return;
    }
    ObjectMapper mapper = getObjectMapper();
    JsonNode optionsJson = mapper.convertValue(options, JsonNode.class);
    JsonNode valueJson = mapper.convertValue(value, JsonNode.class);
    ((ObjectNode) optionsJson).put(field, valueJson);
    Object builder = null;
    try {
        builder = options.getClass().getMethod("builder").invoke(null);
    } catch (Exception e) {
        LOG.warn("Failed to get builder when setting " + field + " on container " + containerId, e);
        throw new RuntimeException("Failed to get builder when setting " + field + " on container " + containerId, e);
    }
    builder = mapper.convertValue(optionsJson, builder.getClass());
    CreateContainerOptions newOptions = null;
    try {
        newOptions = (CreateContainerOptions) builder.getClass().getMethod("build").invoke(builder);
    } catch (Exception e) {
        LOG.warn("Failed to build CreatecontainerOptions when setting " + field + " on container " + containerId, e);
        throw new RuntimeException("Failed to build CreatecontainerOptions when setting " + field + " on container " + containerId, e);
    }
    metadata.setCreateOptions(newOptions);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Create container metadata: " + metadata);
    }
    fabricService.adapt(DataStore.class).setContainerMetadata(metadata);
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DataStore(io.fabric8.api.DataStore) CreateContainerOptions(io.fabric8.api.CreateContainerOptions) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MalformedObjectNameException(javax.management.MalformedObjectNameException) FabricException(io.fabric8.api.FabricException) MalformedURLException(java.net.MalformedURLException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Aggregations

CreateContainerOptions (io.fabric8.api.CreateContainerOptions)7 FabricException (io.fabric8.api.FabricException)5 IOException (java.io.IOException)5 Container (io.fabric8.api.Container)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)3 Map (java.util.Map)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ContainerProvider (io.fabric8.api.ContainerProvider)2 CreateContainerBasicMetadata (io.fabric8.api.CreateContainerBasicMetadata)2 CreateContainerBasicOptions (io.fabric8.api.CreateContainerBasicOptions)2 FabricService (io.fabric8.api.FabricService)2 ProfileDependencyException (io.fabric8.api.ProfileDependencyException)2 MalformedURLException (java.net.MalformedURLException)2 HashMap (java.util.HashMap)2 SortedMap (java.util.SortedMap)2 TreeMap (java.util.TreeMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 MalformedObjectNameException (javax.management.MalformedObjectNameException)2 EncryptionOperationNotPossibleException (org.jasypt.exceptions.EncryptionOperationNotPossibleException)2