Search in sources :

Example 1 with CreationStateListener

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

the class OpenshiftContainerProvider method create.

@Override
public CreateOpenshiftContainerMetadata create(CreateOpenshiftContainerOptions options, CreationStateListener listener) throws Exception {
    assertValid();
    IUser user = getOrCreateConnection(options).getUser();
    IDomain domain = getOrCreateDomain(user, options);
    String cartridgeUrl = null;
    Set<String> profiles = options.getProfiles();
    String versionId = options.getVersion();
    Map<String, String> openshiftConfigOverlay = new HashMap<String, String>();
    if (profiles != null && versionId != null) {
        ProfileService profileService = fabricService.get().adapt(ProfileService.class);
        Version version = profileService.getVersion(versionId);
        if (version != null) {
            for (String profileId : profiles) {
                Profile profile = version.getRequiredProfile(profileId);
                if (profile != null) {
                    Profile overlay = profileService.getOverlayProfile(profile);
                    Map<String, String> openshiftConfig = overlay.getConfiguration(OpenShiftConstants.OPENSHIFT_PID);
                    if (openshiftConfig != null) {
                        openshiftConfigOverlay.putAll(openshiftConfig);
                    }
                }
            }
        }
        cartridgeUrl = openshiftConfigOverlay.get("cartridge");
    }
    if (cartridgeUrl == null) {
        cartridgeUrl = defaultCartridgeUrl;
    }
    String[] cartridgeUrls = cartridgeUrl.split(" ");
    LOG.info("Creating cartridges: " + cartridgeUrl);
    String standAloneCartridgeUrl = cartridgeUrls[0];
    StandaloneCartridge cartridge;
    if (standAloneCartridgeUrl.startsWith(PREFIX_CARTRIDGE_ID)) {
        cartridge = new StandaloneCartridge(standAloneCartridgeUrl.substring(PREFIX_CARTRIDGE_ID.length()));
    } else {
        cartridge = new StandaloneCartridge(new URL(standAloneCartridgeUrl));
    }
    String zookeeperUrl = fabricService.get().getZookeeperUrl();
    String zookeeperPassword = fabricService.get().getZookeeperPassword();
    Map<String, String> userEnvVars = null;
    if (!options.isEnsembleServer()) {
        userEnvVars = new HashMap<String, String>();
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_URL", zookeeperUrl);
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_PASSWORD", zookeeperPassword);
        String zkPasswordEncode = System.getProperty("zookeeper.password.encode", "true");
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_PASSWORD_ENCODE", zkPasswordEncode);
        userEnvVars.put("OPENSHIFT_FUSE_CREATED_FROM_FABRIC", "true");
    }
    String initGitUrl = null;
    int timeout = IHttpClient.NO_TIMEOUT;
    ApplicationScale scale = null;
    String containerName = options.getName();
    long t0 = System.currentTimeMillis();
    IApplication application;
    try {
        application = domain.createApplication(containerName, cartridge, scale, new GearProfile(options.getGearProfile()), initGitUrl, timeout, userEnvVars);
    } catch (OpenShiftTimeoutException e) {
        long t1;
        do {
            Thread.sleep(5000);
            domain.refresh();
            application = domain.getApplicationByName(containerName);
            if (application != null) {
                break;
            }
            t1 = System.currentTimeMillis();
        } while (t1 - t0 < TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES));
    }
    LOG.info("Created application " + containerName);
    // now lets add all the embedded cartridges
    List<IEmbeddableCartridge> list = new ArrayList<IEmbeddableCartridge>();
    for (int idx = 1, size = cartridgeUrls.length; idx < size; idx++) {
        String embeddedUrl = cartridgeUrls[idx];
        LOG.info("Adding embedded cartridge: " + embeddedUrl);
        if (embeddedUrl.startsWith(PREFIX_CARTRIDGE_ID)) {
            list.add(new EmbeddableCartridge(embeddedUrl.substring(PREFIX_CARTRIDGE_ID.length())));
        } else {
            list.add(new EmbeddableCartridge(new URL(embeddedUrl)));
        }
    }
    if (!list.isEmpty()) {
        application.addEmbeddableCartridges(list);
    }
    String gitUrl = application.getGitUrl();
    // in case of OpenShiftTimeoutException, application resource doesn't contain getCreationLog().
    // actually this method throws NPE
    CreateOpenshiftContainerMetadata metadata = new CreateOpenshiftContainerMetadata(domain.getId(), application.getUUID(), application.getMessages() == null ? "" : application.getCreationLog(), gitUrl);
    metadata.setContainerName(containerName);
    metadata.setCreateOptions(options);
    return metadata;
}
Also used : HashMap(java.util.HashMap) ApplicationScale(com.openshift.client.ApplicationScale) OpenShiftTimeoutException(com.openshift.client.OpenShiftTimeoutException) ArrayList(java.util.ArrayList) GearProfile(com.openshift.internal.client.GearProfile) Profile(io.fabric8.api.Profile) IGearProfile(com.openshift.client.IGearProfile) URL(java.net.URL) IDomain(com.openshift.client.IDomain) IApplication(com.openshift.client.IApplication) ProfileService(io.fabric8.api.ProfileService) Version(io.fabric8.api.Version) GearProfile(com.openshift.internal.client.GearProfile) IGearProfile(com.openshift.client.IGearProfile) IUser(com.openshift.client.IUser) EmbeddableCartridge(com.openshift.client.cartridge.EmbeddableCartridge) IEmbeddableCartridge(com.openshift.client.cartridge.IEmbeddableCartridge) StandaloneCartridge(com.openshift.client.cartridge.StandaloneCartridge) IEmbeddableCartridge(com.openshift.client.cartridge.IEmbeddableCartridge)

