@RequirePOST public HttpResponse doImpersonate(StaplerRequest req, @QueryParameter String name) { Authentication auth = Jenkins.getAuthentication(); GrantedAuthority[] authorities = auth.getAuthorities(); if (authorities == null || StringUtils.isBlank(name)) { return HttpResponses.redirectToContextRoot(); } GrantedAuthority authority = null; for (GrantedAuthority a : authorities) { if (a.getAuthority().equals(name)) { authority = a; break; } } if (authority == null) { return HttpResponses.redirectToContextRoot(); } if (!SecurityRealm.AUTHENTICATED_AUTHORITY.equals(authority)) { ACL.impersonate(new ImpersonationAuthentication(auth, authority, SecurityRealm.AUTHENTICATED_AUTHORITY)); } else { ACL.impersonate(new ImpersonationAuthentication(auth, SecurityRealm.AUTHENTICATED_AUTHORITY)); } return HttpResponses.redirectToContextRoot(); }
@RequirePOST public void doClean(StaplerRequest req, StaplerResponse res) throws IOException, ServletException { // TODO switch to Jenkins.getActiveInstance() once 1.590+ is the baseline Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IllegalStateException("Jenkins has not been started, or was already shut down"); } final Job job = jenkins.getItemByFullName(req.getParameter("job"), Job.class); Timer.get().submit(new Runnable() { @Override public void run() { try { job.logRotate(); } catch (Exception e) { logger.log(Level.WARNING, "logRotate failed", e); } } }); res.forwardToPreviousPage(req); }
@RequirePOST public FormValidation doClearRepo() throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (instance.hasPermission(Item.DELETE)) { pulls = new HashMap<>(); save(); result = FormValidation.ok("Pulls deleted"); } else { result = FormValidation.error("Forbidden"); } } catch (Exception e) { LOG.error("Can\'t delete repository file '{}'", configFile.getFile().getAbsolutePath(), e); result = FormValidation.error(e, "Can't delete: %s", e.getMessage()); } return result; }
/** * Run trigger from web. */ @RequirePOST public FormValidation doRunTrigger() { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (instance.hasPermission(Item.BUILD)) { GitHubPRTrigger trigger = JobHelper.ghPRTriggerFromJob(job); if (trigger != null) { trigger.run(); result = FormValidation.ok("GitHub PR trigger run"); LOG.debug("GitHub PR trigger run for {}", job); } else { LOG.error("GitHub PR trigger not available for {}", job); result = FormValidation.error("GitHub PR trigger not available"); } } else { LOG.warn("No permissions to run GitHub PR trigger"); result = FormValidation.error("Forbidden"); } } catch (Exception e) { LOG.error("Can't run trigger", e); result = FormValidation.error(e, "Can't run trigger: %s", e.getMessage()); } return result; }
@RequirePOST public FormValidation doRebuildAllFailed() throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (instance.hasPermission(Item.BUILD)) { Map<Integer, List<Run<?, ?>>> builds = getAllPrBuilds(); for (List<Run<?, ?>> buildList : builds.values()) { if (!buildList.isEmpty() && Result.FAILURE.equals(buildList.get(0).getResult())) { Run<?, ?> lastBuild = buildList.get(0); rebuild(lastBuild); } } result = FormValidation.ok("Rebuild scheduled"); } else { result = FormValidation.error("Forbidden"); } } catch (Exception e) { LOG.error("Can't start rebuild", e); result = FormValidation.error(e, "Can't start rebuild: %s", e.getMessage()); } return result; }
@Override @RequirePOST public FormValidation doClearRepo() throws IOException { LOG.debug("Got clear GitHub Branch repo request for {}", getJob().getFullName()); FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (instance.hasPermission(Item.DELETE)) { branches = new HashMap<>(); save(); result = FormValidation.ok("Branches deleted"); } else { result = FormValidation.error("Forbidden"); } } catch (Exception e) { LOG.error("Can't delete repository file '{}'.", configFile.getFile().getAbsolutePath(), e); result = FormValidation.error(e, "Can't delete: " + e.getMessage()); } return result; }
@Override @RequirePOST public FormValidation doRunTrigger() throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (instance.hasPermission(Item.BUILD)) { GitHubBranchTrigger trigger = ghBranchTriggerFromJob(job); if (trigger != null) { trigger.run(); result = FormValidation.ok("GitHub Branch trigger run"); LOG.debug("GitHub Branch trigger run for {}", job); } else { LOG.error("GitHub Branch trigger not available for {}", job); result = FormValidation.error("GitHub Branch trigger not available"); } } else { LOG.warn("No permissions to run GitHub Branch trigger"); result = FormValidation.error("Forbidden"); } } catch (Exception e) { LOG.error("Can't run trigger", e.getMessage()); result = FormValidation.error(e, "Can't run trigger: %s", e.getMessage()); } return result; }
@Override @RequirePOST public FormValidation doRebuildAllFailed() throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (instance.hasPermission(Item.BUILD)) { Map<String, List<Run<?, ?>>> builds = getAllBranchBuilds(); for (List<Run<?, ?>> buildList : builds.values()) { if (!buildList.isEmpty() && Result.FAILURE.equals(buildList.get(0).getResult())) { Run<?, ?> lastBuild = buildList.get(0); rebuild(lastBuild); } } result = FormValidation.ok("Rebuild scheduled"); } else { result = FormValidation.error("Forbidden"); } } catch (Exception e) { LOG.error("Can't start rebuild", e.getMessage()); result = FormValidation.error(e, "Can't start rebuild: %s", e.getMessage()); } return result; }
/** * Submits the Oracle account username/password. */ @RequirePOST public HttpResponse doPostCredential(@QueryParameter String username, @QueryParameter String password) throws IOException, ServletException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); this.username = username; this.password = Secret.fromString(password); save(); return HttpResponses.redirectTo("credentialOK"); }
@RequirePOST public FormValidation doRebuild(StaplerRequest req) throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (!instance.hasPermission(Item.BUILD)) { return FormValidation.error("Forbidden"); } final String prNumberParam = "prNumber"; int prId = 0; if (req.hasParameter(prNumberParam)) { prId = Integer.valueOf(req.getParameter(prNumberParam)); } Map<Integer, List<Run<?, ?>>> builds = getAllPrBuilds(); List<Run<?, ?>> prBuilds = builds.get(prId); if (prBuilds != null && !prBuilds.isEmpty()) { if (rebuild(prBuilds.get(0))) { result = FormValidation.ok("Rebuild scheduled"); } else { result = FormValidation.warning("Rebuild not scheduled"); } } else { result = FormValidation.warning("Build not found"); } } catch (Exception e) { LOG.error("Can't start rebuild", e); result = FormValidation.error(e, "Can't start rebuild: " + e.getMessage()); } return result; }
@RequirePOST public FormValidation doBuild(StaplerRequest req) throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (!instance.hasPermission(Item.BUILD)) { return FormValidation.error("Forbidden"); } final String param = "branchName"; String branchName = null; if (req.hasParameter(param)) { branchName = req.getParameter(param); } if (isNull(branchName) || !getBranches().containsKey(branchName)) { return FormValidation.error("No branch to build"); } final GitHubBranch localBranch = getBranches().get(branchName); final GitHubBranchCause cause = new GitHubBranchCause(localBranch, this, "Manual run.", false); final JobRunnerForBranchCause runner = new JobRunnerForBranchCause(getJob(), ghBranchTriggerFromJob(getJob())); final QueueTaskFuture<?> queueTaskFuture = runner.startJob(cause); if (nonNull(queueTaskFuture)) { result = FormValidation.ok("Build scheduled"); } else { result = FormValidation.warning("Build not scheduled"); } } catch (Exception e) { LOG.error("Can't start build", e.getMessage()); result = FormValidation.error(e, "Can't start build: " + e.getMessage()); } return result; }
@Override @RequirePOST public FormValidation doRebuild(StaplerRequest req) throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (!instance.hasPermission(Item.BUILD)) { return FormValidation.error("Forbidden"); } final String param = "branchName"; String branchName = ""; if (req.hasParameter(param)) { branchName = req.getParameter(param); } Map<String, List<Run<?, ?>>> allBuilds = getAllBranchBuilds(); List<Run<?, ?>> branchBuilds = allBuilds.get(branchName); if (branchBuilds != null && !allBuilds.isEmpty()) { if (rebuild(branchBuilds.get(0))) { result = FormValidation.ok("Rebuild scheduled"); } else { result = FormValidation.warning("Rebuild not scheduled"); } } else { result = FormValidation.warning("Build not found"); } } catch (Exception e) { LOG.error("Can't start rebuild", e.getMessage()); result = FormValidation.error(e, "Can't start rebuild: " + e.getMessage()); } return result; }
/** * Submits a new event through Jenkins API. * @param inspectData JSON output of docker inspect container (array of container infos) * @param hostName Optional name of the host, which submitted the event * "unknown" by default * @param hostId Optional host ID. * "unknown" by default * @param status Optional status of the container. * By default, an artificial {@link DockerEventType#NONE} will be used. * @param time Optional time when the event happened. * The time is specified in seconds since January 1, 1970, 00:00:00 GMT * Default value - current time * @param environment Optional field, which describes the environment * @param imageName Optional field, which provides the name of the image * @return {@link HttpResponse} * @throws IOException Request processing error * @throws ServletException Servlet error */ //TODO: parameters check @RequirePOST public HttpResponse doSubmitContainerStatus( @QueryParameter(required = true) String inspectData, @QueryParameter(required = false) String hostId, @QueryParameter(required = false) String hostName, @QueryParameter(required = false) String status, @QueryParameter(required = false) long time, @QueryParameter(required = false) @CheckForNull String environment, @QueryParameter(required = false) @CheckForNull String imageName ) throws IOException, ServletException { checkPermission(DockerTraceabilityPlugin.SUBMIT); final ObjectMapper mapper = new ObjectMapper(); final InspectContainerResponse[] inspectContainerResponses = mapper.readValue(inspectData, InspectContainerResponse[].class); final long eventTime = time != 0 ? time : System.currentTimeMillis()/1000; final String effectiveHostName = StringUtils.isNotBlank(hostName) ? hostName : "unknown"; final String effectiveHostId = StringUtils.isNotBlank(hostId) ? hostId : "unknown"; final String effectiveStatus = StringUtils.isNotBlank(status) ? status.toUpperCase(Locale.ENGLISH) : DockerEventType.NONE.toString(); final String effectiveImageName = hudson.Util.fixEmpty(imageName); final String effectiveEnvironment = hudson.Util.fixEmpty(environment); for (InspectContainerResponse inspectContainerResponse : inspectContainerResponses) { final Event event = new DockerEvent(effectiveStatus, inspectContainerResponse.getImageId(), effectiveHostId, eventTime).toDockerEvent(); final Info hostInfo = new DockerInfo(effectiveHostId, effectiveHostName).toInfo(); DockerTraceabilityReport res = new DockerTraceabilityReport(event, hostInfo, inspectContainerResponse, inspectContainerResponse.getImageId(), effectiveImageName, /* InspectImageResponse */ null, new LinkedList<String>(), effectiveEnvironment); DockerTraceabilityReportListener.fire(res); } return HttpResponses.ok(); }
/** * Submits a new {@link DockerTraceabilityReport} via API. * @param json String representation of {@link DockerTraceabilityReport} * @return {@link HttpResponse} * @throws ServletException Servlet error * @throws IOException Processing error */ @RequirePOST public HttpResponse doSubmitReport(@QueryParameter(required = true) String json) throws IOException, ServletException { checkPermission(DockerTraceabilityPlugin.SUBMIT); ObjectMapper mapper = new ObjectMapper(); final DockerTraceabilityReport report = mapper.readValue(json, DockerTraceabilityReport.class); DockerTraceabilityReportListener.fire(report); return HttpResponses.ok(); }
/** * Removes the container reference from the registry. * @param id Container ID. Method supports full 64-char IDs only. * @throws IOException Cannot save the updated {@link DockerTraceabilityRootAction} * @throws ServletException Servlet exception * @return response */ @RequirePOST public HttpResponse doDeleteContainer(@QueryParameter(required = true) String id) throws IOException, ServletException { checkPermission(DockerTraceabilityPlugin.DELETE); removeContainerID(id); return HttpResponses.ok(); }
@SuppressWarnings(UNUSED) @CLIMethod(name = "disable-job") @RequirePOST public HttpResponse doDisable() throws IOException, ServletException { // NOSONAR checkPermission(CONFIGURE); makeDisabled(true); return new HttpRedirect("."); }
@SuppressWarnings(UNUSED) @CLIMethod(name = "enable-job") @RequirePOST public HttpResponse doEnable() throws IOException, ServletException { // NOSONAR checkPermission(CONFIGURE); makeDisabled(false); return new HttpRedirect("."); }
/** Perform the deletion. */ @RequirePOST @Override public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { delete(); rsp.sendRedirect2(Joiner.on("/").join( req.getContextPath(), getParent().getUrl())); }
@RequirePOST public void doIndex(StaplerRequest request, StaplerResponse response) { if (isJenkinsValidation(request)) { response.setHeader(X_INSTANCE_IDENTITY, Identity.getValueOrDefault(this.identity)); response.setStatus(HTTP_OK); return; } String payload = getPayload(request); checkState(payload != null, "Not intended to be browsed interactively (must specify payload parameter)." + " Ensure that the web hook Content-Type header is application/x-www-form-urlencoded"); String eventName = getEventType(request); GitHubEvent event = GitHubEvent.from(eventName); switch (event) { case PING: case SUPPORT: response.setStatus(HTTP_OK); break; case PUSH: PushCause cause = createCause(payload); this.triggerBuilds(Jenkins.getInstance(), cause); break; case UNKNOWN: String msg = String.format("Spoon WebHook event type (%s) is not supported. Only push and support events are supported", eventName); throw new IllegalArgumentException(msg); } }
@RequirePOST public void doDoRename(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if (!hasPermission(CONFIGURE)) { // rename is essentially delete followed by a create checkPermission(CREATE); checkPermission(DELETE); } String newName = req.getParameter("newName"); Jenkins.checkGoodName(newName); renameTo(newName); rsp.sendRedirect2("../" + newName); }
@RequirePOST public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, Descriptor.FormException { checkPermission(CONFIGURE); req.setCharacterEncoding("UTF-8"); JSONObject json = req.getSubmittedForm(); String newReferredItemName = Util.fixEmpty(json.optString("referredItemName")); // prevent invalid configuration with bad failure modes (StackOverflowException etc.) FormValidation result = ((DescriptorImpl)getDescriptor()).doCheckReferredItemName(newReferredItemName, this); if (result.kind == FormValidation.Kind.ERROR) { throw new IllegalArgumentException(result.getMessage(), result); } description = json.getString("description"); referredItemName = newReferredItemName; forwardImmediately = json.optBoolean("forwardImmediately", false); save(); String newName = json.getString("name"); if (newName != null && !newName.equals(name)) { Hudson.checkGoodName(newName); rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8")); } else { FormApply.success(".").generateResponse(req, rsp, this); } }
/** * Binds the thread dump to the CORS aware URL {@code /metrics/threads} where the metrics access key is * provided in the form field {@code key} or an {@code Authorization: Jenkins-Metrics-Key {key}} header * * @param req the request * @param key the key from the form field. * @return the {@link HttpResponse} * @throws IllegalAccessException if the access attempt is invalid. */ @SuppressWarnings("unused") // stapler binding @Restricted(NoExternalUse.class) // stapler binding @RequirePOST public HttpResponse doThreads(StaplerRequest req, @QueryParameter("key") String key) throws IllegalAccessException { requireCorrectMethod(req); if (StringUtils.isBlank(key)) { key = getKeyFromAuthorizationHeader(req); } Metrics.checkAccessKeyThreadDump(key); return Metrics.cors(key, new ThreadDumpResponse(new ThreadDump(ManagementFactory.getThreadMXBean()))); }
@Override @RequirePOST public void doDoDelete(final StaplerRequest req, final StaplerResponse rsp) throws IOException, ServletException { checkPermission(DELETE); this.model.deleteBuild(); rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl()); }
@Override @RequirePOST public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { initPython(); if (pexec.isImplemented(64)) { pexec.execPythonVoid("do_config_submit", req, rsp); } else { super.doConfigSubmit(req, rsp); } }
@Override @RequirePOST public void doDoRename(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { initPython(); if (pexec.isImplemented(70)) { pexec.execPythonVoid("do_do_rename", req, rsp); } else { super.doDoRename(req, rsp); } }
@Override @RequirePOST public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { initPython(); if (pexec.isImplemented(42)) { pexec.execPythonVoid("do_do_delete", req, rsp); } else { super.doDoDelete(req, rsp); } }
@Override @RequirePOST public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { initPython(); if (pexec.isImplemented(75)) { pexec.execPythonVoid("do_do_delete", req, rsp); } else { super.doDoDelete(req, rsp); } }
@Override @RequirePOST public HttpResponse doConfigSubmit(StaplerRequest req) throws IOException, ServletException, FormException { initPython(); if (pexec.isImplemented(83)) { return (HttpResponse) pexec.execPython("do_config_submit", req); } else { return super.doConfigSubmit(req); } }
@RequirePOST public void doDeleteBundles(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { JSONObject json = req.getSubmittedForm(); if (!json.has("bundles")) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } Set<String> bundlesToDelete = new HashSet<>(); for (Selection s : req.bindJSONToList(Selection.class, json.get("bundles"))) { if (s.isSelected()) { bundlesToDelete.add(s.getName()); } } File rootDirectory = SupportPlugin.getRootDirectory(); for(String bundleToDelete : bundlesToDelete) { File fileToDelete = new File(rootDirectory, bundleToDelete); logger.fine("Trying to delete bundle file "+ fileToDelete.getAbsolutePath()); try { if (fileToDelete.delete()) { logger.info("Bundle " + fileToDelete.getAbsolutePath() + " successfully delete."); } else { logger.log(Level.SEVERE, "Unable to delete file " + fileToDelete.getAbsolutePath()); } } catch (RuntimeException e) { logger.log(Level.SEVERE, "Unable to delete file " + fileToDelete.getAbsolutePath(), e); } } rsp.sendRedirect(""); }
@RequirePOST public void doRefresh(StaplerRequest req, StaplerResponse res) throws IOException, ServletException { refreshData(); res.forwardToPreviousPage(req); }
/** {@inheritDoc} */ @Override @RequirePOST public Item doCreateItem(StaplerRequest req, StaplerResponse rsp) { throw new UnsupportedOperationException(); }
@RequirePOST public void doGenerateAllBundles(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { final Jenkins instance = Jenkins.getInstance(); instance.getAuthorizationStrategy().getACL(instance).checkPermission(CREATE_BUNDLE); JSONObject json = req.getSubmittedForm(); if (!json.has("components")) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } logger.fine("Parsing request..."); Set<String> remove = new HashSet<String>(); for (Selection s : req.bindJSONToList(Selection.class, json.get("components"))) { if (!s.isSelected()) { logger.log(Level.FINER, "Excluding ''{0}'' from list of components to include", s.getName()); remove.add(s.getName()); } } logger.fine("Selecting components..."); final List<Component> components = new ArrayList<Component>(getComponents()); for (Iterator<Component> iterator = components.iterator(); iterator.hasNext(); ) { Component c = iterator.next(); if (remove.contains(c.getId()) || !c.isEnabled()) { iterator.remove(); } } final SupportPlugin supportPlugin = SupportPlugin.getInstance(); if (supportPlugin != null) { supportPlugin.setExcludedComponents(remove); } logger.fine("Preparing response..."); rsp.setContentType("application/zip"); rsp.addHeader("Content-Disposition", "inline; filename=" + SupportPlugin.getBundleFileName() + ";"); final ServletOutputStream servletOutputStream = rsp.getOutputStream(); try { SupportPlugin.setRequesterAuthentication(Jenkins.getAuthentication()); try { SecurityContext old = ACL.impersonate(ACL.SYSTEM); try { SupportPlugin.writeBundle(servletOutputStream, components); } catch (IOException e) { logger.log(Level.FINE, e.getMessage(), e); } finally { SecurityContextHolder.setContext(old); } } finally { SupportPlugin.clearRequesterAuthentication(); } } finally { logger.fine("Response completed"); } }
@RequirePOST public HttpResponse doInstall(@QueryParameter PluginImpl.InstallMode installMode) throws Exception { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); PluginImpl.installPlugins(installMode); return HttpResponses.redirectToDot(); }
/** * Generates a support bundle. * @param req The stapler request * @param rsp The stapler response * @throws ServletException * @throws IOException */ @RequirePOST public void doDownload(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { doGenerateAllBundles(req, rsp); }