Java源码示例:org.jenkinsci.plugins.workflow.steps.EnvironmentExpander

示例1
@Override
public boolean start() throws Exception {
	final EnvVars awsEnv = new EnvVars();
	this.withCredentials(this.getContext().get(Run.class), awsEnv);
	this.withProfile(awsEnv);
	this.withRegion(awsEnv);
	this.withEndpointUrl(awsEnv);
	this.withRole(awsEnv);
	this.withFederatedUserId(awsEnv);

	EnvironmentExpander expander = new EnvironmentExpander() {
		@Override
		public void expand(@Nonnull EnvVars envVars) {
			envVars.overrideAll(awsEnv);
		}
	};
	this.getContext().newBodyInvoker()
			.withContext(EnvironmentExpander.merge(this.getContext().get(EnvironmentExpander.class), expander))
			.withCallback(BodyExecutionCallback.wrap(this.getContext()))
			.start();
	return false;
}
 
示例2
@Override
public boolean onStart(SessionManager sessionManager) throws Exception {
    sessionManager.start();

    getContext().newBodyInvoker().
            withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new NamespaceExpander(session.getNamespace()))).
            withCallback(new SessionManagerStopCallback(sessionManager)).
            start();

    return false;
}
 
示例3
@Override
public boolean start() throws Exception {
    TaskListener listener = getContext().get(TaskListener.class);
    NamespaceAction namespaceAction = new NamespaceAction(getContext().get(Run.class));

    sessionId = generateSessionId();
    namespace = generateNamespaceId(step.getName(), step.getPrefix(), sessionId);

    client = getKubernetesClient();
    isOpenshift = client.isAdaptable(OpenShiftClient.class);

    configuration = new DefaultConfigurationBuilder()
            .withNamespace(namespace)
            .withNamespaceLazyCreateEnabled(step.isNamespaceLazyCreateEnabled())
            .withNamespaceDestroyEnabled(step.isNamespaceDestroyEnabled())
            .withMasterUrl(client.getMasterUrl())
            .build();

    StreamLogger logger = new StreamLogger(listener.getLogger());
    LabelProvider labelProvider = new MapLabelProvider(step.getLabels());

    namespaceService = isOpenshift
            ? new OpenshiftNamespaceService.ImmutableOpenshiftNamespaceService(client, configuration, labelProvider, logger)
            : new DefaultNamespaceService.ImmutableNamespaceService(client, configuration, labelProvider, logger);


    if (!namespaceService.exists(namespace) && configuration.isNamespaceLazyCreateEnabled()) {
        namespaceService.create(namespace);
    }
    namespaceAction.push(namespace);

    getContext().newBodyInvoker().
            withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new NamespaceExpander(namespace))).
            withCallback(new NamespaceDestructionCallback(namespace, configuration, namespaceService, namespaceAction)).
            start();

    return false;
}
 
示例4
private void doStart() throws Exception {
    KeyMaterialFactory keyMaterialFactory = newKeyMaterialFactory();
    KeyMaterial material = keyMaterialFactory.materialize();
    getContext().newBodyInvoker().
            withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Expander(material))).
            withCallback(new Callback(material)).
            start();
}
 
示例5
@Override
public boolean start() throws Exception {
    EnvironmentExpander envEx = EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class),
            EnvironmentExpander.constant(Collections.singletonMap("PATH+MODIFIER", step.getElement())));

    body = getContext().newBodyInvoker()
            .withContext(envEx)
            // Could use a dedicated BodyExecutionCallback here if we wished to print a message at the end ("Returning to ${cwd}"):
            .withCallback(BodyExecutionCallback.wrap(getContext()))
            .start();
    return false;
}
 
示例6
private void doStart() throws Exception {
    Run<?,?> run = getContext().get(Run.class);
    TaskListener listener = getContext().get(TaskListener.class);

    FilePath workspace = getContext().get(FilePath.class);
    Launcher launcher = getContext().get(Launcher.class);

    Map<String,String> overrides = new LinkedHashMap<>();
    List<MultiBinding.Unbinder> unbinders = new ArrayList<>();
    for (MultiBinding<?> binding : step.bindings) {
        if (binding.getDescriptor().requiresWorkspace() &&
                (workspace == null || launcher == null)) {
            throw new MissingContextVariableException(FilePath.class);
        }
        MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener);
        unbinders.add(environment.getUnbinder());
        overrides.putAll(environment.getValues());
    }
    if (!overrides.isEmpty()) {
        boolean unix = launcher != null ? launcher.isUnix() : true;
        listener.getLogger().println("Masking supported pattern matches of " + overrides.keySet().stream().map(
            v -> unix ? "$" + v : "%" + v + "%"
        ).collect(Collectors.joining(" or ")));
    }
    getContext().newBodyInvoker().
            withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))).
            withContext(BodyInvoker.mergeConsoleLogFilters(getContext().get(ConsoleLogFilter.class), new Filter(overrides.values(), run.getCharset().name()))).
            withCallback(new Callback2(unbinders)).
            start();
}
 
