// JENKINS-23264
  private Object readResolve() {
    DescriptorImpl d = getDescriptor();
    if (providers == null) {
      providers = d.builders;
    }

    if (providers == null) {
      providers = d.emptyProviders();
    }

    return this;
  }
Пример #2
0
  /**
   * Run the SCM trigger with additional build actions. Used by SubversionRepositoryStatus to
   * trigger a build at a specific revisionn number.
   *
   * @param additionalActions
   * @since 1.375
   */
  public void run(Action[] additionalActions) {
    if (Hudson.getInstance().isQuietingDown()) return; // noop

    DescriptorImpl d = getDescriptor();

    LOGGER.fine("Scheduling a polling for " + job);
    if (d.synchronousPolling) {
      LOGGER.fine(
          "Running the trigger directly without threading, "
              + "as it's already taken care of by Trigger.Cron");
      new Runner(additionalActions).run();
    } else {
      // schedule the polling.
      // even if we end up submitting this too many times, that's OK.
      // the real exclusion control happens inside Runner.
      LOGGER.fine("scheduling the trigger to (asynchronously) run");
      d.queue.execute(new Runner(additionalActions));
      d.clogCheck();
    }
  }
Пример #3
0
  private void updateGeneratedJobMap(
      AbstractProject<?, ?> seedJob,
      Set<GeneratedJob> createdOrUpdatedJobs,
      Set<GeneratedJob> removedJobs)
      throws IOException {
    DescriptorImpl descriptor = Jenkins.getInstance().getDescriptorByType(DescriptorImpl.class);
    boolean descriptorMutated = false;
    Map<String, SeedReference> generatedJobMap = descriptor.getGeneratedJobMap();

    for (GeneratedJob generatedJob : createdOrUpdatedJobs) {
      Item item = getLookupStrategy().getItem(seedJob, generatedJob.getJobName(), Item.class);
      if (item != null) {
        SeedReference newSeedReference = new SeedReference(seedJob.getFullName());
        if (generatedJob.getTemplateName() != null) {
          Item template =
              getLookupStrategy().getItem(seedJob, generatedJob.getTemplateName(), Item.class);
          newSeedReference.setTemplateJobName(template.getFullName());
        }
        newSeedReference.setDigest(Util.getDigestOf(Items.getConfigFile(item).getFile()));

        SeedReference oldSeedReference = generatedJobMap.get(item.getFullName());
        if (!newSeedReference.equals(oldSeedReference)) {
          generatedJobMap.put(item.getFullName(), newSeedReference);
          descriptorMutated = true;
        }
      }
    }

    for (GeneratedJob removedJob : removedJobs) {
      Item removedItem = getLookupStrategy().getItem(seedJob, removedJob.getJobName(), Item.class);
      if (removedItem != null) {
        generatedJobMap.remove(removedItem.getFullName());
        descriptorMutated = true;
      }
    }

    if (descriptorMutated) {
      descriptor.save();
    }
  }
  /**
   * Returns the HTTP POST request ready to be sent to the Stash build API for the given build and
   * change set.
   *
   * @param stashBuildNotificationEntity a entity containing the parameters for Stash
   * @param commitSha1 the SHA1 of the commit that was built
   * @return the HTTP POST request to the Stash build API
   */
  private HttpPost createRequest(
      final HttpEntity stashBuildNotificationEntity, final String commitSha1) {

    String url = stashServerBaseUrl;
    String username = stashUserName;
    String pwd = Secret.toString(stashUserPassword);
    DescriptorImpl descriptor = getDescriptor();

    if ("".equals(url) || url == null) url = descriptor.getStashRootUrl();
    if ("".equals(username) || username == null) username = descriptor.getStashUser();
    if ("".equals(pwd) || pwd == null) pwd = descriptor.getStashPassword().getPlainText();

    HttpPost req = new HttpPost(url + "/rest/build-status/1.0/commits/" + commitSha1);

    req.addHeader(
        BasicScheme.authenticate(new UsernamePasswordCredentials(username, pwd), "UTF-8", false));

    req.addHeader("Content-type", "application/json");
    req.setEntity(stashBuildNotificationEntity);

    return req;
  }
 private void responseCodeIsValid(ResponseContentSupplier response, PrintStream logger)
     throws AbortException {
   List<Range<Integer>> ranges = DescriptorImpl.parseToRange(validResponseCodes);
   for (Range<Integer> range : ranges) {
     if (range.contains(response.getStatus())) {
       logger.println("Success code from " + range);
       return;
     }
   }
   throw new AbortException(
       "Fail: the returned code "
           + response.getStatus()
           + " is not in the accepted range: "
           + ranges);
 }
  /**
   * Returns the HttpClient through which the REST call is made. Uses an unsafe TrustStrategy in
   * case the user specified a HTTPS URL and set the ignoreUnverifiedSSLPeer flag.
   *
   * @param logger the logger to log messages to
   * @return the HttpClient
   */
  private HttpClient getHttpClient(PrintStream logger) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String stashServer = stashServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();
    if ("".equals(stashServer) || stashServer == null) {
      stashServer = descriptor.getStashRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
      ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(stashServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https") && ignoreUnverifiedSSL) {
      // add unsafe trust manager to avoid thrown
      // SSLPeerUnverifiedException
      try {
        TrustStrategy easyStrategy =
            new TrustStrategy() {
              public boolean isTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {
                return true;
              }
            };

        SSLContext sslContext =
            SSLContexts.custom().loadTrustMaterial(null, easyStrategy).useTLS().build();
        SSLConnectionSocketFactory sslConnSocketFactory =
            new SSLConnectionSocketFactory(
                sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(sslConnSocketFactory);

        Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnSocketFactory)
                .build();

        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

        builder.setConnectionManager(ccm);
      } catch (NoSuchAlgorithmException nsae) {
        logger.println("Couldn't establish SSL context:");
        nsae.printStackTrace(logger);
      } catch (KeyManagementException kme) {
        logger.println("Couldn't initialize SSL context:");
        kme.printStackTrace(logger);
      } catch (KeyStoreException kse) {
        logger.println("Couldn't initialize SSL context:");
        kse.printStackTrace(logger);
      }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
      Proxy proxy = proxyConfig.createProxy(url.getHost());
      if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
        SocketAddress addr = proxy.address();
        if (addr != null && addr instanceof InetSocketAddress) {
          InetSocketAddress proxyAddr = (InetSocketAddress) addr;
          HttpHost proxyHost =
              new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
          builder = builder.setProxy(proxyHost);

          String proxyUser = proxyConfig.getUserName();
          if (proxyUser != null) {
            String proxyPass = proxyConfig.getPassword();
            CredentialsProvider cred = new BasicCredentialsProvider();
            cred.setCredentials(
                new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass));
            builder =
                builder
                    .setDefaultCredentialsProvider(cred)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
          }
        }
      }
    }

    return builder.build();
  }
