Search in sources :

Example 21 with Config

use of io.fabric8.docker.client.Config in project fabric8 by jboss-fuse.

the class FabricServiceImpl method getZookeeperInfo.

// FIXME public access on the impl
public String getZookeeperInfo(String name) {
    assertValid();
    String zooKeeperUrl = null;
    // Also this is required for the integration with the IDE.
    try {
        if (curator.get().getZookeeperClient().isConnected()) {
            Version defaultVersion = getDefaultVersion();
            if (defaultVersion != null) {
                Profile profile = defaultVersion.getRequiredProfile("default");
                if (profile != null) {
                    Map<String, String> zookeeperConfig = profile.getConfiguration(Constants.ZOOKEEPER_CLIENT_PID);
                    if (zookeeperConfig != null) {
                        zooKeeperUrl = getSubstitutedData(curator.get(), zookeeperConfig.get(name));
                    }
                }
            }
        }
    } catch (Exception e) {
    // Ignore it.
    }
    if (zooKeeperUrl == null) {
        try {
            Configuration config = configAdmin.get().getConfiguration(Constants.ZOOKEEPER_CLIENT_PID, null);
            zooKeeperUrl = (String) config.getProperties().get(name);
        } catch (Exception e) {
        // Ignore it.
        }
    }
    return zooKeeperUrl;
}
Also used : BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) Configuration(org.osgi.service.cm.Configuration) Version(io.fabric8.api.Version) Profile(io.fabric8.api.Profile) ProfileDependencyException(io.fabric8.api.ProfileDependencyException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException)

Example 22 with Config

use of io.fabric8.docker.client.Config in project fabric8 by jboss-fuse.

the class FabricServiceImpl method validateProfileDependencies.

protected void validateProfileDependencies(CreateContainerOptions options) {
    Map<String, Map<String, String>> profileDependencies = Profiles.getOverlayFactoryConfigurations(this, options.getProfiles(), options.getVersion(), ProfileDependencyConfig.PROFILE_DEPENDENCY_CONFIG_PID);
    Set<Map.Entry<String, Map<String, String>>> entries = profileDependencies.entrySet();
    for (Map.Entry<String, Map<String, String>> entry : entries) {
        String configName = entry.getKey();
        Map<String, String> exportConfig = entry.getValue();
        if (exportConfig != null && !exportConfig.isEmpty()) {
            ProfileDependencyConfig config = new ProfileDependencyConfig();
            try {
                configurer.configure(exportConfig, config);
            } catch (Exception e) {
                throw new FabricException("Failed to load configuration for " + configName + " of " + config + " due to: " + e, e);
            }
            // Ensure dependent container exists
            if (ProfileDependencyKind.ZOOKEEPER_SERVICE.equals(config.getKind())) {
                try {
                    List<String> children = getChildren(this.curator.get(), config.getZookeeperPath());
                    if (children == null || children.isEmpty()) {
                        throw new ProfileDependencyException(options.getProfiles(), config.getProfileWildcards(), config.getProfileTags(), config.getSummary());
                    }
                    boolean dependencyFound = false;
                    Iterator<String> childIterator = children.iterator();
                    while (!dependencyFound && childIterator.hasNext()) {
                        String containerName = childIterator.next();
                        Container container = this.getContainer(containerName);
                        Profile[] profiles = container.getProfiles();
                        int profileCount = 0;
                        while (!dependencyFound && profileCount < profiles.length) {
                            Profile profile = profiles[profileCount];
                            if (config.getProfileWildcards() != null) {
                                for (String profileWildcard : config.getProfileWildcards()) {
                                    if (profile.getId().contains(profileWildcard)) {
                                        dependencyFound = true;
                                        break;
                                    }
                                }
                            }
                            if (!dependencyFound && config.getProfileTags() != null) {
                                List<String> profileTags = profile.getTags();
                                int foundTags = 0;
                                for (String configProfileTag : config.getProfileTags()) {
                                    if (profileTags.contains(configProfileTag)) {
                                        foundTags++;
                                    }
                                }
                                if (foundTags == config.getProfileTags().length) {
                                    dependencyFound = true;
                                }
                            }
                        }
                    }
                    if (!dependencyFound) {
                        throw new ProfileDependencyException(options.getProfiles(), config.getProfileWildcards(), config.getProfileTags(), config.getSummary());
                    }
                } catch (Exception e) {
                    throw new ProfileDependencyException(options.getProfiles(), config.getProfileWildcards(), config.getProfileTags(), config.getSummary(), e);
                }
            }
        }
    }
}
Also used : ProfileDependencyException(io.fabric8.api.ProfileDependencyException) FabricException(io.fabric8.api.FabricException) ProfileDependencyException(io.fabric8.api.ProfileDependencyException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) Profile(io.fabric8.api.Profile) Entry(java.util.Map.Entry) Container(io.fabric8.api.Container) ProfileDependencyConfig(io.fabric8.internal.ProfileDependencyConfig) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 23 with Config

