Example #1
0
  public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml)
      throws IOException {
    acl.checkPermission(Job.CREATE);

    Jenkins.getInstance().getProjectNamingStrategy().checkName(name);
    // place it as config.xml
    File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
    configXml.getParentFile().mkdirs();
    try {
      IOUtils.copy(xml, configXml);

      // load it
      TopLevelItem result;
      Items.updatingByXml.set(true);
      try {
        result = (TopLevelItem) Items.load(parent, configXml.getParentFile());
      } finally {
        Items.updatingByXml.set(false);
      }
      add(result);

      ItemListener.fireOnCreated(result);
      Jenkins.getInstance().rebuildDependencyGraph();

      return result;
    } catch (IOException e) {
      // if anything fails, delete the config file to avoid further confusion
      Util.deleteRecursive(configXml.getParentFile());
      throw e;
    }
  }
Example #2
0
  public synchronized TopLevelItem createProject(
      TopLevelItemDescriptor type, String name, boolean notify) throws IOException {
    acl.checkPermission(Job.CREATE);

    Jenkins.getInstance().getProjectNamingStrategy().checkName(name);
    if (parent.getItem(name) != null)
      throw new IllegalArgumentException("Project of the name " + name + " already exists");

    TopLevelItem item;
    try {
      item = type.newInstance(parent, name);
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
    try {
      callOnCreatedFromScratch(item);
    } catch (AbstractMethodError e) {
      // ignore this error. Must be older plugin that doesn't have this method
    }
    item.save();
    add(item);
    Jenkins.getInstance().rebuildDependencyGraph();

    if (notify) ItemListener.fireOnCreated(item);

    return item;
  }
 public static String getRootUrl() {
   if (Jenkins.getInstance() == null || Jenkins.getInstance().getRootUrl() == null) {
     return "http://localhost:8080/";
   } else {
     return Jenkins.getInstance().getRootUrl();
   }
 }
 /**
  * Construct an object from parameters input by a user.
  *
  * <p>Not using {@link DataBoundConstructor}, but using {@link
  * Descriptor#newInstance(StaplerRequest, JSONObject)}.
  *
  * @param req
  * @param formData
  * @param fieldName used for exception information.
  * @return
  * @throws hudson.model.Descriptor.FormException
  */
 private BuildStep bindJSONWithDescriptor(
     StaplerRequest req, JSONObject formData, String fieldName)
     throws hudson.model.Descriptor.FormException {
   if (formData == null || formData.isNullObject()) {
     return null;
   }
   String clazzName = formData.optString("$class", null);
   if (clazzName == null) {
     // Fall back on the legacy stapler-class attribute.
     clazzName = formData.optString("stapler-class", null);
   }
   if (clazzName == null) {
     throw new FormException("No $class or stapler-class is specified", fieldName);
   }
   try {
     @SuppressWarnings("unchecked")
     Class<? extends Describable<?>> clazz =
         (Class<? extends Describable<?>>)
             Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(clazzName);
     Descriptor<?> d = Jenkins.getInstance().getDescriptorOrDie(clazz);
     return (BuildStep) d.newInstance(req, formData);
   } catch (ClassNotFoundException e) {
     throw new FormException(
         String.format("Failed to instantiate: class not found %s", clazzName), e, fieldName);
   }
 }
  public void testDoDelete() throws Exception {
    UpdateSite target = new UpdateSite("test1", "http://example.com/test/update-center.json");

    Jenkins.getInstance().getUpdateCenter().getSites().clear();
    Jenkins.getInstance().getUpdateCenter().getSites().add(target);

    int initialSize = Jenkins.getInstance().getUpdateCenter().getSites().size();

    WebClient wc = new WebClient();

    HtmlPage deleteSitePage =
        wc.goTo(String.format("%s/%s/delete", UpdateSitesManager.URL, target.getId()));
    assertEquals(
        "UpdateSite must not be deleted yet.",
        initialSize,
        Jenkins.getInstance().getUpdateCenter().getSites().size());

    HtmlForm deleteSiteForm = deleteSitePage.getFormByName("deleteSiteForm");
    assertNotNull("There must be deleteSiteForm", deleteSiteForm);

    submit(deleteSiteForm);
    assertEquals(
        "UpdateSite must be deleted.",
        initialSize - 1,
        Jenkins.getInstance().getUpdateCenter().getSites().size());
  }
  public void testDoConfigure() throws Exception {
    UpdateSite target = new UpdateSite("test1", "http://example.com/test/update-center.json");

    // Multiple update site.
    Jenkins.getInstance().getUpdateCenter().getSites().clear();
    Jenkins.getInstance().getUpdateCenter().getSites().add(target);

    String originalId = target.getId();

    WebClient wc = new WebClient();

    HtmlPage editSitePage = wc.goTo(String.format("%s/%s", UpdateSitesManager.URL, target.getId()));

    HtmlForm editSiteForm = editSitePage.getFormByName("editSiteForm");
    assertNotNull("There must be editSiteForm", editSiteForm);

    String newId = "newId";
    String newUrl = "http://localhost/update-center.json";
    editSiteForm.getInputByName("_.id").setValueAttribute(newId);
    editSiteForm.getInputByName("_.url").setValueAttribute(newUrl);
    submit(editSiteForm);

    UpdateSite site = null;
    for (UpdateSite s : Jenkins.getInstance().getUpdateCenter().getSites()) {
      if (newId.equals(s.getId())) {
        site = s;
      }
      assertFalse("id must be updated(old one must not remain)", originalId.equals(s.getId()));
    }
    assertNotNull("id must be updated", site);
    assertEquals("url must be updated", newUrl, site.getUrl());
  }
Example #7
0
 /**
  * Since this shares much of the configuration with {@link EC2Computer}, check its help page,
  * too.
  */
 @Override
 public String getHelpFile(String fieldName) {
   String p = super.getHelpFile(fieldName);
   if (p == null)
     p = Jenkins.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName);
   if (p == null)
     p = Jenkins.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName);
   return p;
 }
