Search in sources :

Example 1 with BodyInvoker

use of org.jenkinsci.plugins.workflow.steps.BodyInvoker in project kubernetes-plugin by jenkinsci.

the class PodTemplateStepExecution method start.

@Override
public boolean start() throws Exception {
    KubernetesCloud cloud = resolveCloud();
    Run<?, ?> run = getContext().get(Run.class);
    if (cloud.isUsageRestricted()) {
        checkAccess(run, cloud);
    }
    PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class);
    String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null;
    String label = step.getLabel();
    if (label == null) {
        label = labelify(run.getExternalizableId());
    }
    // Let's generate a random name based on the user specified to make sure that we don't have
    // issues with concurrent builds, or messing with pre-existing configuration
    String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
    String stepName = step.getName();
    if (stepName == null) {
        stepName = label;
    }
    String name = String.format(NAME_FORMAT, stepName, randString);
    String namespace = checkNamespace(cloud, podTemplateContext);
    newTemplate = new PodTemplate();
    newTemplate.setName(name);
    newTemplate.setNamespace(namespace);
    if (step.getInheritFrom() == null) {
        newTemplate.setInheritFrom(PodTemplateUtils.emptyToNull(parentTemplates));
    } else {
        newTemplate.setInheritFrom(PodTemplateUtils.emptyToNull(step.getInheritFrom()));
    }
    newTemplate.setInstanceCap(step.getInstanceCap());
    newTemplate.setIdleMinutes(step.getIdleMinutes());
    newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout());
    newTemplate.setLabel(label);
    newTemplate.setEnvVars(step.getEnvVars());
    newTemplate.setVolumes(step.getVolumes());
    if (step.getWorkspaceVolume() != null) {
        newTemplate.setWorkspaceVolume(step.getWorkspaceVolume());
    }
    newTemplate.setContainers(step.getContainers());
    newTemplate.setNodeSelector(step.getNodeSelector());
    newTemplate.setNodeUsageMode(step.getNodeUsageMode());
    newTemplate.setServiceAccount(step.getServiceAccount());
    newTemplate.setSchedulerName(step.getSchedulerName());
    newTemplate.setRunAsUser(step.getRunAsUser());
    newTemplate.setRunAsGroup(step.getRunAsGroup());
    if (step.getHostNetwork() != null) {
        newTemplate.setHostNetwork(step.getHostNetwork());
    }
    newTemplate.setAnnotations(step.getAnnotations());
    TaskListener listener = getContext().get(TaskListener.class);
    newTemplate.setListener(listener);
    newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy());
    if (run != null) {
        String url = cloud.getJenkinsUrlOrNull();
        if (url != null) {
            newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl()));
            newTemplate.getAnnotations().add(new PodAnnotation("runUrl", run.getUrl()));
        }
    }
    newTemplate.setImagePullSecrets(step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList()));
    newTemplate.setYaml(step.getYaml());
    if (step.isShowRawYamlSet()) {
        newTemplate.setShowRawYaml(step.isShowRawYaml());
    }
    newTemplate.setPodRetention(step.getPodRetention());
    if (step.getActiveDeadlineSeconds() != 0) {
        newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds());
    }
    for (ContainerTemplate container : newTemplate.getContainers()) {
        if (!PodTemplateUtils.validateContainerName(container.getName())) {
            throw new AbortException(Messages.RFC1123_error(container.getName()));
        }
    }
    Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls());
    if (!errors.isEmpty()) {
        throw new AbortException(Messages.RFC1123_error(String.join(", ", errors)));
    }
    if (VERBOSE) {
        listener.getLogger().println("Registering template with id=" + newTemplate.getId() + ",label=" + newTemplate.getLabel());
    }
    cloud.addDynamicTemplate(newTemplate);
    BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate));
    if (step.getLabel() == null) {
        invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label))));
    }
    invoker.start();
    return false;
}
Also used : PodAnnotation(org.csanchez.jenkins.plugins.kubernetes.PodAnnotation) PodImagePullSecret(org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret) KubernetesCloud(org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud) ContainerTemplate(org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate) TaskListener(hudson.model.TaskListener) BodyInvoker(org.jenkinsci.plugins.workflow.steps.BodyInvoker) PodTemplate(org.csanchez.jenkins.plugins.kubernetes.PodTemplate) AbortException(hudson.AbortException)

Example 2 with BodyInvoker

use of org.jenkinsci.plugins.workflow.steps.BodyInvoker in project lockable-resources-plugin by jenkinsci.

the class LockStepExecution method proceed.

public static void proceed(final List<String> resourceNames, StepContext context, String resourceDescription, final String variable, boolean inversePrecedence) {
    Run<?, ?> r;
    FlowNode node;
    try {
        r = context.get(Run.class);
        node = context.get(FlowNode.class);
        context.get(TaskListener.class).getLogger().println("Lock acquired on [" + resourceDescription + "]");
    } catch (Exception e) {
        context.onFailure(e);
        return;
    }
    LOGGER.finest("Lock acquired on [" + resourceDescription + "] by " + r.getExternalizableId());
    try {
        PauseAction.endCurrentPause(node);
        BodyInvoker bodyInvoker = context.newBodyInvoker().withCallback(new Callback(resourceNames, resourceDescription, inversePrecedence));
        if (variable != null && variable.length() > 0) {
            // set the variable for the duration of the block
            bodyInvoker.withContext(EnvironmentExpander.merge(context.get(EnvironmentExpander.class), new EnvironmentExpander() {

                private static final long serialVersionUID = -3431466225193397896L;

                @Override
                public void expand(@NonNull EnvVars env) {
                    final Map<String, String> variables = new HashMap<>();
                    final String resources = String.join(",", resourceNames);
                    variables.put(variable, resources);
                    for (int index = 0; index < resourceNames.size(); ++index) {
                        variables.put(variable + index, resourceNames.get(index));
                    }
                    LOGGER.finest("Setting " + variables.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining(", ")) + " for the duration of the block");
                    env.overrideAll(variables);
                }
            }));
        }
        bodyInvoker.start();
    } catch (IOException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : HashMap(java.util.HashMap) EnvironmentExpander(org.jenkinsci.plugins.workflow.steps.EnvironmentExpander) Run(hudson.model.Run) IOException(java.io.IOException) IOException(java.io.IOException) BodyExecutionCallback(org.jenkinsci.plugins.workflow.steps.BodyExecutionCallback) EnvVars(hudson.EnvVars) NonNull(edu.umd.cs.findbugs.annotations.NonNull) BodyInvoker(org.jenkinsci.plugins.workflow.steps.BodyInvoker) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode)

Aggregations

BodyInvoker (org.jenkinsci.plugins.workflow.steps.BodyInvoker)2 NonNull (edu.umd.cs.findbugs.annotations.NonNull)1 AbortException (hudson.AbortException)1 EnvVars (hudson.EnvVars)1 Run (hudson.model.Run)1 TaskListener (hudson.model.TaskListener)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 ContainerTemplate (org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate)1 KubernetesCloud (org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud)1 PodAnnotation (org.csanchez.jenkins.plugins.kubernetes.PodAnnotation)1 PodImagePullSecret (org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret)1 PodTemplate (org.csanchez.jenkins.plugins.kubernetes.PodTemplate)1 FlowNode (org.jenkinsci.plugins.workflow.graph.FlowNode)1 BodyExecutionCallback (org.jenkinsci.plugins.workflow.steps.BodyExecutionCallback)1 EnvironmentExpander (org.jenkinsci.plugins.workflow.steps.EnvironmentExpander)1