Java Code Examples for hudson.model.Run#getEnvironment()

The following examples show how to use hudson.model.Run#getEnvironment() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenShiftImageStreams.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> build,
        FilePath workspace, Launcher launcher, TaskListener listener)
        throws IOException, InterruptedException {
    EnvVars env = build.getEnvironment(listener);
    listener.getLogger().println(
            String.format(MessageConstants.SCM_CALC, DISPLAY_NAME,
                    getImageStreamName(env), tag, getNamespace(env)));

    String commitId = lastCommitId;

    ImageStreamRevisionState currIMSState = null;
    if (commitId != null) {
        currIMSState = new ImageStreamRevisionState(commitId);
        listener.getLogger().println(
                String.format(MessageConstants.SCM_LAST_REV,
                        currIMSState.toString()));
    } else {
        currIMSState = new ImageStreamRevisionState("");
        listener.getLogger().println(MessageConstants.SCM_NO_REV);
    }

    return currIMSState;
}
 
Example 2
Source File: LambdaInvokeBuildStep.java    From aws-lambda-jenkins-plugin with MIT License 6 votes vote down vote up
public void perform(LambdaInvokeBuildStepVariables lambdaInvokeBuildStepVariables,Run<?, ?> run, Launcher launcher, TaskListener listener) {
    try {
        LambdaInvokeBuildStepVariables executionVariables = lambdaInvokeBuildStepVariables.getClone();
        executionVariables.expandVariables(run.getEnvironment(listener));
        LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig();
        InvokeConfig invokeConfig = executionVariables.getInvokeConfig();

        InvokeCallable invokeCallable = new InvokeCallable(listener, invokeConfig, clientConfig);

        LambdaInvocationResult invocationResult = launcher.getChannel().call(invokeCallable);
        if(!invocationResult.isSuccess()){
            run.setResult(Result.FAILURE);
        }
        for (Map.Entry<String,String> entry : invocationResult.getInjectables().entrySet()) {
            run.addAction(new LambdaOutputInjectionAction(entry.getKey(), entry.getValue()));
        }
        run.getEnvironment(listener);
        run.addAction(new LambdaInvokeAction(executionVariables.getFunctionName(), invocationResult.isSuccess()));
    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }
}
 
Example 3
Source File: JenkinsModule.java    From appcenter-plugin with MIT License 5 votes vote down vote up
@Provides
@Singleton
static EnvVars provideEnvVars(Run<?, ?> run, TaskListener taskListener) throws RuntimeException {
    final PrintStream logger = taskListener.getLogger();
    try {
        return run.getEnvironment(taskListener);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace(logger);
        throw new RuntimeException("Failed to get Environment Variables.");
    }
}
 
Example 4
Source File: GitChangelogPerformer.java    From git-changelog-plugin with MIT License 5 votes vote down vote up
public static void performerPerform(
    final GitChangelogConfig configUnexpanded,
    final Run<?, ?> build,
    final TaskListener listener,
    final FilePath workspace) {
  try {
    final EnvVars env = build.getEnvironment(listener);
    final GitChangelogConfig config = expand(configUnexpanded, env);
    listener.getLogger().println("---");
    listener.getLogger().println("--- Git Changelog ---");
    listener.getLogger().println("---");

    setApiTokenCredentials(config, listener);

    final RemoteCallable remoteTask = new RemoteCallable(workspace.getRemote(), config);
    final RemoteResult remoteResult = workspace.act(remoteTask);
    if (!isNullOrEmpty(remoteResult.getLeftSideTitle())) {
      build.addAction(
          new GitChangelogLeftsideBuildDecorator(
              remoteResult.getLeftSideTitle(), remoteResult.getLeftSideUrl()));
    }
    if (!isNullOrEmpty(remoteResult.getSummary())) {
      build.addAction(new GitChangelogSummaryDecorator(remoteResult.getSummary()));
    }
    doLog(listener, INFO, remoteResult.getLog());
  } catch (final Exception e) {
    doLog(listener, SEVERE, e.getMessage(), e);
  }
}
 
Example 5
Source File: OpenShiftImageStreams.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void checkout(Run<?, ?> build, Launcher launcher,
        FilePath workspace, TaskListener listener, File changelogFile,
        SCMRevisionState baseline) throws IOException, InterruptedException {
    boolean chatty = Boolean.parseBoolean(verbose);

    String bldName = null;
    if (build != null)
        bldName = build.getDisplayName();
    if (chatty)
        listener.getLogger().println(
                "\n\nOpenShiftImageStreams checkout called for " + bldName);

    EnvVars env = build.getEnvironment(listener);
    lastCommitId = getCommitId(listener, env);
    if (lastCommitId == null) {
        String imageStream = getImageStreamName(env);
        String tag = getTag(env);
        listener.getLogger().println(
                String.format(MessageConstants.SCM_IMAGESTREAM_NOT_FOUND,
                        imageStream, tag));
        // We cannot yet throw an exception here because the calling code
        // will be interrupted and the SCM action
        // will not be added to the build job.
        // Just setting the build result here. An exception will be thrown
        // in the postCheckout method.
        build.setResult(Result.FAILURE);
    }
}
 