Example #8
0
 /** Really deletes the slave. */
 @CLIMethod(name = "delete-node")
 public HttpResponse doDoDelete() throws IOException {
   checkPermission(DELETE);
   Node node = getNode();
   if (node != null) {
     Jenkins.getInstance().removeNode(node);
   } else {
     AbstractCIBase app = Jenkins.getInstance();
     app.removeComputer(this);
   }
   return new HttpRedirect("..");
 }
Example #9
0
 private void redirectToBuildPage(StaplerResponse res, Run build) {
   if (build != null) {
     try {
       res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getUrl());
     } catch (IOException e) {
       try {
         res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl());
       } catch (IOException e1) {
         e1.printStackTrace();
       }
     }
   }
 }
  /**
   * Returns the description of the build used for the Stash notification. Uses the build
   * description provided by the Jenkins job, if available.
   *
   * @param build the build to be described
   * @param state the state of the build
   * @return the description of the build
   */
  private String getBuildDescription(final AbstractBuild<?, ?> build, final StashBuildState state) {

    if (build.getDescription() != null && build.getDescription().trim().length() > 0) {

      return build.getDescription();
    } else {
      switch (state) {
        case INPROGRESS:
          return "building on Jenkins @ " + Jenkins.getInstance().getRootUrl();
        default:
          return "built by Jenkins @ " + Jenkins.getInstance().getRootUrl();
      }
    }
  }
  /** Try to make this user a super-user */
  private void tryToMakeAdmin(User u) throws IOException {
    WwpassIdentity p = u.getProperty(WwpassIdentity.class);
    p.activate();
    u.save();
    AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy();

    for (PermissionAdder adder : Jenkins.getInstance().getExtensionList(PermissionAdder.class)) {
      if (adder.add(as, u, Jenkins.ADMINISTER)) {
        return;
      }
    }
    LOGGER.severe(
        "Admin permission wasn't added for user: "******", ID: " + u.getId());
  }
