Search in sources :

Example 1 with KubernetesAuthException

use of org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthException in project kubernetes-plugin by jenkinsci.

the class KubernetesSlave method _terminate.

@Override
protected void _terminate(TaskListener listener) throws IOException, InterruptedException {
    LOGGER.log(Level.INFO, "Terminating Kubernetes instance for agent {0}", name);
    KubernetesCloud cloud;
    try {
        cloud = getKubernetesCloud();
    } catch (IllegalStateException e) {
        e.printStackTrace(listener.fatalError("Unable to terminate agent. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster."));
        LOGGER.log(Level.SEVERE, String.format("Unable to terminate agent %s. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster.", name));
        return;
    }
    KubernetesClient client;
    try {
        client = cloud.connect();
    } catch (KubernetesAuthException | IOException e) {
        String msg = String.format("Failed to connect to cloud %s. There may be leftover resources on the Kubernetes cluster.", getCloudName());
        e.printStackTrace(listener.fatalError(msg));
        LOGGER.log(Level.SEVERE, msg);
        return;
    }
    // Prior to termination, determine if we should delete the slave pod based on
    // the slave pod's current state and the pod retention policy.
    // Healthy slave pods should still have a JNLP agent running at this point.
    Pod pod = client.pods().inNamespace(getNamespace()).withName(name).get();
    boolean deletePod = getPodRetention(cloud).shouldDeletePod(cloud, pod);
    Computer computer = toComputer();
    if (computer == null) {
        String msg = String.format("Computer for agent is null: %s", name);
        LOGGER.log(Level.SEVERE, msg);
        listener.fatalError(msg);
        return;
    }
    // Tell the slave to stop JNLP reconnects.
    VirtualChannel ch = computer.getChannel();
    if (ch != null) {
        Future<Void> disconnectorFuture = ch.callAsync(new SlaveDisconnector());
        try {
            disconnectorFuture.get(DISCONNECTION_TIMEOUT, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            String msg = String.format("Ignoring error sending order to not reconnect agent %s: %s", name, e.getMessage());
            LOGGER.log(Level.INFO, msg, e);
        }
    }
    if (getCloudName() == null) {
        String msg = String.format("Cloud name is not set for agent, can't terminate: %s", name);
        LOGGER.log(Level.SEVERE, msg);
        listener.fatalError(msg);
        return;
    }
    if (deletePod) {
        deleteSlavePod(listener, client);
        Metrics.metricRegistry().counter(MetricNames.PODS_TERMINATED).inc();
    } else {
        // Log warning, as the agent pod may still be running
        LOGGER.log(Level.WARNING, "Agent pod {0} was not deleted due to retention policy {1}.", new Object[] { name, getPodRetention(cloud) });
    }
    String msg = String.format("Disconnected computer %s", name);
    LOGGER.log(Level.INFO, msg);
    listener.getLogger().println(msg);
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Pod(io.fabric8.kubernetes.api.model.Pod) VirtualChannel(hudson.remoting.VirtualChannel) IOException(java.io.IOException) SlaveComputer(hudson.slaves.SlaveComputer) Computer(hudson.model.Computer) KubernetesAuthException(org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with KubernetesAuthException

use of org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthException in project kubernetes-plugin by jenkinsci.

the class KubectlBuildWrapper method setUp.

@Override
public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {
    if (credentialsId == null) {
        throw new AbortException("No credentials defined to setup Kubernetes CLI");
    }
    workspace.mkdirs();
    FilePath configFile = workspace.createTempFile(".kube", "config");
    Set<String> tempFiles = new HashSet<>(Arrays.asList(configFile.getRemote()));
    context.env("KUBECONFIG", configFile.getRemote());
    context.setDisposer(new CleanupDisposer(tempFiles));
    StandardCredentials credentials = CredentialsProvider.findCredentialById(credentialsId, StandardCredentials.class, build, Collections.emptyList());
    if (credentials == null) {
        throw new AbortException("No credentials found for id \"" + credentialsId + "\"");
    }
    KubernetesAuth auth = AuthenticationTokens.convert(KubernetesAuth.class, credentials);
    if (auth == null) {
        throw new AbortException("Unsupported Credentials type " + credentials.getClass().getName());
    }
    try (Writer w = new OutputStreamWriter(configFile.write(), StandardCharsets.UTF_8)) {
        w.write(auth.buildKubeConfig(new KubernetesAuthConfig(getServerUrl(), getCaCertificate(), getCaCertificate() == null)));
    } catch (KubernetesAuthException e) {
        throw new AbortException(e.getMessage());
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    String cmd = "kubectl version";
    int status = launcher.launch().cmdAsSingleString(cmd).stdout(out).stderr(err).quiet(true).envs("KUBECONFIG=" + configFile.getRemote()).join();
    if (status != 0) {
        StringBuilder msgBuilder = new StringBuilder("Failed to run \"").append(cmd).append("\". Returned status code ").append(status).append(".\n");
        msgBuilder.append("stdout:\n").append(out).append("\n");
        msgBuilder.append("stderr:\n").append(err);
        throw new AbortException(msgBuilder.toString());
    }
}
Also used : FilePath(hudson.FilePath) KubernetesAuth(org.jenkinsci.plugins.kubernetes.auth.KubernetesAuth) KubernetesAuthConfig(org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthConfig) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) KubernetesAuthException(org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthException) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) AbortException(hudson.AbortException) HashSet(java.util.HashSet)

Aggregations

KubernetesAuthException (org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthException)2 StandardCredentials (com.cloudbees.plugins.credentials.common.StandardCredentials)1 AbortException (hudson.AbortException)1 FilePath (hudson.FilePath)1 Computer (hudson.model.Computer)1 VirtualChannel (hudson.remoting.VirtualChannel)1 SlaveComputer (hudson.slaves.SlaveComputer)1 Pod (io.fabric8.kubernetes.api.model.Pod)1 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Writer (java.io.Writer)1 HashSet (java.util.HashSet)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 KubernetesAuth (org.jenkinsci.plugins.kubernetes.auth.KubernetesAuth)1 KubernetesAuthConfig (org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthConfig)1