Example 6
Source File: OpenShiftImageStreams.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void postCheckout(@Nonnull Run<?, ?> build,
        @Nonnull Launcher launcher, @Nonnull FilePath workspace,
        @Nonnull TaskListener listener) throws IOException,
        InterruptedException {
    if (build.getResult() == Result.FAILURE) {
        EnvVars env = build.getEnvironment(listener);
        String msg = String.format(
                MessageConstants.SCM_IMAGESTREAM_NOT_FOUND,
                getImageStreamName(env), getTag(env));
        throw new AbortException(msg);
    }
}
 
Example 7
Source File: AbstractAnsibleInvocation.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
protected AbstractAnsibleInvocation(String exe, Run<?, ?> build, FilePath ws, TaskListener listener)
        throws IOException, InterruptedException, AnsibleInvocationException
{
    this.build = build;
    this.ws = ws;
    this.envVars = build.getEnvironment(listener);
    this.listener = listener;
    this.exe = exe;
    if (exe == null) {
        throw new AnsibleInvocationException("Ansible executable not found, check your installation.");
    }
}
 
Example 8
Source File: VariableUtils.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
/**
 * Resolve on remoting side during execution.
 * Because node may have some specific node vars.
 */
public static String resolveVar(String var, Run run, TaskListener taskListener) {
    String resolvedVar = var;
    try {
        final EnvVars envVars = run.getEnvironment(taskListener);
        resolvedVar = envVars.expand(var);
    } catch (IOException | InterruptedException e) {
        LOG.warn("Can't resolve variable " + var + " for {}", run, e);
    }
    return resolvedVar;
}
 
Example 9
Source File: JvctgPerformer.java    From violation-comments-to-github-plugin with MIT License 4 votes vote down vote up
public static void jvctsPerform(
    final ViolationsToGitHubConfig configUnexpanded,
    final FilePath fp,
    final Run<?, ?> build,
    final TaskListener listener) {
  final PrintStream logger = listener.getLogger();
  try {
    final EnvVars env = build.getEnvironment(listener);
    final ViolationsToGitHubConfig configExpanded = expand(configUnexpanded, env);
    logger.println("---");
    logger.println("--- Jenkins Violation Comments to GitHub ---");
    logger.println("---");
    logConfiguration(configExpanded, build, listener);

    final Optional<StandardCredentials> credentials =
        findCredentials(
            build.getParent(), configExpanded.getCredentialsId(), configExpanded.getGitHubUrl());

    if (!isNullOrEmpty(configExpanded.getoAuth2Token())) {
      logger.println("Using OAuth2Token");
    } else if (credentials.isPresent()) {
      final StandardCredentials standardCredentials = credentials.get();
      if (standardCredentials instanceof StandardUsernamePasswordCredentials) {
        logger.println("Using username / password");
      } else if (standardCredentials instanceof StringCredentials) {
        logger.println("Using OAuth2Token credential style");
      }
    } else {
      throw new IllegalStateException("No credentials found!");
    }

    logger.println("Running Jenkins Violation Comments To GitHub");
    logger.println("PR " + configExpanded.getPullRequestId());

    fp.act(
        new FileCallable<Void>() {

          private static final long serialVersionUID = 6166111757469534436L;

          @Override
          public void checkRoles(final RoleChecker checker) throws SecurityException {}

          @Override
          public Void invoke(final File workspace, final VirtualChannel channel)
              throws IOException, InterruptedException {
            setupFindBugsMessages();
            listener.getLogger().println("Workspace: " + workspace.getAbsolutePath());
            doPerform(configExpanded, workspace, credentials.orNull(), listener);
            return null;
          }
        });
  } catch (final Exception e) {
    Logger.getLogger(JvctgPerformer.class.getName()).log(SEVERE, "", e);
    final StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    logger.println(sw.toString());
    return;
  }
}
 
Example 10
Source File: DingTalkPipeline.java    From dingtalk-plugin with MIT License 4 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace,
    @Nonnull Launcher launcher, @Nonnull TaskListener listener)
    throws InterruptedException, IOException {

  EnvVars envVars = run.getEnvironment(listener);

  boolean defaultBtns = MsgTypeEnum.ACTION_CARD.equals(type) &&
      StringUtils.isEmpty(singleTitle) &&
      (btns == null || btns.isEmpty());

  if (defaultBtns) {
    String jobUrl = rootPath + run.getUrl();
    this.btns = Utils.createDefaultBtns(jobUrl);
  } else if (btns != null) {
    btns.forEach(item -> {
      item.setTitle(
          envVars.expand(
              item.getTitle()
          )
      );
      item.setActionUrl(
          envVars.expand(
              item.getActionUrl()
          )
      );
    });
  }

  if (at != null) {
    String atStr = envVars.expand(
        Utils.join(at)
    );

    this.at = new HashSet<>(
        Arrays.asList(
            Utils.split(atStr)
        )
    );
  }

  String result = service.send(
      robot,
      MessageModel.builder()
          .type(type)
          .atMobiles(at)
          .atAll(atAll)
          .title(
              envVars.expand(title)
          )
          .text(
              envVars.expand(
                  Utils.join(text)
              )
          )
          .messageUrl(
              envVars.expand(messageUrl)
          )
          .picUrl(
              envVars.expand(picUrl)
          )
          .singleTitle(
              envVars.expand(singleTitle)
          )
          .singleUrl(
              envVars.expand(singleUrl)
          )
          .btns(btns)
          .btnOrientation(
              getBtnLayout()
          )
          .hideAvatar(isHideAvatar())
          .build()
  );
  if (!StringUtils.isEmpty(result)) {
    Logger.error(listener, result);
  }
}
 
