Search in sources :

Example 1 with Configuration

use of io.fabric8.annotations.Configuration in project camel by apache.

the class KubernetesEndpoint method createKubernetesClient.

private KubernetesClient createKubernetesClient() {
    LOG.debug("Create Kubernetes client with the following Configuration: " + configuration.toString());
    ConfigBuilder builder = new ConfigBuilder();
    builder.withMasterUrl(configuration.getMasterUrl());
    if ((ObjectHelper.isNotEmpty(configuration.getUsername()) && ObjectHelper.isNotEmpty(configuration.getPassword())) && ObjectHelper.isEmpty(configuration.getOauthToken())) {
        builder.withUsername(configuration.getUsername());
        builder.withPassword(configuration.getPassword());
    }
    if (ObjectHelper.isNotEmpty(configuration.getOauthToken())) {
        builder.withOauthToken(configuration.getOauthToken());
    }
    if (ObjectHelper.isNotEmpty(configuration.getCaCertData())) {
        builder.withCaCertData(configuration.getCaCertData());
    }
    if (ObjectHelper.isNotEmpty(configuration.getCaCertFile())) {
        builder.withCaCertFile(configuration.getCaCertFile());
    }
    if (ObjectHelper.isNotEmpty(configuration.getClientCertData())) {
        builder.withClientCertData(configuration.getClientCertData());
    }
    if (ObjectHelper.isNotEmpty(configuration.getClientCertFile())) {
        builder.withClientCertFile(configuration.getClientCertFile());
    }
    if (ObjectHelper.isNotEmpty(configuration.getApiVersion())) {
        builder.withApiVersion(configuration.getApiVersion());
    }
    if (ObjectHelper.isNotEmpty(configuration.getClientKeyAlgo())) {
        builder.withClientKeyAlgo(configuration.getClientKeyAlgo());
    }
    if (ObjectHelper.isNotEmpty(configuration.getClientKeyData())) {
        builder.withClientKeyData(configuration.getClientKeyData());
    }
    if (ObjectHelper.isNotEmpty(configuration.getClientKeyFile())) {
        builder.withClientKeyFile(configuration.getClientKeyFile());
    }
    if (ObjectHelper.isNotEmpty(configuration.getClientKeyPassphrase())) {
        builder.withClientKeyPassphrase(configuration.getClientKeyPassphrase());
    }
    if (ObjectHelper.isNotEmpty(configuration.getTrustCerts())) {
        builder.withTrustCerts(configuration.getTrustCerts());
    }
    Config conf = builder.build();
    return new DefaultKubernetesClient(conf);
}
Also used : Config(io.fabric8.kubernetes.client.Config) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient)

Example 2 with Configuration

use of io.fabric8.annotations.Configuration in project carbon-apimgt by wso2.

the class ServiceDiscovererKubernetes method buildConfig.

/**
 * Builds the Config required by DefaultOpenShiftClient
 * Also sets the system properties
 * (1) to not refer .kube/config file and
 * (2) the client to use service account procedure to get authenticated and authorised
 *
 * @return {@link io.fabric8.kubernetes.client.Config} object to build the client
 * @throws ServiceDiscoveryException if an error occurs while building the config using externally stored token
 */
private Config buildConfig(Map<String, String> implParameters) throws ServiceDiscoveryException, APIMgtDAOException {
    System.setProperty(TRY_KUBE_CONFIG, "false");
    System.setProperty(TRY_SERVICE_ACCOUNT, "true");
    /*
         *  Common to both situations,
         *      - Token found inside APIM pod
         *      - Token stored in APIM resources/security folder }
         */
    ConfigBuilder configBuilder = new ConfigBuilder().withMasterUrl(implParameters.get(MASTER_URL)).withCaCertFile(implParameters.get(CA_CERT_PATH));
    /*
         *  Check if a service account token File Name is given in the configuration
         *      - if not : assume APIM is running inside a pod and look for the pod's token
         */
    String externalSATokenFileName = implParameters.get(EXTERNAL_SA_TOKEN_FILE_NAME);
    if (StringUtils.isEmpty(externalSATokenFileName)) {
        log.debug("Looking for service account token in " + POD_MOUNTED_SA_TOKEN_FILE_PATH);
        String podMountedSAToken = APIFileUtils.readFileContentAsText(implParameters.get(POD_MOUNTED_SA_TOKEN_FILE_PATH));
        return configBuilder.withOauthToken(podMountedSAToken).build();
    } else {
        log.info("Using externally stored service account token");
        return configBuilder.withOauthToken(resolveToken("encrypted" + externalSATokenFileName)).build();
    }
}
Also used : ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder)

Example 3 with Configuration

use of io.fabric8.annotations.Configuration in project carbon-apimgt by wso2.

the class ServiceDiscovererKubernetes method initImpl.

