/** * Returns a read-only view of all {@link Job}s in this view. * * <p>This method returns a separate copy each time to avoid concurrent modification issue. */ public synchronized List<TopLevelItem> getItems() { SortedSet<String> names = new TreeSet<String>(jobNames); if (includePattern != null) { for (TopLevelItem item : Hudson.getInstance().getItems()) { String itemName = item.getName(); if (includePattern.matcher(itemName).matches()) { names.add(itemName); } } } List<TopLevelItem> items = new ArrayList<TopLevelItem>(names.size()); for (String n : names) { TopLevelItem item = Hudson.getInstance().getItem(n); // Add if no status filter or filter matches enabled/disabled status: if (item != null && (statusFilter == null || !(item instanceof AbstractProject) || ((AbstractProject) item).isDisabled() ^ statusFilter)) items.add(item); } // check the filters Iterable<ViewJobFilter> jobFilters = getJobFilters(); List<TopLevelItem> allItems = Hudson.getInstance().getItems(); for (ViewJobFilter jobFilter : jobFilters) { items = jobFilter.filter(items, allItems, this); } return items; }
private void makeBuildable(BuildableItem p) { if (Hudson.FLYWEIGHT_SUPPORT && p.task instanceof FlyweightTask) { ConsistentHash<Node> hash = new ConsistentHash<Node>( new Hash<Node>() { public String hash(Node node) { return node.getNodeName(); } }); Hudson h = Hudson.getInstance(); hash.add(h, h.getNumExecutors() * 100); for (Node n : h.getNodes()) hash.add(n, n.getNumExecutors() * 100); for (Node n : hash.list(p.task.getFullDisplayName())) { Computer c = n.toComputer(); if (c == null) continue; c.startFlyWeightTask(p); return; } // if the execution get here, it means we couldn't schedule it anywhere. // so do the scheduling like other normal jobs. } buildables.put(p.task, p); }
public void testSelfExcludingJobs() throws Exception { BuildBlockerProperty theProperty = new BuildBlockerProperty(); theProperty.setBlockingJobs("SelfExcluding_.*"); FreeStyleProject theJob1 = createFreeStyleProject("SelfExcluding_Job1"); theJob1.addProperty(theProperty); assertTrue(theJob1.getBuilds().isEmpty()); FreeStyleProject theJob2 = createFreeStyleProject("SelfExcluding_Job2"); theJob2.addProperty(theProperty); assertTrue(theJob1.getBuilds().isEmpty()); // allow executing two simultanious jobs int theOldNumExecutors = Hudson.getInstance().getNumExecutors(); Hudson.getInstance().setNumExecutors(2); Future<FreeStyleBuild> theFuture1 = theJob1.scheduleBuild2(0); Future<FreeStyleBuild> theFuture2 = theJob2.scheduleBuild2(0); long theStartTime = System.currentTimeMillis(); long theEndTime = theStartTime; while ((!theFuture1.isDone() || !theFuture2.isDone()) && theEndTime < theStartTime + 5000) { theEndTime = System.currentTimeMillis(); } // if more then five seconds have passed, we assume its a deadlock. assertTrue(theEndTime < theStartTime + 5000); // restore changed settings Hudson.getInstance().setNumExecutors(theOldNumExecutors); theJob2.delete(); theJob1.delete(); }
/** Does the opposite of {@link #toNameList(Collection)}. */ public static <T extends Item> List<T> fromNameList(String list, Class<T> type) { Hudson hudson = Hudson.getInstance(); List<T> r = new ArrayList<T>(); StringTokenizer tokens = new StringTokenizer(list, ","); while (tokens.hasMoreTokens()) { String fullName = tokens.nextToken().trim(); T item = hudson.getItemByFullName(fullName, type); if (item != null) { r.add(item); } } return r; }
/** * Creates a {@link Launcher} that this build will use. This can be overridden by derived types * to decorate the resulting {@link Launcher}. * * @param listener Always non-null. Connected to the main build output. */ protected Launcher createLauncher(BuildListener listener) throws IOException, InterruptedException { Launcher l = getCurrentNode().createLauncher(listener); if (project instanceof BuildableItemWithBuildWrappers) { BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project; for (BuildWrapper bw : biwbw.getBuildWrappersList()) l = bw.decorateLauncher(AbstractBuild.this, l, listener); } buildEnvironments = new ArrayList<Environment>(); for (NodeProperty nodeProperty : Hudson.getInstance().getGlobalNodeProperties()) { Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener); if (environment != null) { buildEnvironments.add(environment); } } for (NodeProperty nodeProperty : Computer.currentComputer().getNode().getNodeProperties()) { Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener); if (environment != null) { buildEnvironments.add(environment); } } return l; }
public List<Action> getOwnerViewActions() { try { return _getOwnerViewActions(); } catch (AbstractMethodError e) { return Hudson.getInstance().getActions(); } }
/** Backward-compatible way of getting {@code getOwner().getItemGroup()} */ public ItemGroup<? extends TopLevelItem> getOwnerItemGroup() { try { return _getOwnerItemGroup(); } catch (AbstractMethodError e) { return Hudson.getInstance(); } }
/** * Gets the changes incorporated into this build. * * @return never null. */ @Exported public ChangeLogSet<? extends Entry> getChangeSet() { if (scm == null) { // for historical reason, null means CVS. try { Class<?> c = Hudson.getInstance() .getPluginManager() .uberClassLoader .loadClass("hudson.scm.CVSChangeLogParser"); scm = (ChangeLogParser) c.newInstance(); } catch (ClassNotFoundException e) { // if CVS isn't available, fall back to something non-null. scm = new NullChangeLogParser(); } catch (InstantiationException e) { scm = new NullChangeLogParser(); throw (Error) new InstantiationError().initCause(e); } catch (IllegalAccessException e) { scm = new NullChangeLogParser(); throw (Error) new IllegalAccessError().initCause(e); } } if (changeSet == null) // cached value try { changeSet = calcChangeSet(); } finally { // defensive check. if the calculation fails (such as through an exception), // set a dummy value so that it'll work the next time. the exception will // be still reported, giving the plugin developer an opportunity to fix it. if (changeSet == null) changeSet = ChangeLogSet.createEmpty(this); } return changeSet; }
/** * Gets the list of {@link Build}s that include changes by this user, by the timestamp order. * * <p>TODO: do we need some index for this? */ @WithBridgeMethods(List.class) public RunList getBuilds() { List<AbstractBuild> r = new ArrayList<AbstractBuild>(); for (AbstractProject<?, ?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) for (AbstractBuild<?, ?> b : p.getBuilds()) if (b.hasParticipant(this)) r.add(b); return RunList.fromRuns(r); }
@Override public void onRenamed(Item item, String oldName, String newName) { if (item instanceof AbstractProject) { AbstractProject p = Hudson.getInstance().getItemByFullName(newName, AbstractProject.class); if (p != null) { RunList builds = p.getBuilds(); for (Object build : builds) { if (build instanceof AbstractBuild) { Collection<Fingerprint> fingerprints = ((AbstractBuild) build).getBuildFingerprints(); for (Fingerprint f : fingerprints) { try { f.rename(oldName, newName); } catch (IOException e) { logger.log( Level.WARNING, "Failed to update fingerprint record " + f.getFileName() + " when " + oldName + " was renamed to " + newName, e); } } } } } } }
/** Builds up an HTML fragment that starts all the download jobs. */ public String generateFragment() { if (neverUpdate) return ""; StringBuilder buf = new StringBuilder(); if (Hudson.getInstance().hasPermission(Hudson.READ)) { long now = System.currentTimeMillis(); for (Downloadable d : Downloadable.all()) { if (d.getDue() < now) { buf.append("<script>downloadService.download(") .append(QuotedStringTokenizer.quote(d.getId())) .append(',') .append(QuotedStringTokenizer.quote(d.getUrl())) .append(',') .append("{version:" + QuotedStringTokenizer.quote(Hudson.VERSION) + '}') .append(',') .append( QuotedStringTokenizer.quote( Stapler.getCurrentRequest().getContextPath() + '/' + getUrl() + "/byId/" + d.getId() + "/postBack")) .append(',') .append("null);</script>"); } } } return buf.toString(); }
/** * Saves the form to the configuration and disk. * * @param req StaplerRequest * @param rsp StaplerResponse * @throws ServletException if something unfortunate happens. * @throws IOException if something unfortunate happens. * @throws InterruptedException if something unfortunate happens. */ public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException, InterruptedException { getProject().checkPermission(AbstractProject.BUILD); if (isRebuildAvailable()) { if (!req.getMethod().equals("POST")) { // show the parameter entry form. req.getView(this, "index.jelly").forward(req, rsp); return; } build = req.findAncestorObject(AbstractBuild.class); ParametersDefinitionProperty paramDefProp = build.getProject().getProperty(ParametersDefinitionProperty.class); List<ParameterValue> values = new ArrayList<ParameterValue>(); ParametersAction paramAction = build.getAction(ParametersAction.class); JSONObject formData = req.getSubmittedForm(); if (!formData.isEmpty()) { JSONArray a = JSONArray.fromObject(formData.get("parameter")); for (Object o : a) { JSONObject jo = (JSONObject) o; String name = jo.getString("name"); ParameterValue parameterValue = getParameterValue(paramDefProp, name, paramAction, req, jo); if (parameterValue != null) { values.add(parameterValue); } } } CauseAction cause = new CauseAction(new RebuildCause(build)); Hudson.getInstance() .getQueue() .schedule(build.getProject(), 0, new ParametersAction(values), cause); rsp.sendRedirect("../../"); } }
/** * Handles the configuration submission. * * <p>Load view-specific properties here. */ @Override protected void submit(StaplerRequest req) throws ServletException, FormException, IOException { jobNames.clear(); for (TopLevelItem item : Hudson.getInstance().getItems()) { if (req.getParameter(item.getName()) != null) jobNames.add(item.getName()); } if (req.getParameter("useincluderegex") != null) { includeRegex = Util.nullify(req.getParameter("includeRegex")); if (includeRegex == null) includePattern = null; else includePattern = Pattern.compile(includeRegex); } else { includeRegex = null; includePattern = null; } if (columns == null) { columns = new DescribableList<ListViewColumn, Descriptor<ListViewColumn>>(Saveable.NOOP); } columns.rebuildHetero(req, req.getSubmittedForm(), ListViewColumn.all(), "columns"); if (jobFilters == null) { jobFilters = new DescribableList<ViewJobFilter, Descriptor<ViewJobFilter>>(Saveable.NOOP); } jobFilters.rebuildHetero(req, req.getSubmittedForm(), ViewJobFilter.all(), "jobFilters"); String filter = Util.fixEmpty(req.getParameter("statusFilter")); statusFilter = filter != null ? "1".equals(filter) : null; }
/** * visit project chain, from current through parents. * * @param visitor * @param run */ public static void traverseChain(HudsonVisitor visitor, Run run) { if (run == null) return; traverse(visitor, run); RepositoryAction repositoryAction = run.getAction(RepositoryAction.class); if (repositoryAction != null) { if (repositoryAction instanceof ProjectRepositoryAction) { final ProjectRepositoryAction projectRepositoryAction = (ProjectRepositoryAction) repositoryAction; AbstractProject item = (AbstractProject) Hudson.getInstance().getItem(projectRepositoryAction.getProjectName()); Optional<Run> r = Iterables.tryFind( item.getBuilds(), new Predicate<Run>() { public boolean apply(Run run) { return run.getNumber() == projectRepositoryAction.getBuildNumber(); } }); if (r.isPresent()) traverseChain(visitor, r.get()); } } }
/** * Call this method while rebuilding non parameterized build. . * * @param currentBuild current build. * @param response current response object. * @throws ServletException if something unfortunate happens. * @throws IOException if something unfortunate happens. * @throws InterruptedException if something unfortunate happens. */ public void nonParameterizedRebuild(AbstractBuild currentBuild, StaplerResponse response) throws ServletException, IOException, InterruptedException { getProject().checkPermission(AbstractProject.BUILD); CauseAction cause = new CauseAction(new RebuildCause(currentBuild)); Hudson.getInstance().getQueue().schedule(currentBuild.getProject(), 0, null, cause); response.sendRedirect("../../"); }
@Override public synchronized void doSubmitDescription(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(Hudson.ADMINISTER); Hudson.getInstance().setSystemMessage(req.getParameter("description")); rsp.sendRedirect("."); }
public Item doCreateItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Item item = Hudson.getInstance().doCreateItem(req, rsp); if (item != null) { jobNames.add(item.getName()); owner.save(); } return item; }
/** Returns the {@link MavenModule}s that are in the queue. */ public List<Queue.Item> getQueueItems() { List<Queue.Item> r = new ArrayList<hudson.model.Queue.Item>(); for (Queue.Item item : Hudson.getInstance().getQueue().getItems()) { Task t = item.task; if ((t instanceof MavenModule && ((MavenModule) t).getParent() == this) || t == this) r.add(item); } return r; }
/** Loads the queue contents that was {@link #save() saved}. */ public synchronized void load() { try { // first try the old format File queueFile = getQueueFile(); if (queueFile.exists()) { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(queueFile))); String line; while ((line = in.readLine()) != null) { AbstractProject j = Hudson.getInstance().getItemByFullName(line, AbstractProject.class); if (j != null) j.scheduleBuild(); } in.close(); // discard the queue file now that we are done queueFile.delete(); } else { queueFile = getXMLQueueFile(); if (queueFile.exists()) { List list = (List) new XmlFile(XSTREAM, queueFile).read(); int maxId = 0; for (Object o : list) { if (o instanceof Task) { // backward compatiblity schedule((Task) o, 0); } else if (o instanceof Item) { Item item = (Item) o; if (item.task == null) continue; // botched persistence. throw this one away maxId = Math.max(maxId, item.id); if (item instanceof WaitingItem) { waitingList.add((WaitingItem) item); } else if (item instanceof BlockedItem) { blockedProjects.put(item.task, (BlockedItem) item); } else if (item instanceof BuildableItem) { buildables.add((BuildableItem) item); } else { throw new IllegalStateException("Unknown item type! " + item); } } // this conveniently ignores null } WaitingItem.COUNTER.set(maxId); // I just had an incident where all the executors are dead at AbstractProject._getRuns() // because runs is null. Debugger revealed that this is caused by a MatrixConfiguration // object that doesn't appear to be de-serialized properly. // I don't know how this problem happened, but to diagnose this problem better // when it happens again, save the old queue file for introspection. File bk = new File(queueFile.getPath() + ".bak"); bk.delete(); queueFile.renameTo(bk); queueFile.delete(); } } } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load the queue file " + getQueueFile(), e); } }
public ACL getACL() { final ACL base = Hudson.getInstance().getAuthorizationStrategy().getACL(this); // always allow a non-anonymous user full control of himself. return new ACL() { public boolean hasPermission(Authentication a, Permission permission) { return (a.getName().equals(id) && !(a instanceof AnonymousAuthenticationToken)) || base.hasPermission(a, permission); } }; }
@Override public boolean cancel(boolean mayInterruptIfRunning) { Queue q = Hudson.getInstance().getQueue(); synchronized (q) { if (executor != null) { if (mayInterruptIfRunning) executor.interrupt(); return mayInterruptIfRunning; } return q.cancel(task); } }
@Override public String getWhy() { Hudson hudson = Hudson.getInstance(); if (hudson.isQuietingDown()) return Messages.Queue_HudsonIsAboutToShutDown(); Label label = task.getAssignedLabel(); if (hudson.getNodes().isEmpty()) label = null; // no master/slave. pointless to talk about nodes String name = null; if (label != null) { name = label.getName(); if (label.isOffline()) { if (label.getNodes().size() > 1) return Messages.Queue_AllNodesOffline(name); else return Messages.Queue_NodeOffline(name); } } if (name == null) return Messages.Queue_WaitingForNextAvailableExecutor(); else return Messages.Queue_WaitingForNextAvailableExecutorOn(name); }
/** * visit everything in order. * * @param visitor */ public static void traverse(HudsonVisitor visitor) { for (BuildableItemWithBuildWrappers item : Hudson.getInstance().getAllItems(BuildableItemWithBuildWrappers.class)) { visitor.visitProject(item); List<? extends Run> runs = item.asProject().getBuilds(); for (Run run : runs) { traverse(visitor, run); } } }
/** Deletes this user from Hudson. */ public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { requirePOST(); checkPermission(Hudson.ADMINISTER); if (id.equals(Hudson.getAuthentication().getName())) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot delete self"); return; } delete(); rsp.sendRedirect2("../.."); }
public Map<String, String> getJenkinsSystemVariables(boolean forceOnMaster) throws IOException, InterruptedException { Map<String, String> result = new TreeMap<String, String>(); Computer computer; if (forceOnMaster) { computer = Hudson.getInstance().toComputer(); } else { computer = Computer.currentComputer(); } // test if there is at least one executor if (computer != null) { result = computer.getEnvironment().overrideAll(result); Node n = computer.getNode(); if (n != null) result.put("NODE_NAME", computer.getName()); result.put("NODE_LABELS", Util.join(n.getAssignedLabels(), " ")); } String rootUrl = Hudson.getInstance().getRootUrl(); if (rootUrl != null) { result.put("JENKINS_URL", rootUrl); result.put("HUDSON_URL", rootUrl); // Legacy compatibility } result.put("JENKINS_HOME", Hudson.getInstance().getRootDir().getPath()); result.put("HUDSON_HOME", Hudson.getInstance().getRootDir().getPath()); // legacy compatibility List<EnvironmentVariablesNodeProperty> globalNodeProperties = Hudson.getInstance() .getGlobalNodeProperties() .getAll(EnvironmentVariablesNodeProperty.class); for (EnvironmentVariablesNodeProperty environmentVariablesNodeProperty : globalNodeProperties) { result.putAll(environmentVariablesNodeProperty.getEnvVars()); } return result; }
@SuppressWarnings("unchecked") public Map<String, String> getBuildVariables(AbstractBuild build, EnvInjectLogger logger) throws EnvInjectException { Map<String, String> result = new HashMap<String, String>(); // Add build process variables result.putAll(build.getCharacteristicEnvVars()); try { // EnvVars envVars = new EnvVars(); // for (EnvironmentContributor ec : EnvironmentContributor.all()) { // ec.buildEnvironmentFor(build, envVars, new LogTaskListener(LOG, Level.ALL)); // result.putAll(envVars); // } JDK jdk = build.getProject().getJDK(); if (jdk != null) { Node node = build.getBuiltOn(); if (node != null) { jdk = jdk.forNode(node, logger.getListener()); } jdk.buildEnvVars(result); } } catch (IOException ioe) { throw new EnvInjectException(ioe); } catch (InterruptedException ie) { throw new EnvInjectException(ie); } Executor e = build.getExecutor(); if (e != null) { result.put("EXECUTOR_NUMBER", String.valueOf(e.getNumber())); } String rootUrl = Hudson.getInstance().getRootUrl(); if (rootUrl != null) { result.put("BUILD_URL", rootUrl + build.getUrl()); result.put("JOB_URL", rootUrl + build.getParent().getUrl()); } // Add build variables such as parameters, plugins contributions, ... result.putAll(build.getBuildVariables()); // Retrieve triggered cause Map<String, String> triggerVariable = new BuildCauseRetriever().getTriggeredCause(build); result.putAll(triggerVariable); return result; }
public void testMultipleExecutors() throws Exception { // Job1 runs for 1 second, no dependencies FreeStyleProject theJob1 = createFreeStyleProject("MultipleExecutor_Job1"); theJob1.getBuildersList().add(new Shell("sleep 1; exit 0")); assertTrue(theJob1.getBuilds().isEmpty()); // Job2 returns immediatly but can't run while Job1 is running. FreeStyleProject theJob2 = createFreeStyleProject("MultipleExecutor_Job2"); { BuildBlockerProperty theProperty = new BuildBlockerProperty(); theProperty.setBlockingJobs("MultipleExecutor_Job1"); theJob2.addProperty(theProperty); } assertTrue(theJob1.getBuilds().isEmpty()); // allow executing two simultanious jobs int theOldNumExecutors = Hudson.getInstance().getNumExecutors(); Hudson.getInstance().setNumExecutors(2); Future<FreeStyleBuild> theFuture1 = theJob1.scheduleBuild2(0); Future<FreeStyleBuild> theFuture2 = theJob2.scheduleBuild2(0); while (!theFuture1.isDone() || !theFuture2.isDone()) { // let the jobs process } // check if job2 was not started before job1 was finished Run theRun1 = theJob1.getLastBuild(); Run theRun2 = theJob2.getLastBuild(); assertTrue(theRun1.getTimeInMillis() + theRun1.getDuration() <= theRun2.getTimeInMillis()); // restore changed settings Hudson.getInstance().setNumExecutors(theOldNumExecutors); theJob2.delete(); theJob1.delete(); }
public void doRssLatest(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { final List<Run> lastBuilds = new ArrayList<Run>(); for (final TopLevelItem item : Hudson.getInstance().getItems()) { if (!(item instanceof Job)) continue; for (Run r = ((Job) item).getLastBuild(); r != null; r = r.getPreviousBuild()) { if (!(r instanceof AbstractBuild)) continue; final AbstractBuild b = (AbstractBuild) r; if (b.hasParticipant(this)) { lastBuilds.add(b); break; } } } rss(req, rsp, " latest build", RunList.fromRuns(lastBuilds), Run.FEED_ADAPTER_LATEST); }
/** Visit projects and builds */ public static void traverseProjectsAndBuilds(HudsonVisitor visitor) { for (BuildableItemWithBuildWrappers item : Hudson.getInstance().getAllItems(BuildableItemWithBuildWrappers.class)) { visitor.visitProject(item); List<? extends Run> runs = item.asProject().getBuilds(); for (Run run : runs) { if (run instanceof MavenModuleSetBuild) { MavenModuleSetBuild mmsb = (MavenModuleSetBuild) run; visitor.visitModuleSet(mmsb); } } } }
private void checkout(BuildListener listener) throws Exception { try { for (int retryCount = project.getScmCheckoutRetryCount(); ; retryCount--) { // for historical reasons, null in the scm field means CVS, so we need to explicitly set // this to something // in case check out fails and leaves a broken changelog.xml behind. // see // http://www.nabble.com/CVSChangeLogSet.parse-yields-SAXParseExceptions-when-parsing-bad-*AccuRev*-changelog.xml-files-td22213663.html AbstractBuild.this.scm = new NullChangeLogParser(); try { if (project.checkout( AbstractBuild.this, launcher, listener, new File(getRootDir(), "changelog.xml"))) { // check out succeeded SCM scm = project.getScm(); AbstractBuild.this.scm = scm.createChangeLogParser(); AbstractBuild.this.changeSet = AbstractBuild.this.calcChangeSet(); for (SCMListener l : Hudson.getInstance().getSCMListeners()) l.onChangeLogParsed(AbstractBuild.this, listener, changeSet); return; } } catch (AbortException e) { listener.error(e.getMessage()); } catch (IOException e) { // checkout error not yet reported e.printStackTrace(listener.getLogger()); } if (retryCount == 0) // all attempts failed throw new RunnerAbortedException(); listener.getLogger().println("Retrying after 10 seconds"); Thread.sleep(10000); } } catch (InterruptedException e) { listener.getLogger().println(Messages.AbstractProject_ScmAborted()); LOGGER.log(Level.INFO, AbstractBuild.this + " aborted", e); throw new RunnerAbortedException(); } }