Example 11
Source File: JvctbPerformer.java    From violation-comments-to-stash-plugin with MIT License 4 votes vote down vote up
public static void jvctsPerform(
    final ProxyConfigDetails proxyConfigDetails,
    final ViolationsToBitbucketServerConfig configUnexpanded,
    final FilePath fp,
    final Run<?, ?> build,
    final TaskListener listener) {
  try {
    final EnvVars env = build.getEnvironment(listener);
    final ViolationsToBitbucketServerConfig configExpanded = expand(configUnexpanded, env);
    listener.getLogger().println("---");
    listener.getLogger().println("--- Jenkins Violation Comments to Bitbucket Server ---");
    listener.getLogger().println("---");
    logConfiguration(configExpanded, build, listener);

    final Optional<StandardCredentials> credentials =
        findCredentials(
            build.getParent(),
            configExpanded.getCredentialsId(),
            configExpanded.getBitbucketServerUrl());

    if (!credentials.isPresent()) {
      listener.getLogger().println("Credentials not found!");
      return;
    }

    listener.getLogger().println("Pull request: " + configExpanded.getPullRequestId());

    fp.act(
        new FileCallable<Void>() {

          private static final long serialVersionUID = 6166111757469534436L;

          @Override
          public void checkRoles(final RoleChecker checker) throws SecurityException {}

          @Override
          public Void invoke(final File workspace, final VirtualChannel channel)
              throws IOException, InterruptedException {
            setupFindBugsMessages();
            listener.getLogger().println("Workspace: " + workspace.getAbsolutePath());
            doPerform(
                proxyConfigDetails, configExpanded, workspace, credentials.orNull(), listener);
            return null;
          }
        });
  } catch (final Exception e) {
    Logger.getLogger(JvctbPerformer.class.getName()).log(SEVERE, "", e);
    final StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    listener.getLogger().println(sw.toString());
    return;
  }
}
 
Example 12
Source File: ContainerStepExecution.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 13
Source File: AWSCodeDeployPublisher.java    From aws-codedeploy-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void perform(@Nonnull Run<?,?> build, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    this.logger = listener.getLogger();
    envVars = build.getEnvironment(listener);
    final boolean buildFailed = build.getResult() == Result.FAILURE;
    if (buildFailed) {
        logger.println("Skipping CodeDeploy publisher as build failed");
        return;
    }

    final AWSClients aws;
    if ("awsAccessKey".equals(credentials)) {
        if (StringUtils.isEmpty(this.awsAccessKey) && StringUtils.isEmpty(this.awsSecretKey)) {
            aws = AWSClients.fromDefaultCredentialChain(
                    this.region,
                    this.proxyHost,
                    this.proxyPort);
        } else {
            aws = AWSClients.fromBasicCredentials(
                    this.region,
                    this.awsAccessKey,
                    this.awsSecretKey,
                    this.proxyHost,
                    this.proxyPort);
        }
    } else {
        aws = AWSClients.fromIAMRole(
            this.region,
            this.iamRoleArn,
            this.getDescriptor().getExternalId(),
            this.proxyHost,
            this.proxyPort);
    }

    boolean success = false;

    try {

        verifyCodeDeployApplication(aws);

        final String projectName = build.getDisplayName();
        if (workspace == null) {
            throw new IllegalArgumentException("No workspace present for the build.");
        }

        RevisionLocation revisionLocation;

        if (!StringUtils.isEmpty(this.githubRepository) && !StringUtils.isEmpty(this.githubCommitId)) {
          revisionLocation = createFromGitHub();
        } else {
          final FilePath sourceDirectory = getSourceDirectory(workspace);
          revisionLocation = zipAndUpload(aws, projectName, sourceDirectory);
        }

        registerRevision(aws, revisionLocation);
        if ("onlyRevision".equals(deploymentMethod)){
          success = true;
        } else {

          String deploymentId = createDeployment(aws, revisionLocation);

          success = waitForDeployment(aws, deploymentId);
        }

    } catch (Exception e) {

        this.logger.println("Failed CodeDeploy post-build step; exception follows.");
        this.logger.println(e.getMessage());
        e.printStackTrace(this.logger);
    }

    if (!success) {
        throw new AbortException();
    }
}