/**
 * Initializes OpenShiftClient (extended KubernetesClient) and sets the necessary parameters
 *
 * @param implParameters implementation parameters added by the super class #initImpl(java.util.Map) method
 * @throws ServiceDiscoveryException if an error occurs while initializing the client
 */
@Override
public void initImpl(Map<String, String> implParameters) throws ServiceDiscoveryException {
    try {
        setClient(new DefaultOpenShiftClient(buildConfig(implParameters)));
    } catch (KubernetesClientException | APIMgtDAOException e) {
        String msg = "Error occurred while creating Kubernetes client";
        throw new ServiceDiscoveryException(msg, e, ExceptionCodes.ERROR_INITIALIZING_SERVICE_DISCOVERY);
    } catch (ArrayIndexOutOfBoundsException e) {
        String msg = "Error occurred while reading filtering criteria from the configuration";
        throw new ServiceDiscoveryException(msg, e, ExceptionCodes.ERROR_INITIALIZING_SERVICE_DISCOVERY);
    }
    includeClusterIP = Boolean.parseBoolean(implParameters.get(INCLUDE_CLUSTER_IPS));
    includeExternalNameTypeServices = Boolean.parseBoolean(implParameters.get(INCLUDE_EXTERNAL_NAME_SERVICES));
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) ServiceDiscoveryException(org.wso2.carbon.apimgt.core.exception.ServiceDiscoveryException) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 4 with Configuration

use of io.fabric8.annotations.Configuration in project docker-maven-plugin by fabric8io.

the class DockerAssemblyManager method createDockerTarArchive.

/**
 * Create an docker tar archive from the given configuration which can be send to the Docker host for
 * creating the image.
 *
 * @param imageName Name of the image to create (used for creating build directories)
 * @param params Mojos parameters (used for finding the directories)
 * @param buildConfig configuration for how to build the image
 * @param log Logger used to display warning if permissions are to be normalized
 * @param finalCustomizer finalCustomizer to be applied to the tar archive
 * @return file holding the path to the created assembly tar file
 * @throws MojoExecutionException
 */
public File createDockerTarArchive(String imageName, MojoParameters params, final BuildImageConfiguration buildConfig, Logger log, ArchiverCustomizer finalCustomizer) throws MojoExecutionException {
    final BuildDirs buildDirs = createBuildDirs(imageName, params);
    final AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration();
    final List<ArchiverCustomizer> archiveCustomizers = new ArrayList<>();
    // Build up assembly. In dockerfile mode this must be added explicitly in the Dockerfile with an ADD
    if (hasAssemblyConfiguration(assemblyConfig)) {
        createAssemblyArchive(assemblyConfig, params, buildDirs);
    }
    try {
        if (buildConfig.isDockerFileMode()) {
            // Use specified docker directory which must include a Dockerfile.
            final File dockerFile = buildConfig.getAbsoluteDockerFilePath(params);
            if (!dockerFile.exists()) {
                throw new MojoExecutionException("Configured Dockerfile \"" + buildConfig.getDockerFile() + "\" (resolved to \"" + dockerFile + "\") doesn't exist");
            }
            FixedStringSearchInterpolator interpolator = DockerFileUtil.createInterpolator(params, buildConfig.getFilter());
            verifyGivenDockerfile(dockerFile, buildConfig, interpolator, log);
            interpolateDockerfile(dockerFile, buildDirs, interpolator);
            // User dedicated Dockerfile from extra directory
            archiveCustomizers.add(new ArchiverCustomizer() {

                @Override
                public TarArchiver customize(TarArchiver archiver) throws IOException {
                    DefaultFileSet fileSet = DefaultFileSet.fileSet(dockerFile.getParentFile());
                    addDockerIgnoreIfPresent(fileSet);
                    // Exclude non-interpolated dockerfile from source tree
                    // Interpolated Dockerfile is already added as it was created into the output directory when
                    // using dir dir mode
                    excludeDockerfile(fileSet, dockerFile);
                    // directly to docker.tar (as the output builddir is not picked up in archive mode)
                    if (isArchive(assemblyConfig)) {
                        String name = dockerFile.getName();
                        archiver.addFile(new File(buildDirs.getOutputDirectory(), name), name);
                    }
                    archiver.addFileSet(fileSet);
                    return archiver;
                }
            });
        } else {
            // Create custom docker file in output dir
            DockerFileBuilder builder = createDockerFileBuilder(buildConfig, assemblyConfig);
            builder.write(buildDirs.getOutputDirectory());
            // Add own Dockerfile
            final File dockerFile = new File(buildDirs.getOutputDirectory(), DOCKERFILE_NAME);
            archiveCustomizers.add(new ArchiverCustomizer() {

                @Override
                public TarArchiver customize(TarArchiver archiver) throws IOException {
                    archiver.addFile(dockerFile, DOCKERFILE_NAME);
                    return archiver;
                }
            });
        }
        // If required make all files in the assembly executable
        if (assemblyConfig != null) {
            AssemblyConfiguration.PermissionMode mode = assemblyConfig.getPermissions();
            if (mode == AssemblyConfiguration.PermissionMode.exec || mode == AssemblyConfiguration.PermissionMode.auto && EnvUtil.isWindows()) {
                archiveCustomizers.add(new AllFilesExecCustomizer(log));
            }
        }
        if (finalCustomizer != null) {
            archiveCustomizers.add(finalCustomizer);
        }
        return createBuildTarBall(buildDirs, archiveCustomizers, assemblyConfig, buildConfig.getCompression());
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("Cannot create %s in %s", DOCKERFILE_NAME, buildDirs.getOutputDirectory()), e);
    }
}
Also used : FixedStringSearchInterpolator(org.codehaus.plexus.interpolation.fixed.FixedStringSearchInterpolator) DefaultFileSet(org.codehaus.plexus.archiver.util.DefaultFileSet) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) TarArchiver(org.codehaus.plexus.archiver.tar.TarArchiver) AssemblyConfiguration(io.fabric8.maven.docker.config.AssemblyConfiguration) File(java.io.File)