Example #12
0
  public List<Queue.Item> getQueueItems() {
    if (!isFilterQueue()) {
      return Arrays.asList(Jenkins.getInstance().getQueue().getItems());
    }

    Collection<TopLevelItem> items = getItems();
    List<Queue.Item> result = new ArrayList<Queue.Item>();
    for (Queue.Item qi : Jenkins.getInstance().getQueue().getItems()) {
      if (items.contains(qi.task)) {
        result.add(qi);
      }
    }
    return result;
  }
Example #13
0
  public HttpResponse doUpdateSources(StaplerRequest req) throws IOException {
    Jenkins.getInstance().checkPermission(CONFIGURE_UPDATECENTER);

    if (req.hasParameter("remove")) {
      UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
      BulkChange bc = new BulkChange(uc);
      try {
        for (String id : req.getParameterValues("sources")) uc.getSites().remove(uc.getById(id));
      } finally {
        bc.commit();
      }
    } else if (req.hasParameter("add")) return new HttpRedirect("addSite");

    return new HttpRedirect("./sites");
  }
Example #14
0
 public List<Action> getOwnerViewActions() {
   try {
     return _getOwnerViewActions();
   } catch (AbstractMethodError e) {
     return Jenkins.getInstance().getActions();
   }
 }
  public void testNativeMaven() throws Exception {
    MavenInstallation maven = configureDefaultMaven();
    String mavenPath = maven.getHome();
    Jenkins.getInstance()
        .getDescriptorByType(Maven.DescriptorImpl.class)
        .setInstallations(new MavenInstallation("maven", "THIS IS WRONG", NO_PROPERTIES));

    MavenModuleSet project = createMavenProject();
    project.setScm(new ExtractResourceSCM(getClass().getResource("/simple-projects.zip")));
    project.setAssignedLabel(slave.getSelfLabel());
    project.setJDK(jenkins.getJDK("default"));

    project.setMaven("maven");
    project.setGoals("clean");

    Run build = project.scheduleBuild2(0).get();
    assertBuildStatus(Result.FAILURE, build);

    ToolLocationNodeProperty property =
        new ToolLocationNodeProperty(
            new ToolLocationNodeProperty.ToolLocation(
                jenkins.getDescriptorByType(MavenInstallation.DescriptorImpl.class),
                "maven",
                mavenPath));
    slave.getNodeProperties().add(property);

    build = project.scheduleBuild2(0).get();
    System.out.println(build.getLog());
    assertBuildStatus(Result.SUCCESS, build);
  }
  private void handlePullRequestEvent(String payload) throws IOException {

    GitHub gitHub = createGitHub(JSONObject.fromObject(payload));

    if (gitHub == null) {
      return;
    }

    GHEventPayload.PullRequest pullRequest =
        gitHub.parseEventPayload(new StringReader(payload), GHEventPayload.PullRequest.class);

    if (SUPPORTED_EVENTS.contains(pullRequest.getAction())) {
      Authentication old = SecurityContextHolder.getContext().getAuthentication();
      SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
      try {
        for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
          PullRequestBuildTrigger trigger = job.getTrigger(PullRequestBuildTrigger.class);
          if (trigger != null && trigger.getBuildHandler() instanceof PullRequestBuildHandler) {
            ((PullRequestBuildHandler) trigger.getBuildHandler()).handle(pullRequest, gitHub);
          }
        }
      } finally {
        SecurityContextHolder.getContext().setAuthentication(old);
      }
    } else {
      LOGGER.warning(
          MessageFormat.format(
              "Unsupported pull request action: ''{0}''", pullRequest.getAction()));
    }
  }
  private void createCommitStatus(
      AbstractBuild<?, ?> build,
      TaskListener listener,
      String message,
      GHRepository repo,
      GHCommitState state)
      throws GhprcCommitStatusException {
    GhprcCause cause = Ghprc.getCause(build);

    String sha1 = cause.getCommit();
    String url = Jenkins.getInstance().getRootUrl() + build.getUrl();
    if (!StringUtils.isEmpty(statusUrl)) {
      url = Ghprc.replaceMacros(build, listener, statusUrl);
    }
    String context = Util.fixEmpty(commitStatusContext);
    context = Ghprc.replaceMacros(build, listener, context);

    listener
        .getLogger()
        .println(
            String.format(
                "Setting status of %s to %s with url %s and message: '%s'",
                sha1, state, url, message));
    if (context != null) {
      listener.getLogger().println(String.format("Using context: " + context));
    }
    try {
      repo.createCommitStatus(sha1, state, url, message, context);
    } catch (IOException e) {
      throw new GhprcCommitStatusException(e, state, message, cause.getPullID());
    }
  }
 @Override
 public final boolean start(StepContext context) {
   try {
     FilePath ws = context.get(FilePath.class);
     assert ws != null
         : context.getClass() + " failed to provide a FilePath even though one was requested";
     String remote = ws.getRemote();
     String node = null;
     for (Computer c : Jenkins.getInstance().getComputers()) {
       if (c.getChannel() == ws.getChannel()) {
         node = c.getName();
         break;
       }
     }
     if (node == null) {
       throw new IllegalStateException("no known node for " + ws);
     }
     register(
         context,
         task()
             .launch(
                 context.get(EnvVars.class),
                 ws,
                 context.get(Launcher.class),
                 context.get(TaskListener.class)),
         node,
         remote);
   } catch (Exception x) {
     context.onFailure(x);
   }
   return false;
   // TODO implement stop, however it is design (will need to call Controller.stop)
 }
