Search in sources :

Example 6 with ContainerProvider

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

the class SshContainerCompleter method getProvider.

private ContainerProvider getProvider(Container container) {
    CreateContainerMetadata metadata = container.getMetadata();
    String type = metadata != null ? metadata.getCreateOptions().getProviderType() : null;
    if (type == null) {
        return null;
    }
    ContainerProvider provider = fabricService.getProvider(type);
    if (provider == null) {
        return null;
    }
    return provider;
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider) CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata)

Example 7 with ContainerProvider

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

the class FabricServiceImpl method destroyContainer.

public void destroyContainer(Container container, boolean force) {
    assertValid();
    String containerId = container.getId();
    Exception providerException = null;
    LOGGER.info("Destroying container {}", containerId);
    boolean destroyed = false;
    try {
        ContainerProvider provider = getProvider(container, true);
        if (provider != null) {
            try {
                provider.stop(container);
            } catch (Exception ex) {
                // Ignore error while stopping and try to destroy.
                // and if its already stopped then ignore the exception and do not rethrow later
                boolean stopped = "Instance already stopped".equals(ex.getMessage());
                if (!stopped) {
                    providerException = ex;
                }
            }
            provider.destroy(container);
            destroyed = true;
        } else {
            throw new FabricException("Container's lifecycle not managed by Fabric8 (the container was not created by Fabric8).");
        }
    } finally {
        try {
            if (destroyed || force) {
                try {
                    portService.get().unregisterPort(container);
                } catch (Exception e) {
                    LOGGER.warn("Failed to cleanup container {} entries due to: {}. This will be ignored.", containerId, e.getMessage());
                }
                dataStore.get().deleteContainer(this, container.getId());
            }
        } catch (Exception e) {
            LOGGER.warn("Failed to cleanup container {} entries due to: {}. This will be ignored.", containerId, e.getMessage());
        }
        if (providerException != null) {
            throw FabricException.launderThrowable(providerException);
        }
    }
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider) FabricException(io.fabric8.api.FabricException) ProfileDependencyException(io.fabric8.api.ProfileDependencyException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException)

Example 8 with ContainerProvider

use of io.fabric8.api.ContainerProvider 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 9 with ContainerProvider

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

the class MQManager method createContainerBuilders.

/**
 * Creates container builders for the given DTO
 */
public static List<CreateContainerBasicOptions.Builder> createContainerBuilders(MQBrokerConfigDTO dto, FabricService fabricService, String containerProviderScheme, String profileId, String version, String[] createContainers) throws IOException {
    ContainerProvider containerProvider = fabricService.getProvider(containerProviderScheme);
    Objects.notNull(containerProvider, "No ContainerProvider available for scheme: " + containerProviderScheme);
    if (!containerProvider.isValidProvider()) {
        throw new IllegalArgumentException("ContainerProvider for scheme: " + containerProviderScheme + " is not valid in current environment");
    }
    List<CreateContainerBasicOptions.Builder> containerBuilders = new ArrayList<CreateContainerBasicOptions.Builder>();
    for (String container : createContainers) {
        String type = null;
        String parent = fabricService.getCurrentContainerName();
        String jvmOpts = dto.getJvmOpts();
        CreateContainerBasicOptions.Builder builder = containerProvider.newBuilder();
        builder = (CreateContainerBasicOptions.Builder) builder.name(container).parent(parent).number(dto.requiredInstances()).ensembleServer(false).proxyUri(fabricService.getMavenRepoURI()).jvmOpts(jvmOpts).zookeeperUrl(fabricService.getZookeeperUrl()).zookeeperPassword(fabricService.getZookeeperPassword()).profiles(profileId).version(version);
        containerBuilders.add(builder);
    }
    return containerBuilders;
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider) ArrayList(java.util.ArrayList) CreateContainerBasicOptions(io.fabric8.api.CreateContainerBasicOptions)

Example 10 with ContainerProvider

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

the class FabricServiceImpl method startContainer.

public void startContainer(Container container, boolean force) {
    assertValid();
    LOGGER.info("Starting container {}", container.getId());
    ContainerProvider provider = getProvider(container);
    provider.start(container);
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider)

Aggregations

ContainerProvider (io.fabric8.api.ContainerProvider)10 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)4 CreateContainerBasicOptions (io.fabric8.api.CreateContainerBasicOptions)3 FabricException (io.fabric8.api.FabricException)3 IOException (java.io.IOException)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 CreateContainerOptions (io.fabric8.api.CreateContainerOptions)2 ProfileDependencyException (io.fabric8.api.ProfileDependencyException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 TreeMap (java.util.TreeMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 EncryptionOperationNotPossibleException (org.jasypt.exceptions.EncryptionOperationNotPossibleException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 Container (io.fabric8.api.Container)1 ContainerAutoScaler (io.fabric8.api.ContainerAutoScaler)1 ContainerAutoScalerFactory (io.fabric8.api.ContainerAutoScalerFactory)1 CreateContainerBasicMetadata (io.fabric8.api.CreateContainerBasicMetadata)1 CreationStateListener (io.fabric8.api.CreationStateListener)1 FabricService (io.fabric8.api.FabricService)1