示例7
protected boolean doStart() throws Exception {
    envOverride = new EnvVars();
    console = listener.getLogger();

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Maven: {0}", step.getMaven());
        LOGGER.log(Level.FINE, "Jdk: {0}", step.getJdk());
        LOGGER.log(Level.FINE, "MavenOpts: {0}", step.getMavenOpts());
        LOGGER.log(Level.FINE, "Temporary Binary Directory: {0}", step.getTempBinDir());
        LOGGER.log(Level.FINE, "Settings Config: {0}", step.getMavenSettingsConfig());
        LOGGER.log(Level.FINE, "Settings FilePath: {0}", step.getMavenSettingsFilePath());
        LOGGER.log(Level.FINE, "Global settings Config: {0}", step.getGlobalMavenSettingsConfig());
        LOGGER.log(Level.FINE, "Global settings FilePath: {0}", step.getGlobalMavenSettingsFilePath());
        LOGGER.log(Level.FINE, "Options: {0}", step.getOptions());
        LOGGER.log(Level.FINE, "env.PATH: {0}", env.get("PATH")); // JENKINS-40484
        LOGGER.log(Level.FINE, "ws: {0}", ws.getRemote()); // JENKINS-47804
    }

    listener.getLogger().println("[withMaven] Options: " + step.getOptions());
    ExtensionList<MavenPublisher> availableMavenPublishers = Jenkins.getInstance().getExtensionList(MavenPublisher.class);
    listener.getLogger().println("[withMaven] Available options: " + availableMavenPublishers.stream().map(publisher -> publisher.toString()).collect(Collectors.joining(",")));

    getComputer();

    withContainer = detectWithContainer();

    if (withContainer) {
        listener.getLogger().print("[withMaven] IMPORTANT \"withMaven(){...}\" step running within a Docker container. See " );
        listener.hyperlink("https://github.com/jenkinsci/pipeline-maven-plugin/blob/master/jenkins-plugin/src/resources/faq.md#how-to-use-the-pipeline-maven-plugin-with-docker-since-version-303", "Pipeline Maven Plugin FAQ");
        listener.getLogger().println(" in case of problem.");
    }

    setupJDK();

    // list of credentials injected by withMaven. They will be tracked and masked in the logs
    Collection<Credentials> credentials = new ArrayList<>();
    setupMaven(credentials);

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, this.build + " - Track usage and mask password of credentials " + credentials.stream().map(new CredentialsToPrettyString()).collect(Collectors.joining(",")));
    }
    CredentialsProvider.trackAll(build, new ArrayList<>(credentials));

    ConsoleLogFilter originalFilter = getContext().get(ConsoleLogFilter.class);
    ConsoleLogFilter maskSecretsFilter = MaskPasswordsConsoleLogFilter.newMaskPasswordsConsoleLogFilter(credentials, getComputer().getDefaultCharset());
    MavenColorizerConsoleLogFilter mavenColorizerFilter = new MavenColorizerConsoleLogFilter(getComputer().getDefaultCharset().name());

    ConsoleLogFilter newFilter = BodyInvoker.mergeConsoleLogFilters(
            BodyInvoker.mergeConsoleLogFilters(originalFilter, maskSecretsFilter),
            mavenColorizerFilter);

    EnvironmentExpander envEx = EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new ExpanderImpl(envOverride));

    LOGGER.log(Level.FINEST, "envOverride: {0}", envOverride); // JENKINS-40484

    body = getContext().newBodyInvoker().withContexts(envEx, newFilter).withCallback(new WithMavenStepExecutionCallBack(tempBinDir, step.getOptions(), step.getPublisherStrategy())).start();

    return false;
}
 
示例8
@Deprecated
public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, String namespace, EnvironmentExpander environmentExpander, FilePath ws) {
    this.containerName = containerName;
    this.environmentExpander = environmentExpander;
    this.ws = ws;
}
 
示例9
@Deprecated
public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, String namespace, EnvironmentExpander environmentExpander) {
    this(client, podName, containerName, namespace, environmentExpander, null);
}
 
示例10
public EnvironmentExpander getEnvironmentExpander() {
    return environmentExpander;
}
 
示例11
public void setEnvironmentExpander(EnvironmentExpander environmentExpander) {
    this.environmentExpander = environmentExpander;
}
 
示例12
@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(Strings.emptyToNull(parentTemplates));
    } else {
        newTemplate.setInheritFrom(Strings.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.setRunAsUser(step.getRunAsUser());
    newTemplate.setRunAsGroup(step.getRunAsGroup());
    if (step.getHostNetwork() != null) {
        newTemplate.setHostNetwork(step.getHostNetwork());
    }
    newTemplate.setAnnotations(step.getAnnotations());
    newTemplate.setListener(getContext().get(TaskListener.class));
    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)));
    }

    // Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally.
    if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) {
        throw new AbortException(Messages.label_error(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;
}
 
示例13
@Override
public boolean start() throws Exception {
    LOGGER.log(Level.FINE, "Starting container step.");
    String containerName = step.getName();
    String shell = step.getShell();

    KubernetesNodeContext nodeContext = new KubernetesNodeContext(getContext());

    EnvironmentExpander env = getContext().get(EnvironmentExpander.class);
    EnvVars globalVars = null;
    Jenkins instance = Jenkins.getInstance();

    DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
    List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties
            .getAll(EnvironmentVariablesNodeProperty.class);
    if (envVarsNodePropertyList != null && envVarsNodePropertyList.size() != 0) {
        globalVars = envVarsNodePropertyList.get(0).getEnvVars();
    }

    EnvVars rcEnvVars = null;
    Run run = getContext().get(Run.class);
    TaskListener taskListener = getContext().get(TaskListener.class);
    if(run!=null && taskListener != null) {
        rcEnvVars = run.getEnvironment(taskListener);
    }

    decorator = new ContainerExecDecorator();
    decorator.setNodeContext(nodeContext);
    decorator.setContainerName(containerName);
    decorator.setEnvironmentExpander(env);
    decorator.setWs(getContext().get(FilePath.class));
    decorator.setGlobalVars(globalVars);
    decorator.setRunContextEnvVars(rcEnvVars);
    decorator.setShell(shell);
    getContext().newBodyInvoker()
            .withContext(BodyInvoker
                    .mergeLauncherDecorators(getContext().get(LauncherDecorator.class), decorator))
            .withCallback(new ContainerExecCallback(decorator))
            .start();
    return false;
}