Example #19
0
  /**
   * Return a list of projects which can be built
   *
   * @return
   */
  protected final List<AbstractProject<?, ?>> getProjects(String viewName) {

    List<AbstractProject<?, ?>> projects = new ArrayList<AbstractProject<?, ?>>();
    Collection<TopLevelItem> items = Jenkins.getInstance().getItems();
    View view = null;
    BulkBuilderAction bulkBuilderAction = new BulkBuilderAction();

    if (viewName != null) {
      for (View currentView : bulkBuilderAction.getViews()) {
        if (currentView.getViewName().equals(viewName)) {
          view = currentView;
        }
      }

      if (view != null) {
        items = view.getItems();
      }
    }

    for (AbstractProject<?, ?> project : Util.createSubList(items, AbstractProject.class)) {
      if (!project.isBuildable()) {
        continue;
      }
      projects.add(project);
    }

    return projects;
  }
  /** The login process starts from here. */
  public HttpResponse doCommenceLogin(
      StaplerRequest req,
      StaplerResponse rsp,
      @QueryParameter String from,
      @QueryParameter String ticket)
      throws ServletException, IOException {

    // TODO write login method
    String puid = authenticateInWwpass(ticket, certFile, keyFile);

    WwpassIdentity u;
    try {
      u = loadUserByUsername(puid);
    } catch (UsernameNotFoundException e) {
      if (allowsSignup()) {
        req.setAttribute("errorMessage", Messages.WwpassSecurityRealm_NoSuchUserAllowsSignup());
      } else {
        req.setAttribute("errorMessage", Messages.WwpassSecurityRealm_NoSuchUserDisableSignup());
      }
      req.getView(this, "login.jelly").forward(req, rsp);
      throw e;
    }
    if (!u.isAccountNonLocked() || !u.isEnabled()) {
      // throw new LockedException("Account is not activated for " + puid);
      throw new Failure(Messages.WwpassSecurityRealm_AccountNotActivated());
    }

    Authentication a = new WwpassAuthenticationToken(u.getNickname());
    a = this.getSecurityComponents().manager.authenticate(a);
    SecurityContextHolder.getContext().setAuthentication(a);

    return new HttpRedirect(Jenkins.getInstance().getRootUrl());
  }
  private GroovyShell createEngine(AbstractBuild<?, ?> build, TaskListener listener) {

    ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader;
    ScriptSandbox sandbox = null;
    CompilerConfiguration cc = new CompilerConfiguration();
    cc.addCompilationCustomizers(
        new ImportCustomizer()
            .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model"));

    ExtendedEmailPublisher publisher =
        build.getProject().getPublishersList().get(ExtendedEmailPublisher.class);
    if (publisher.getDescriptor().isSecurityEnabled()) {
      cc.addCompilationCustomizers(new SandboxTransformer());
      sandbox = new ScriptSandbox();
    }

    Binding binding = new Binding();
    binding.setVariable("build", build);
    binding.setVariable("project", build.getParent());
    binding.setVariable("rooturl", publisher.getDescriptor().getHudsonUrl());
    binding.setVariable("out", listener.getLogger());

    GroovyShell shell = new GroovyShell(cl, binding, cc);

    if (sandbox != null) {
      sandbox.register();
    }

    return shell;
  }
 private String getHookUrl() {
   String baseUrl = helper.getTrigger().getGitHubApiAuth().getJenkinsUrl();
   if (baseUrl == null) {
     baseUrl = Jenkins.getInstance().getRootUrl();
   }
   return baseUrl + GhprbRootAction.URL + "/";
 }
 private void copySlaveJar(PrintStream logger, SmbFile remoteRoot) throws IOException {
   // copy slave.jar
   logger.println("Copying slave.jar");
   copyStreamAndClose(
       Jenkins.getInstance().getJnlpJars("slave.jar").getURL().openStream(),
       new SmbFile(remoteRoot, "slave.jar").getOutputStream());
 }
Example #24
0
  public List<Computer> getComputers() {
    Computer[] computers = Jenkins.getInstance().getComputers();

    if (!isFilterExecutors()) {
      return Arrays.asList(computers);
    }

    List<Computer> result = new ArrayList<Computer>();

    boolean roam = false;
    HashSet<Label> labels = new HashSet<Label>();
    for (Item item : getItems()) {
      if (item instanceof AbstractProject<?, ?>) {
        AbstractProject<?, ?> p = (AbstractProject<?, ?>) item;
        Label l = p.getAssignedLabel();
        if (l != null) {
          labels.add(l);
        } else {
          roam = true;
        }
      }
    }

    for (Computer c : computers) {
      Node n = c.getNode();
      if (n != null) {
        if (roam && n.getMode() == Mode.NORMAL
            || !Collections.disjoint(n.getAssignedLabels(), labels)) {
          result.add(c);
        }
      }
    }

    return result;
  }
  /** If the command is currently running inside a build, return it. Otherwise null. */
  protected Run optCurrentlyBuilding() throws CmdLineException {
    try {
      CLICommand c = CLICommand.getCurrent();
      if (c == null) throw new IllegalStateException("Not executing a CLI command");
      String[] envs = c.checkChannel().call(new GetCharacteristicEnvironmentVariables());

      if (envs[0] == null || envs[1] == null) return null;

      Job j = Jenkins.getInstance().getItemByFullName(envs[0], Job.class);
      if (j == null) throw new CmdLineException("No such job: " + envs[0]);

      try {
        Run r = j.getBuildByNumber(Integer.parseInt(envs[1]));
        if (r == null) throw new CmdLineException("No such build #" + envs[1] + " in " + envs[0]);
        if (!r.isBuilding()) {
          throw new CmdLineException(r + " is not currently being built");
        }
        return r;
      } catch (NumberFormatException e) {
        throw new CmdLineException("Invalid build number: " + envs[1]);
      }
    } catch (IOException e) {
      throw new CmdLineException("Failed to identify the build being executed", e);
    } catch (InterruptedException e) {
      throw new CmdLineException("Failed to identify the build being executed", e);
    }
  }
Example #26
0
  public ServerInfo convert(@SuppressWarnings("rawtypes") final Class type, final Object value) {
    // get the main config.
    final NeoGlobalConfig.DescriptorImpl globalConfigDescriptor =
        (NeoGlobalConfig.DescriptorImpl) Jenkins.getInstance().getDescriptor(NeoGlobalConfig.class);

    if (globalConfigDescriptor == null) {
      LOGGER.log(
          Level.FINEST,
          "No NeoLoad server settings found. Please add servers before configuring jobs. (getLicenseServerOptions)");
      return null;
    }

    // find the serverInfo based on the unique ID.
    @SuppressWarnings("unchecked")
    final Collection<ServerInfo> allServerInfo =
        CollectionUtils.union(
            globalConfigDescriptor.getNtsInfo(), globalConfigDescriptor.getCollabInfo());
    for (final ServerInfo si : allServerInfo) {
      if (si.getUniqueID().equals(value)) {
        return si;
      }
    }

    return null;
  }
Example #27
0
 private void updateComputer(
     Node n, Map<String, Computer> byNameMap, Set<Computer> used, boolean automaticSlaveLaunch) {
   Map<Node, Computer> computers = getComputerMap();
   Computer c;
   c = byNameMap.get(n.getNodeName());
   if (c != null) {
     c.setNode(n); // reuse
   } else {
     // we always need Computer for the master as a fallback in case there's no other Computer.
     if (n.getNumExecutors() > 0 || n == Jenkins.getInstance()) {
       computers.put(n, c = n.createComputer());
       if (!n.isHoldOffLaunchUntilSave() && automaticSlaveLaunch) {
         RetentionStrategy retentionStrategy = c.getRetentionStrategy();
         if (retentionStrategy != null) {
           // if there is a retention strategy, it is responsible for deciding to start the
           // computer
           retentionStrategy.start(c);
         } else {
           // we should never get here, but just in case, we'll fall back to the legacy behaviour
           c.connect(true);
         }
       }
     }
   }
   used.add(c);
 }
  public AbstractProject<?, ?> getParentProject() {
    AbstractProject<?, ?> context = null;
    List<AbstractProject> jobs = Jenkins.getInstance().getAllItems(AbstractProject.class);

    for (AbstractProject<?, ?> project : jobs) {
      if (!(project instanceof TopLevelItem)) continue;

      ParametersDefinitionProperty property =
          project.getProperty(ParametersDefinitionProperty.class);

      if (property != null) {
        List<ParameterDefinition> parameterDefinitions = property.getParameterDefinitions();

        if (parameterDefinitions != null) {
          for (ParameterDefinition pd : parameterDefinitions) {

            if (pd instanceof GitParameterDefinition
                && ((GitParameterDefinition) pd).compareTo(this) == 0) {

              context = project;
              break;
            }
          }
        }
      }
    }

    return context;
  }
 /**
  * Constructor.
  *
  * @param type the type.
  */
 DescriptorOrder(Class<T> type) {
   Jenkins j = Jenkins.getInstance();
   if (j == null) {
     throw new IllegalStateException(); // TODO 1.590+ getActiveInstance
   }
   descriptors = j.getDescriptorList(type);
 }
  // TODO Tag projects as created by us, so that we can intelligently delete them and prevent
  // multiple jobs editing Projects
  private boolean createNewJob(String jobName, String config) {
    LOGGER.log(Level.FINE, String.format("Creating project as %s", config));
    boolean created;

    try {
      InputStream is =
          new ByteArrayInputStream(config.getBytes("UTF-8")); // TODO confirm that we're using UTF-8

      int i = jobName.lastIndexOf('/');
      Jenkins jenkins = Jenkins.getInstance();
      ModifiableTopLevelItemGroup ctx = jenkins;
      if (i > 0) {
        String contextName = jobName.substring(0, i);
        jobName = jobName.substring(i + 1);
        Item contextItem = jenkins.getItemByFullName(contextName);
        if (contextItem instanceof ModifiableItemGroup) {
          ctx = (ModifiableTopLevelItemGroup) contextItem;
        }
      }
      TopLevelItem item = ctx.createProjectFromXML(jobName, is);
      created = true;
    } catch (UnsupportedEncodingException ueex) {
      LOGGER.log(Level.WARNING, "Unsupported encoding used in config. Should be UTF-8.");
      created = false;
    } catch (IOException ioex) {
      LOGGER.log(
          Level.WARNING, String.format("Error writing config for new job %s.", jobName), ioex);
      created = false;
    }
    return created;
  }