Search in sources :

Example 11 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8-maven-plugin by fabric8io.

the class ImportMojo method executeInternal.

@Override
public void executeInternal() throws MojoExecutionException, MojoFailureException {
    if (!basedir.isDirectory() || !basedir.exists()) {
        throw new MojoExecutionException("No directory for base directory: " + basedir);
    }
    // lets check for a git repo
    String gitRemoteURL = null;
    Repository repository = null;
    try {
        repository = GitUtils.findRepository(basedir);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to find local git repository in current directory: " + e, e);
    }
    try {
        gitRemoteURL = GitUtils.getRemoteAsHttpsURL(repository);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to get the current git branch: " + e, e);
    }
    try {
        clusterAccess = new ClusterAccess(this.namespace);
        if (Strings.isNullOrBlank(projectName)) {
            projectName = basedir.getName();
        }
        KubernetesClient kubernetes = clusterAccess.createDefaultClient(log);
        KubernetesResourceUtil.validateKubernetesMasterUrl(kubernetes.getMasterUrl());
        String namespace = clusterAccess.getNamespace();
        OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinsShift(kubernetes, namespace);
        if (gitRemoteURL != null) {
            // lets check we don't already have this project imported
            String branch = repository.getBranch();
            BuildConfig buildConfig = findBuildConfigForGitRepo(openShiftClient, namespace, gitRemoteURL, branch);
            if (buildConfig != null) {
                logBuildConfigLink(kubernetes, namespace, buildConfig, log);
                throw new MojoExecutionException("Project already imported into build " + getName(buildConfig) + " for URI: " + gitRemoteURL + " and branch: " + branch);
            } else {
                Map<String, String> annotations = new HashMap<>();
                annotations.put(Annotations.Builds.GIT_CLONE_URL, gitRemoteURL);
                buildConfig = createBuildConfig(kubernetes, namespace, projectName, gitRemoteURL, annotations);
                openShiftClient.buildConfigs().inNamespace(namespace).create(buildConfig);
                ensureExternalGitSecretsAreSetupFor(kubernetes, namespace, gitRemoteURL);
                logBuildConfigLink(kubernetes, namespace, buildConfig, log);
            }
        } else {
            // lets create an import a new project
            UserDetails userDetails = createGogsUserDetails(kubernetes, namespace);
            userDetails.setBranch(branchName);
            BuildConfigHelper.CreateGitProjectResults createGitProjectResults;
            try {
                createGitProjectResults = BuildConfigHelper.importNewGitProject(kubernetes, userDetails, basedir, namespace, projectName, remoteName, "Importing project from mvn fabric8:import", false);
            } catch (WebApplicationException e) {
                Response response = e.getResponse();
                if (response.getStatus() > 400) {
                    String message = getEntityMessage(response);
                    log.warn("Could not create the git repository: %s %s", e, message);
                    log.warn("Are your username and password correct in the Secret %s/%s?", secretNamespace, gogsSecretName);
                    log.warn("To re-enter your password rerun this command with -Dfabric8.passsword.retry=true");
                    throw new MojoExecutionException("Could not create the git repository. " + "Are your username and password correct in the Secret " + secretNamespace + "/" + gogsSecretName + "?" + e + message, e);
                } else {
                    throw e;
                }
            }
            BuildConfig buildConfig = createGitProjectResults.getBuildConfig();
            openShiftClient.buildConfigs().inNamespace(namespace).create(buildConfig);
            logBuildConfigLink(kubernetes, namespace, buildConfig, log);
        }
    } catch (KubernetesClientException e) {
        KubernetesResourceUtil.handleKubernetesClientException(e, this.log);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) IOException(java.io.IOException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) PrompterException(org.codehaus.plexus.components.interactivity.PrompterException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Response(javax.ws.rs.core.Response) Repository(org.eclipse.jgit.lib.Repository) UserDetails(io.fabric8.project.support.UserDetails) BuildConfigHelper(io.fabric8.project.support.BuildConfigHelper) ClusterAccess(io.fabric8.maven.core.access.ClusterAccess) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) BuildConfigHelper.createBuildConfig(io.fabric8.project.support.BuildConfigHelper.createBuildConfig) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 12 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project strimzi by strimzi.

the class AbstractModel method createExecProbe.

protected Probe createExecProbe(String command, int initialDelay, int timeout) {
    Probe probe = new ProbeBuilder().withNewExec().withCommand(command).endExec().withInitialDelaySeconds(initialDelay).withTimeoutSeconds(timeout).build();
    log.trace("Created exec probe {}", probe);
    return probe;
}
Also used : ProbeBuilder(io.fabric8.kubernetes.api.model.ProbeBuilder) Probe(io.fabric8.kubernetes.api.model.Probe)

Example 13 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project zalenium by zalando.

the class KubernetesContainerClient method executeCommand.

@Override
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
    final CountDownLatch latch = new CountDownLatch(1);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    logger.info(String.format("%s %s", containerId, Arrays.toString(command)));
    ExecWatch exec = client.pods().withName(containerId).writingOutput(baos).writingError(baos).usingListener(new ExecListener() {

        @Override
        public void onOpen(Response response) {
        }

        @Override
        public void onFailure(Throwable t, Response response) {
            logger.error(String.format("%s Failed to execute command %s", containerId, Arrays.toString(command)), t);
            latch.countDown();
        }

        @Override
        public void onClose(int code, String reason) {
            latch.countDown();
        }
    }).exec(command);
    Supplier<Void> waitForResultsAndCleanup = () -> {
        try {
            latch.await();
        } catch (InterruptedException e) {
            logger.error(String.format("%s Failed to execute command %s", containerId, Arrays.toString(command)), e);
        } finally {
            exec.close();
        }
        logger.info(String.format("%s %s", containerId, baos.toString()));
        return null;
    };
    if (waitForExecution) {
        // If we're going to wait, let's use the same thread
        waitForResultsAndCleanup.get();
    } else {
        // Let the common ForkJoinPool handle waiting for the results, since we don't care when it finishes.
        CompletableFuture.supplyAsync(waitForResultsAndCleanup);
    }
}
Also used : Response(okhttp3.Response) ExecWatch(io.fabric8.kubernetes.client.dsl.ExecWatch) ExecListener(io.fabric8.kubernetes.client.dsl.ExecListener) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 14 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project zalenium by zalando.