Пример #7
0
  /** Uses generatedJobs as existing data, so call before updating generatedJobs. */
  private Set<String> updateTemplates(
      AbstractBuild<?, ?> build, BuildListener listener, Set<GeneratedJob> freshJobs)
      throws IOException {
    AbstractProject<?, ?> seedJob = build.getProject();

    Set<String> freshTemplates = getTemplates(freshJobs);
    Set<String> existingTemplates =
        getTemplates(extractGeneratedObjects(seedJob, GeneratedJobsAction.class));
    Set<String> newTemplates = Sets.difference(freshTemplates, existingTemplates);
    Set<String> removedTemplates = Sets.difference(existingTemplates, freshTemplates);

    logItems(listener, "Existing templates", existingTemplates);
    logItems(listener, "New templates", newTemplates);
    logItems(listener, "Unreferenced templates", removedTemplates);

    // Collect information about the templates we loaded
    final String seedJobName = seedJob.getName();
    DescriptorImpl descriptor = Jenkins.getInstance().getDescriptorByType(DescriptorImpl.class);
    boolean descriptorMutated = false;

    // Clean up
    for (String templateName : removedTemplates) {
      Collection<SeedReference> seedJobReferences =
          descriptor.getTemplateJobMap().get(templateName);
      Collection<SeedReference> matching =
          Collections2.filter(seedJobReferences, new SeedNamePredicate(seedJobName));
      if (!matching.isEmpty()) {
        seedJobReferences.removeAll(matching);
        descriptorMutated = true;
      }
    }

    // Ensure we have a reference
    for (String templateName : freshTemplates) {
      Collection<SeedReference> seedJobReferences =
          descriptor.getTemplateJobMap().get(templateName);
      Collection<SeedReference> matching =
          Collections2.filter(seedJobReferences, new SeedNamePredicate(seedJobName));

      AbstractProject templateProject =
          getLookupStrategy().getItem(seedJob, templateName, AbstractProject.class);
      final String digest =
          Util.getDigestOf(new FileInputStream(templateProject.getConfigFile().getFile()));

      if (matching.size() == 1) {
        // Just update digest
        SeedReference ref = Iterables.get(matching, 0);
        if (digest.equals(ref.getDigest())) {
          ref.setDigest(digest);
          descriptorMutated = true;
        }
      } else {
        if (matching.size() > 1) {
          // Not sure how there could be more one, throw it all away and start over
          seedJobReferences.removeAll(matching);
        }
        seedJobReferences.add(new SeedReference(templateName, seedJobName, digest));
        descriptorMutated = true;
      }
    }

    if (descriptorMutated) {
      descriptor.save();
    }
    return freshTemplates;
  }