Search in sources :

Example 41 with Config

use of io.fabric8.kubernetes.api.model.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 42 with Config

use of io.fabric8.kubernetes.api.model.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 43 with Config

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

Example 44 with Config

use of io.fabric8.kubernetes.api.model.Config in project jointware by isdream.

the class KubernetesClient method create.

@Override
public Object create(Map<String, Object> map) {
    String prefix = null;
    if (map == null || map.get(MASTER_TYPE) == null) {
        return null;
    } else if (map.get(MASTER_TYPE).equals(PROTOCOL_HTTP)) {
        prefix = PROTOCOL_HTTP + "://";
    } else {
        return null;
    }
    Config config = new ConfigBuilder().withMasterUrl(prefix + map.get(MASTER_IP) + ":" + map.get(MASTER_PORT)).build();
    return new DefaultKubernetesClient(config);
}
Also used : Config(io.fabric8.kubernetes.client.Config) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient)

Example 45 with Config

use of io.fabric8.kubernetes.api.model.Config in project kubernetes by ballerinax.

the class DockerHandler method pushImage.

/**
 * Push docker image.
 *
 * @param dockerModel DockerModel
 * @throws InterruptedException When error with docker build process
 * @throws IOException          When error with docker build process
 */
public void pushImage(DockerModel dockerModel) throws InterruptedException, IOException, KubernetesPluginException {
    AuthConfig authConfig = new AuthConfigBuilder().withUsername(dockerModel.getUsername()).withPassword(dockerModel.getPassword()).build();
    Config config = new ConfigBuilder().withDockerUrl(dockerModel.getDockerHost()).addToAuthConfigs(RegistryUtils.extractRegistry(dockerModel.getName()), authConfig).build();
    DockerClient client = new DefaultDockerClient(config);
    final DockerError dockerError = new DockerError();
    OutputHandle handle = client.image().withName(dockerModel.getName()).push().usingListener(new EventListener() {

        @Override
        public void onSuccess(String message) {
            pushDone.countDown();
        }

        @Override
        public void onError(String message) {
            pushDone.countDown();
            dockerError.setErrorMsg("error pushing docker image: " + message);
        }

        @Override
        public void onError(Throwable t) {
            pushDone.countDown();
            dockerError.setErrorMsg("error pushing docker image: " + t.getMessage());
        }

        @Override
        public void onEvent(String event) {
            printDebug(event);
        }
    }).toRegistry();
    pushDone.await();
    handle.close();
    client.close();
    handleError(dockerError);
}
Also used : AuthConfigBuilder(io.fabric8.docker.api.model.AuthConfigBuilder) DefaultDockerClient(io.fabric8.docker.client.DefaultDockerClient) DockerClient(io.fabric8.docker.client.DockerClient) Config(io.fabric8.docker.client.Config) AuthConfig(io.fabric8.docker.api.model.AuthConfig) DefaultDockerClient(io.fabric8.docker.client.DefaultDockerClient) AuthConfigBuilder(io.fabric8.docker.api.model.AuthConfigBuilder) ConfigBuilder(io.fabric8.docker.client.ConfigBuilder) OutputHandle(io.fabric8.docker.dsl.OutputHandle) AuthConfig(io.fabric8.docker.api.model.AuthConfig) EventListener(io.fabric8.docker.dsl.EventListener)

Aggregations

Test (org.junit.Test)106 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)37 HashMap (java.util.HashMap)34 IOException (java.io.IOException)32 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)28 File (java.io.File)26 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)24 Map (java.util.Map)24 ProcessorConfig (io.fabric8.maven.core.config.ProcessorConfig)23 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)21 Expectations (mockit.Expectations)20 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)17 ArrayList (java.util.ArrayList)17 VolumeConfig (io.fabric8.maven.core.config.VolumeConfig)15 AbstractConfigHandlerTest (io.fabric8.maven.docker.config.handler.AbstractConfigHandlerTest)15 ConfigMapBuilder (io.fabric8.kubernetes.api.model.ConfigMapBuilder)14 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)13 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)12 Before (org.junit.Before)12 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)11