Example 5 with Configuration

use of io.fabric8.annotations.Configuration in project docker-maven-plugin by fabric8io.

the class BuildService method buildImage.

/**
 * Build an image
 *
 * @param imageConfig the image configuration
 * @param params mojo params for the project
 * @param noCache if not null, dictate the caching behaviour. Otherwise its taken from the build configuration
 * @param buildArgs
 * @throws DockerAccessException
 * @throws MojoExecutionException
 */
protected void buildImage(ImageConfiguration imageConfig, MojoParameters params, boolean noCache, Map<String, String> buildArgs) throws DockerAccessException, MojoExecutionException {
    String imageName = imageConfig.getName();
    ImageName.validate(imageName);
    BuildImageConfiguration buildConfig = imageConfig.getBuildConfiguration();
    String oldImageId = null;
    CleanupMode cleanupMode = buildConfig.cleanupMode();
    if (cleanupMode.isRemove()) {
        oldImageId = queryService.getImageId(imageName);
    }
    long time = System.currentTimeMillis();
    if (buildConfig.getDockerArchive() != null) {
        docker.loadImage(imageName, buildConfig.getAbsoluteDockerTarPath(params));
        log.info("%s: Loaded tarball in %s", buildConfig.getDockerArchive(), EnvUtil.formatDurationTill(time));
        return;
    }
    File dockerArchive = archiveService.createArchive(imageName, buildConfig, params, log);
    log.info("%s: Created %s in %s", imageConfig.getDescription(), dockerArchive.getName(), EnvUtil.formatDurationTill(time));
    Map<String, String> mergedBuildMap = prepareBuildArgs(buildArgs, buildConfig);
    // auto is now supported by docker, consider switching?
    BuildOptions opts = new BuildOptions(buildConfig.getBuildOptions()).dockerfile(getDockerfileName(buildConfig)).forceRemove(cleanupMode.isRemove()).noCache(noCache).buildArgs(mergedBuildMap);
    String newImageId = doBuildImage(imageName, dockerArchive, opts);
    log.info("%s: Built image %s", imageConfig.getDescription(), newImageId);
    if (oldImageId != null && !oldImageId.equals(newImageId)) {
        try {
            docker.removeImage(oldImageId, true);
            log.info("%s: Removed old image %s", imageConfig.getDescription(), oldImageId);
        } catch (DockerAccessException exp) {
            if (cleanupMode == CleanupMode.TRY_TO_REMOVE) {
                log.warn("%s: %s (old image)%s", imageConfig.getDescription(), exp.getMessage(), (exp.getCause() != null ? " [" + exp.getCause().getMessage() + "]" : ""));
            } else {
                throw exp;
            }
        }
    }
}
Also used : BuildOptions(io.fabric8.maven.docker.access.BuildOptions) DockerAccessException(io.fabric8.maven.docker.access.DockerAccessException) CleanupMode(io.fabric8.maven.docker.config.CleanupMode) File(java.io.File) BuildImageConfiguration(io.fabric8.maven.docker.config.BuildImageConfiguration)

Aggregations

IOException (java.io.IOException)29 HashMap (java.util.HashMap)23 File (java.io.File)22 Configuration (org.osgi.service.cm.Configuration)20 Map (java.util.Map)16 BootstrapConfiguration (io.fabric8.zookeeper.bootstrap.BootstrapConfiguration)15 Test (org.junit.Test)13 ArrayList (java.util.ArrayList)12 Container (io.fabric8.api.Container)11 Profile (io.fabric8.api.Profile)11 RuntimeProperties (io.fabric8.api.RuntimeProperties)9 HashSet (java.util.HashSet)9 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)8 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)8 FabricException (io.fabric8.api.FabricException)7 FabricService (io.fabric8.api.FabricService)7 Properties (java.util.Properties)7 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)6 Util.readAsString (io.fabric8.arquillian.utils.Util.readAsString)5 URL (java.net.URL)5