the class KubernetesContainerClient method copyFiles.

/**
 * Copy some files by executing a tar command to the stdout and return the InputStream that contains the tar
 * contents.
 * <p>
 * Unfortunately due to the fact that any error handling happens on another thread, if the tar command fails the
 * InputStream will simply be empty and it will close. It won't propagate an Exception to the reader of the
 * InputStream.
 */
@Override
public InputStream copyFiles(String containerId, String folderName) {
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    String[] command = new String[] { "tar", "-C", folderName, "-c", "." };
    CopyFilesExecListener listener = new CopyFilesExecListener(stderr, command, containerId);
    ExecWatch exec = client.pods().withName(containerId).redirectingOutput().writingError(stderr).usingListener(listener).exec(command);
    // FIXME: This is a bit dodgy, but we need the listener to be able to close the ExecWatch in failure conditions,
    // because it doesn't cleanup properly and deadlocks.
    // Needs bugs fixed inside kubernetes-client.
    listener.setExecWatch(exec);
    // When zalenium is under high load sometimes the stdout isn't connected by the time we try to read from it.
    // Let's wait until it is connected before proceeding.
    listener.waitForInputStreamToConnect();
    return exec.getOutput();
}
Also used : ExecWatch(io.fabric8.kubernetes.client.dsl.ExecWatch) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 15 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project docker-maven-plugin by fabric8io.

the class RunService method createContainerConfig.

// visible for testing
ContainerCreateConfig createContainerConfig(String imageName, RunImageConfiguration runConfig, PortMapping mappedPorts, GavLabel gavLabel, Properties mavenProps, File baseDir) throws DockerAccessException {
    try {
        ContainerCreateConfig config = new ContainerCreateConfig(imageName).hostname(runConfig.getHostname()).domainname(runConfig.getDomainname()).user(runConfig.getUser()).workingDir(runConfig.getWorkingDir()).entrypoint(runConfig.getEntrypoint()).exposedPorts(mappedPorts.getContainerPorts()).environment(runConfig.getEnvPropertyFile(), runConfig.getEnv(), mavenProps).labels(mergeLabels(runConfig.getLabels(), gavLabel)).command(runConfig.getCmd()).hostConfig(createContainerHostConfig(runConfig, mappedPorts, baseDir));
        RunVolumeConfiguration volumeConfig = runConfig.getVolumeConfiguration();
        if (volumeConfig != null) {
            resolveRelativeVolumeBindings(baseDir, volumeConfig);
            config.binds(volumeConfig.getBind());
        }
        NetworkConfig networkConfig = runConfig.getNetworkingConfig();
        if (networkConfig.isCustomNetwork() && networkConfig.hasAliases()) {
            ContainerNetworkingConfig networkingConfig = new ContainerNetworkingConfig().aliases(networkConfig);
            config.networkingConfig(networkingConfig);
        }
        return config;
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(String.format("Failed to create contained configuration for [%s]", imageName), e);
    }
}
Also used : RunVolumeConfiguration(io.fabric8.maven.docker.config.RunVolumeConfiguration) NetworkConfig(io.fabric8.maven.docker.config.NetworkConfig) ContainerCreateConfig(io.fabric8.maven.docker.access.ContainerCreateConfig) ContainerNetworkingConfig(io.fabric8.maven.docker.access.ContainerNetworkingConfig)

Aggregations

IOException (java.io.IOException)9 File (java.io.File)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 Container (io.fabric8.api.Container)5 JMXRequest (io.fabric8.api.commands.JMXRequest)4 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 FabricService (io.fabric8.api.FabricService)3 ContainerCreateConfig (io.fabric8.maven.docker.access.ContainerCreateConfig)3 Arguments (io.fabric8.maven.docker.config.Arguments)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Properties (java.util.Properties)3 TemplatedResource (com.netflix.spinnaker.halyard.core.resource.v1.TemplatedResource)2 ArtifactService (com.netflix.spinnaker.halyard.deploy.services.v1.ArtifactService)2 GenerateService (com.netflix.spinnaker.halyard.deploy.services.v1.GenerateService)2 SpinnakerRuntimeSettings (com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings)2 Container (io.fabric8.kubernetes.api.model.Container)2