Example 2 with CreationStateListener

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

the class ChildContainerProvider method createKarafContainerController.

private ChildContainerController createKarafContainerController() {
    return new ChildContainerController() {

        @Override
        public CreateChildContainerMetadata create(final CreateChildContainerOptions options, final CreationStateListener listener) {
            final Container parent = fabricService.get().getContainer(options.getParent());
            ContainerTemplate containerTemplate = new ContainerTemplate(parent, options.getJmxUser(), options.getJmxPassword(), false);
            return containerTemplate.execute(new ContainerTemplate.AdminServiceCallback<CreateChildContainerMetadata>() {

                public CreateChildContainerMetadata doWithAdminService(AdminServiceMBean adminService) throws Exception {
                    return doCreateKaraf(adminService, options, listener, parent);
                }
            });
        }

        @Override
        public void start(final Container container) {
            getContainerTemplateForChild(container).execute(new ContainerTemplate.AdminServiceCallback<Object>() {

                public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
                    // update jvm options if they have have changed
                    CreateChildContainerMetadata metadata = (CreateChildContainerMetadata) container.getMetadata();
                    CreateChildContainerOptions createOptions = metadata.getCreateOptions();
                    String jvmOpts = createOptions.getJvmOpts();
                    TabularData instances = adminService.getInstances();
                    Collection<CompositeDataSupport> values = (Collection<CompositeDataSupport>) instances.values();
                    for (CompositeDataSupport o : values) {
                        if (container.getId().equals(o.get("Name"))) {
                            if (o.containsKey("JavaOpts")) {
                                String oldJavaOpts = (String) o.get("JavaOpts");
                                StringBuilder stringBuilder = ChildContainerProvider.buildJvmOpts(createOptions, fabricService.get());
                                String extendendJvmOpts = stringBuilder.toString();
                                if (jvmOpts != null && !extendendJvmOpts.equals(oldJavaOpts)) {
                                    adminService.changeJavaOpts(container.getId(), extendendJvmOpts);
                                }
                            }
                            break;
                        }
                    }
                    adminService.startInstance(container.getId(), null);
                    return null;
                }
            });
        }

        @Override
        public void stop(final Container container) {
            getContainerTemplateForChild(container).execute(new ContainerTemplate.AdminServiceCallback<Object>() {

                public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
                    String prevProvisionResult = container.getProvisionResult();
                    container.setProvisionResult(Container.PROVISION_STOPPING);
                    try {
                        adminService.stopInstance(container.getId());
                        container.setProvisionResult(Container.PROVISION_STOPPED);
                    } catch (Throwable t) {
                        container.setProvisionResult(prevProvisionResult);
                        LOG.error("Failed to stop container: " + container.getId(), t);
                        throw t;
                    }
                    return null;
                }
            });
        }

        @Override
        public void destroy(final Container container) {
            getContainerTemplateForChild(container).execute(new ContainerTemplate.AdminServiceCallback<Object>() {

                public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
                    adminService.destroyInstance(container.getId());
                    return null;
                }
            });
        }
    };
}
Also used : CompositeDataSupport(javax.management.openmbean.CompositeDataSupport) AdminServiceMBean(org.apache.karaf.admin.management.AdminServiceMBean) TabularData(javax.management.openmbean.TabularData) ContainerTemplate(io.fabric8.service.ContainerTemplate) Collection(java.util.Collection)

Example 3 with CreationStateListener

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

the class JcloudsContainerProvider method create.