use of io.fabric8.docker.client.Config in project fabric8 by jboss-fuse.

the class MQServiceImpl method createOrUpdateMQProfile.

@Override
public Profile createOrUpdateMQProfile(String versionId, String profileId, String brokerName, Map<String, String> configs, boolean replicated) {
    Version version = profileService.getRequiredVersion(versionId);
    String parentProfileName = null;
    if (configs != null && configs.containsKey("parent")) {
        parentProfileName = configs.remove("parent");
    }
    if (Strings.isNullOrBlank(parentProfileName)) {
        parentProfileName = replicated ? MQ_PROFILE_REPLICATED : MQ_PROFILE_BASE;
    }
    Profile parentProfile = version.getRequiredProfile(parentProfileName);
    if (brokerName == null || profileId == null) {
        return parentProfile;
    }
    String pidName = getBrokerPID(brokerName);
    // lets check we have a config value
    ProfileBuilder builder;
    Profile overlay;
    // create a profile if it doesn't exist
    Map<String, String> config = null;
    boolean create = !version.hasProfile(profileId);
    if (create) {
        builder = ProfileBuilder.Factory.create(versionId, profileId);
        if (parentProfile != null) {
            builder.addParent(parentProfile.getId());
        }
        overlay = profileService.getOverlayProfile(parentProfile);
    } else {
        Profile profile = version.getRequiredProfile(profileId);
        builder = ProfileBuilder.Factory.createFrom(profile);
        config = builder.getConfiguration(pidName);
        overlay = profileService.getOverlayProfile(profile);
    }
    Map<String, String> parentProfileConfig = ProfileBuilder.Factory.createFrom(overlay).getConfiguration(MQ_PID_TEMPLATE);
    if (config == null) {
        config = parentProfileConfig;
    }
    if (configs != null && "true".equals(configs.get("ssl"))) {
        // Only generate the keystore file if it does not exist.
        // [TOOD] Fix direct data access! This should be part of the ProfileBuilder
        byte[] keystore = overlay.getFileConfiguration("keystore.jks");
        if (keystore == null) {
            try {
                String host = configs.get("keystore.cn");
                if (host == null) {
                    host = configs.get(GROUP);
                    if (host == null) {
                        host = "localhost";
                    }
                    configs.put("keystore.cn", host);
                }
                String password = configs.get("keystore.password");
                if (password == null) {
                    password = generatePassword(8);
                    configs.put("keystore.password", password);
                }
                File keystoreFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                keystoreFile.delete();
                LOG.info("Generating ssl keystore...");
                int rc = system("keytool", "-genkey", "-storetype", "JKS", "-storepass", password, "-keystore", keystoreFile.getCanonicalPath(), "-keypass", password, "-alias", host, "-keyalg", "RSA", "-keysize", "4096", "-dname", String.format("cn=%s", host), "-validity", "3650");
                if (rc != 0) {
                    throw new IOException("keytool failed with exit code: " + rc);
                }
                keystore = Files.readBytes(keystoreFile);
                keystoreFile.delete();
                LOG.info("Keystore generated");
                builder.addFileConfiguration("keystore.jks", keystore);
                configs.put("keystore.file", "profile:keystore.jks");
            } catch (IOException e) {
                LOG.error("Failed to generate keystore.jks: " + e.getMessage(), e);
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        // [TOOD] Fix direct data access! This should be part of the ProfileBuilder
        byte[] truststore = overlay.getFileConfiguration("truststore.jks");
        if (truststore == null && configs.get("keystore.password") != null) {
            try {
                String password = configs.get("truststore.password");
                if (password == null) {
                    password = configs.get("keystore.password");
                    configs.put("truststore.password", password);
                }
                File keystoreFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                Files.writeToFile(keystoreFile, keystore);
                File certFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                certFile.delete();
                LOG.info("Exporting broker certificate to create truststore.jks");
                int rc = system("keytool", "-exportcert", "-rfc", "-keystore", keystoreFile.getCanonicalPath(), "-storepass", configs.get("keystore.password"), "-alias", configs.get("keystore.cn"), "--file", certFile.getCanonicalPath());
                keystoreFile.delete();
                if (rc != 0) {
                    throw new IOException("keytool failed with exit code: " + rc);
                }
                LOG.info("Creating truststore.jks");
                File truststoreFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                truststoreFile.delete();
                rc = system("keytool", "-importcert", "-noprompt", "-keystore", truststoreFile.getCanonicalPath(), "-storepass", password, "--file", certFile.getCanonicalPath());
                certFile.delete();
                if (rc != 0) {
                    throw new IOException("keytool failed with exit code: " + rc);
                }
                truststore = Files.readBytes(truststoreFile);
                truststoreFile.delete();
                builder.addFileConfiguration("truststore.jks", truststore);
                configs.put("truststore.file", "profile:truststore.jks");
            } catch (IOException e) {
                LOG.error("Failed to generate truststore.jks due: " + e.getMessage(), e);
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
    config.put("broker-name", brokerName);
    if (configs != null) {
        config.putAll(configs);
    }
    // lets check we've a bunch of config values inherited from the template
    String[] propertiesToDefault = { CONFIG_URL, STANDBY_POOL, CONNECTORS };
    for (String key : propertiesToDefault) {
        if (config.get(key) == null) {
            String defaultValue = parentProfileConfig.get(key);
            if (Strings.isNotBlank(defaultValue)) {
                config.put(key, defaultValue);
            }
        }
    }
    // config map is not from "official" profile, so it doesn't have to use felix' Properties class
    builder.addConfiguration(pidName, config);
    Profile profile = builder.getProfile();
    return create ? profileService.createProfile(profile) : profileService.updateProfile(profile);
}
Also used : Version(io.fabric8.api.Version) IOException(java.io.IOException) ProfileBuilder(io.fabric8.api.ProfileBuilder) File(java.io.File) Profile(io.fabric8.api.Profile)

Example 24 with Config

use of io.fabric8.docker.client.Config 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 25 with Config

use of io.fabric8.docker.client.Config in project fabric8 by jboss-fuse.

the class SshContainerProvider method createSession.

protected Session createSession(CreateSshContainerOptions options) throws Exception {
    Session session = null;
    Exception connectException = null;
    for (int i = 0; i <= options.getSshRetries(); i++) {
        if (i > 0) {
            long delayMs = (long) (200L * Math.pow(i, 2));
            Thread.sleep(delayMs);
        }
        try {
            JSch jsch = new JSch();
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            byte[] privateKey = readFile(options.getPrivateKeyFile());
            byte[] passPhrase = options.getPassPhrase() != null ? options.getPassPhrase().getBytes() : null;
            if (privateKey != null && options.getPassword() == null) {
                jsch.addIdentity(options.getUsername(), privateKey, null, passPhrase);
                session = jsch.getSession(options.getUsername(), options.getHost(), options.getPort());
                config.put("PreferredAuthentications", "publickey");
            } else {
                session = jsch.getSession(options.getUsername(), options.getHost(), options.getPort());
                session.setPassword(options.getPassword());
                config.put("PreferredAuthentications", "password,keyboard-interactive");
            }
            session.setTimeout(60000);
            session.setConfig(config);
            session.connect();
            connectException = null;
            break;
        } catch (Exception from) {
            connectException = from;
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
            session = null;
        }
    }
    if (connectException != null) {
        throw connectException;
    }
    return session;
}
Also used : JSch(com.jcraft.jsch.JSch) Properties(org.apache.felix.scr.annotations.Properties) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) Session(com.jcraft.jsch.Session)

Aggregations

Test (org.junit.Test)128 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)44 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)43 IOException (java.io.IOException)41 HashMap (java.util.HashMap)40 File (java.io.File)31 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)28 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)28 Map (java.util.Map)28 RunImageConfiguration (io.fabric8.maven.docker.config.RunImageConfiguration)24 ArrayList (java.util.ArrayList)24 ProcessorConfig (io.fabric8.maven.core.config.ProcessorConfig)23 AbstractConfigHandlerTest (io.fabric8.maven.docker.config.handler.AbstractConfigHandlerTest)21 Expectations (mockit.Expectations)20 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)19 ConfigMapBuilder (io.fabric8.kubernetes.api.model.ConfigMapBuilder)17 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)16 VolumeConfig (io.fabric8.maven.core.config.VolumeConfig)15 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)14 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)12