@Override
public CreateJCloudsContainerMetadata create(CreateJCloudsContainerOptions input, CreationStateListener listener) throws MalformedURLException, RunNodesException, URISyntaxException, InterruptedException {
    assertValid();
    CreateJCloudsContainerOptions options = input.updateComputeService(getOrCreateComputeService(input));
    listener.onStateChange("Looking up for compute service.");
    ComputeService computeService = getOrCreateComputeService(options);
    if (computeService == null) {
        throw new IllegalStateException("Compute service could not be found or created.");
    }
    Template template = ToTemplate.apply(options);
    listener.onStateChange(String.format(OVERVIEW_FORMAT, 1, options.getContextName()));
    try {
        Set<? extends NodeMetadata> metadata = computeService.createNodesInGroup(options.getGroup(), 1, template);
        if (metadata == null || metadata.size() != 1) {
            throw new IllegalStateException("JClouds created " + metadata.size() + " containers instead of 1");
        }
        NodeMetadata nodeMetadata = metadata.iterator().next();
        switch(nodeMetadata.getStatus()) {
            case RUNNING:
                listener.onStateChange(String.format(NODE_CREATED_FORMAT, nodeMetadata.getName()));
                break;
            default:
                listener.onStateChange(String.format(NODE_ERROR_FORMAT, nodeMetadata.getStatus()));
        }
        CloudContainerInstallationTask installationTask = new CloudContainerInstallationTask(options.getName(), nodeMetadata, options, computeService, firewallManagerFactory.get(), template.getOptions(), listener);
        return installationTask.install();
    } catch (Throwable ex) {
        CreateJCloudsContainerMetadata failureMetadata = new CreateJCloudsContainerMetadata();
        failureMetadata.setCreateOptions(options);
        failureMetadata.setFailure(ex);
        return failureMetadata;
    }
}
Also used : NodeMetadata(org.jclouds.compute.domain.NodeMetadata) ComputeService(org.jclouds.compute.ComputeService) ToTemplate(io.fabric8.service.jclouds.functions.ToTemplate) Template(org.jclouds.compute.domain.Template)

Example 4 with CreationStateListener

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

the class SshContainerProvider method create.

/**
 * Creates an {@link io.fabric8.api.Container} with the given name pointing to the specified zooKeeperUrl.
 */
public CreateSshContainerMetadata create(CreateSshContainerOptions options, CreationStateListener listener) {
    try {
        String path = options.getPath();
        String host = options.getHost();
        String ip = InetAddress.getByName(host).getHostAddress();
        if (host == null) {
            throw new IllegalArgumentException("Host name not specified.");
        }
        int port = options.getPort();
        if (port == -1) {
            port = 22;
        }
        String containerName = options.getName();
        CreateSshContainerMetadata metadata = new CreateSshContainerMetadata();
        metadata.setCreateOptions(options);
        metadata.setContainerName(containerName);
        String script = buildInstallAndStartScript(containerName, options);
        LOGGER.debug("Running script on host {}:\n{}", host, script);
        Session session = null;
        try {
            session = createSession(options);
            if (options.doUploadDistribution()) {
                uploadTo(session, options.getProxyUri().resolve("io/fabric8/fabric8-karaf/" + FabricConstants.FABRIC_VERSION + "/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip").toURL(), "/tmp/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip");
            }
            runScriptOnHost(session, script);
        } catch (Throwable ex) {
            metadata.setFailure(ex);
            throw new FabricException(ex);
        } finally {
            if (session != null) {
                session.disconnect();
            }
        }
        return metadata;
    } catch (Exception e) {
        throw FabricException.launderThrowable(e);
    }
}
Also used : FabricException(io.fabric8.api.FabricException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) Session(com.jcraft.jsch.Session)

Example 5 with CreationStateListener

use of io.fabric8.api.CreationStateListener 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)

Aggregations

FabricException (io.fabric8.api.FabricException)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Session (com.jcraft.jsch.Session)1 ApplicationScale (com.openshift.client.ApplicationScale)1 IApplication (com.openshift.client.IApplication)1 IDomain (com.openshift.client.IDomain)1 IGearProfile (com.openshift.client.IGearProfile)1 IUser (com.openshift.client.IUser)1 OpenShiftTimeoutException (com.openshift.client.OpenShiftTimeoutException)1 EmbeddableCartridge (com.openshift.client.cartridge.EmbeddableCartridge)1 IEmbeddableCartridge (com.openshift.client.cartridge.IEmbeddableCartridge)1 StandaloneCartridge (com.openshift.client.cartridge.StandaloneCartridge)1 GearProfile (com.openshift.internal.client.GearProfile)1 Container (io.fabric8.api.Container)1 ContainerProvider (io.fabric8.api.ContainerProvider)1 CreateContainerBasicMetadata (io.fabric8.api.CreateContainerBasicMetadata)1 CreateContainerBasicOptions (io.fabric8.api.CreateContainerBasicOptions)1 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)1