public HttpResponse doPost(StaplerRequest request) throws IOException { if (!request.getMethod().equals("POST")) { return HttpResponses .error(HttpServletResponse.SC_BAD_REQUEST, "Only POST requests are supported, this was a " + request.getMethod() + " request"); } if (!"application/json".equals(request.getContentType())) { return HttpResponses .error(HttpServletResponse.SC_BAD_REQUEST, "Only application/json content is supported, this was " + request.getContentType()); } String type = request.getHeader("X-Gitea-Event"); if (StringUtils.isBlank(type)) { return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, "Expecting a Gitea event, missing expected X-Gitea-Event header"); } String origin = SCMEvent.originOf(request); boolean processed = false; for (GiteaWebhookHandler<?, ?> h : ExtensionList.lookup(GiteaWebhookHandler.class)) { if (h.matches(type)) { h.process(request.getInputStream(), origin); processed = true; } } return HttpResponses.plainText(processed ? "Processed" : "Ignored"); }
/** * Serves the testCoverage badge image. TO DO * @param req * @param rsp * @param job * @return */ @SuppressWarnings("rawtypes") public HttpResponse doTestIcon(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job) { Job<?, ?> project = getProject(job); Integer testPass = null; Integer testTotal = null; if (project.getLastCompletedBuild() != null) { AbstractTestResultAction testAction = project.getLastCompletedBuild().getAction(AbstractTestResultAction.class); if(testAction != null){ int total = testAction.getTotalCount(); int pass = total - testAction.getFailCount() - testAction.getSkipCount(); testTotal = total; testPass = pass; } } return iconResolver.getTestResultImage(testPass, testTotal); }
/** * Serves the Build Description badge image. * @param req * @param rsp * @param job * @return */ public HttpResponse doBuildDescriptionIcon(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job) { Job<?, ?> project = getProject(job); String buildDescription = null; /*if (project.getLastSuccessfulBuild() != null) { buildDescription = project.getLastSuccessfulBuild().getDescription(); }*/ /*if (project.getLastBuild() != null) { buildDescription = project.getLastBuild().getDescription(); }*/ if (project.getLastCompletedBuild() != null) { buildDescription = project.getLastCompletedBuild().getDescription(); } return iconResolver.getBuildDescriptionImage(buildDescription); }
@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(); }
public HttpResponse doQueryJiraFields(@QueryParameter String issueKey) { try { if (!Config.getGlobalConfig().isJiraConfigComplete()) { return FormValidation.error("JIRA settings are not set in global config"); } final Map<String, String> jiraFields = getJiraClientSvc().getJiraFields(issueKey); return new ForwardToView(this, "/org/jenkinsci/plugins/jiraext/view/UpdateField/jiraFields.jelly") .with("jiraFieldMap", jiraFields); } catch (Throwable t) { String message = "Error finding FieldIds for issueKey: " + issueKey; logger.log(Level.WARNING, message, t); return FormValidation.error(t, message); } }
public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException { checkPermission(PROVISION); if (template == null) { throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing"); } SlaveTemplate t = getTemplate(template); if (t == null) { throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template); } StringWriter sw = new StringWriter(); StreamTaskListener listener = new StreamTaskListener(sw); try { EC2AbstractSlave node = t.provision(listener); Hudson.getInstance().addNode(node); return HttpResponses.redirectViaContextPath("/computer/" + node.getNodeName()); } catch (AmazonClientException e) { throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e); } }
/** * Retrieves the latest container status via API. * The output will be retrieved in JSON. Supports filers. Missing * "since" and "until" * @param id ID of the container, for which the info should be retrieved. * Short container IDs are not supported. * @throws IOException Processing error * @throws ServletException Servlet error * @return Raw JSON output compatible with docker inspect */ public HttpResponse doRawContainerInfo(@QueryParameter(required = true) String id) throws IOException, ServletException { checkPermission(DockerTraceabilityPlugin.READ_DETAILS); //TODO: check containerID format final DockerTraceabilityReport report = DockerTraceabilityHelper.getLastReport(id); if (report == null) { return HttpResponses.error(404, "No info available for the containerId=" + id); } final InspectContainerResponse inspectInfo = report.getContainer(); if (inspectInfo == null) { assert false : "Input logic should reject such cases"; return HttpResponses.error(500, "Cannot retrieve the container's status"); } // Return raw JSON in the response InspectContainerResponse[] out = {inspectInfo}; return toJSONResponse(out); }
/** * Performs the notification on 'POST' action named "perform" * * @param req StaplerRequest * @param rsp StaplerResponse * @return HttpResponse */ public HttpResponse do_perform(final StaplerRequest req, final StaplerResponse rsp) { // Only administrator can create a new site. Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); // TODO: display the progression for(ResendProjectAction resendProjectAction: resendActions){ try { final NotificationHandler notifHandler = new NotificationHandler(resendProjectAction.getConfig()); for(Map.Entry<AbstractBuild<?,?>, List<ResendBuildAction>> resendBuildAction: resendProjectAction.getResendActionPerBuild().entrySet()){ notifHandler.send(resendBuildAction.getKey(), resendBuildAction.getValue()); } } catch (Exception e ){ GrapesPlugin.getLogger().log(Level.SEVERE, "[GRAPES] Failed to re-send notification: ", e); } } refresh(); return HttpRedirect.DOT; }
public HttpResponse cors(@CheckForNull String accessKey, final HttpResponse resp) { final MetricsAccessKey key = getAccessKey(accessKey); return key == null ? resp : new HttpResponse() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { String origin = req.getHeader("Origin"); if (StringUtils.isNotBlank(origin) && key.isOriginAllowed(origin)) { rsp.addHeader("Access-Control-Allow-Origin", origin); rsp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); rsp.addHeader("Access-Control-Allow-Headers", "Accept, Authorization"); if ("OPTIONS".equals(req.getMethod())) { rsp.setStatus(200); return; } } resp.generateResponse(req, rsp, node); } }; }
/** * Binds the health checks to the CORS aware URL {@code /metrics/healthcheck} 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 public HttpResponse doHealthcheck(StaplerRequest req, @QueryParameter("key") String key) throws IllegalAccessException { requireCorrectMethod(req); if (StringUtils.isBlank(key)) { key = getKeyFromAuthorizationHeader(req); } Metrics.checkAccessKeyHealthCheck(key); long ifModifiedSince = req.getDateHeader("If-Modified-Since"); long maxAge = getCacheControlMaxAge(req); Metrics.HealthCheckData data = Metrics.getHealthCheckData(); if (data == null || (maxAge != -1 && data.getLastModified() + maxAge < System.currentTimeMillis())) { data = new Metrics.HealthCheckData(Metrics.healthCheckRegistry().runHealthChecks()); } else if (ifModifiedSince != -1 && data.getLastModified() < ifModifiedSince) { return Metrics.cors(key, HttpResponses.status(HttpServletResponse.SC_NOT_MODIFIED)); } return Metrics.cors(key, new HealthCheckResponse(data)); }
/** * Condense the health check into one bit of information * for frontend reverse proxies like haproxy. * * Other health check calls requires authentication, which * is not suitable for the haproxy use. But this endpoint * only exposes one bit information, it's deemed OK to be exposed * unsecurely. * * return status 200 if everything is OK, 503 (service unavailable) otherwise * * @param req the request * @return the HTTP response */ @SuppressWarnings("unused") // stapler binding @Restricted(NoExternalUse.class) // stapler binding public HttpResponse doHealthcheckOk(StaplerRequest req) { long ifModifiedSince = req.getDateHeader("If-Modified-Since"); long maxAge = getCacheControlMaxAge(req); Metrics.HealthCheckData data = Metrics.getHealthCheckData(); if (data == null || (maxAge != -1 && data.getLastModified() + maxAge < System.currentTimeMillis())) { data = new Metrics.HealthCheckData(Metrics.healthCheckRegistry().runHealthChecks()); } else if (ifModifiedSince != -1 && data.getLastModified() < ifModifiedSince) { return HttpResponses.status(HttpServletResponse.SC_NOT_MODIFIED); } for (HealthCheck.Result result : data.getResults().values()) { if (!result.isHealthy()) { return new StatusResponse(HttpServletResponse.SC_SERVICE_UNAVAILABLE, data.getLastModified(), data.getExpires()); } } return new StatusResponse(HttpServletResponse.SC_OK, data.getLastModified(), data.getExpires()); }
/** * Web binding for {@literal /} * * @return the response */ @Restricted(NoExternalUse.class) // only for use by stapler web binding public HttpResponse doIndex() { return HttpResponses .html("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n" + " \"http://www.w3.org/TR/html4/loose.dtd\">\n" + "<html>\n" + "<head>\n" + " <title>Metrics</title>\n" + "</head>\n" + "<body>\n" + " <h1>Operational Menu</h1>\n" + " <ul>\n" + " <li><a href=\"./metrics?pretty=true\">Metrics</a></li>\n" + " <li><a href=\"./ping\">Ping</a></li>\n" + " <li><a href=\"./threads\">Threads</a></li>\n" + " <li><a href=\"./healthcheck?pretty=true\">Healthcheck</a></li>\n" + " </ul>\n" + "</body>\n" + "</html>"); }
public HttpResponse doFinishLogin(StaplerRequest request, StaplerResponse rsp) throws IOException { String code = request.getParameter("code"); if (code == null || code.trim().length() == 0) { Log.info("doFinishLogin: missing code."); return HttpResponses.redirectToContextRoot(); } String content = postForAccessToken(code); String accessToken = extractToken(content); updateOfflineAccessTokenForUser(accessToken); request.getSession().setAttribute("access_token", accessToken); String newProjectSetupUrl = getJenkinsRootUrl() + "/" + GithubReposController.URL; return HttpResponses.redirectTo(newProjectSetupUrl); }
/** * Generates a response containing issue data, but first logs in to YouTrack. * * @return the response. */ public HttpResponse doIssue() { return new HttpResponse() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { String id = req.getParameter("id"); YouTrackSite youTrackSite = YouTrackSite.get(project); if (youTrackSite == null) { rsp.getWriter().write("YouTrack integration not set up for this project"); return; } YouTrackServer youTrackServer = new YouTrackServer(youTrackSite.getUrl()); User user = youTrackServer.login(youTrackSite.getUsername(), youTrackSite.getPassword()); Issue issue = youTrackServer.getIssue(user, id); Gson gson = new Gson(); String json = gson.toJson(issue); rsp.getWriter().write(json); } }; }
/** * 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"); }
/** * Serves the codeCoverage badge image. * * @param req * @param rsp * @param job * @return */ public HttpResponse doCoverageIcon(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job) { Job<?, ?> project = getProject(job); Integer codeCoverage = null; if (project.getLastSuccessfulBuild() != null) { PluginWrapper jacocoInstalled = getInstance().pluginManager.getPlugin("jacoco"); // Checks for Jacoco if (jacocoInstalled != null && jacocoInstalled.isActive()) { JacocoBuildAction jacocoAction = project.getLastSuccessfulBuild().getAction(JacocoBuildAction.class); if (jacocoAction != null) { if (jacocoAction.getInstructionCoverage() != null){ codeCoverage = jacocoAction.getInstructionCoverage().getPercentage(); } } } PluginWrapper coberturaInstalled = getInstance().pluginManager.getPlugin("cobertura"); // Checks for Cobertura if (coberturaInstalled != null && coberturaInstalled.isActive()) { CoberturaBuildAction coverageAction = project.getLastSuccessfulBuild().getAction(CoberturaBuildAction.class); if (coverageAction != null) { if (coverageAction.getBuildHealth() != null){ codeCoverage = coverageAction.getResults().get(CoverageMetric.LINE).getPercentage(); } } } PluginWrapper cloverInstalled = getInstance().pluginManager.getPlugin("clover"); // Checks for Clover if (cloverInstalled != null && cloverInstalled.isActive()) { CloverBuildAction cloverAction = project.getLastSuccessfulBuild().getAction(CloverBuildAction.class); if (cloverAction != null){ if (cloverAction.getBuildHealth() != null){ codeCoverage = cloverAction.getElementCoverage().getPercentage(); } } } } return iconResolver.getCoverageImage(codeCoverage); }
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException { String code = request.getParameter("code"); if (StringUtils.isBlank(code)) { LOGGER.log(Level.SEVERE, "doFinishLogin() code = null"); return HttpResponses.redirectToContextRoot(); } DeepinToken token = new DeepinOAuthApiService(clientID, clientSecret).getTokenByAuthorizationCode(code); if (!token.accessToken.isEmpty()) { DeepinAuthenticationToken auth = new DeepinAuthenticationToken(token, clientID, clientSecret); SecurityContextHolder.getContext().setAuthentication(auth); User u = User.current(); u.setFullName(auth.getName()); } else { LOGGER.log(Level.SEVERE, "doFinishLogin() accessToken = null"); } // redirect to referer String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE); if (referer != null) { return HttpResponses.redirectTo(referer); } else { return HttpResponses.redirectToContextRoot(); } }
public static HttpResponse jsonResponse(final Object payload) { return new HttpResponse() { @Override public void generateResponse(StaplerRequest request, StaplerResponse response, Object node) throws IOException, ServletException { response.setContentType("application/json"); if (payload != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); objectMapper.writeValue(buffer, payload); response.getOutputStream().write(buffer.toByteArray()); } } }; }
public static HttpResponse jsonResponse(final CollectorRegistry collectorRegistry) { return new HttpResponse() { @Override public void generateResponse(StaplerRequest request, StaplerResponse response, Object node) throws IOException, ServletException { response.setStatus(StaplerResponse.SC_OK); response.setContentType(TextFormat.CONTENT_TYPE_004); StringWriter buffer = new StringWriter(); TextFormat.write004(buffer, collectorRegistry.metricFamilySamples()); buffer.close(); response.getWriter().write(buffer.toString()); } }; }
/** * When the slave is deleted, terminate the instance. */ @Override public HttpResponse doDoDelete() throws IOException { checkPermission(DELETE); if (getNode() != null) getNode().terminate(); return new HttpRedirect(".."); }
/** * 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(); }
/** * Retrieves the latest raw status via API. * The output will be retrieved in JSON. * @param id ID of the image, for which the info should be retrieved. * Short container IDs are not supported. * @throws IOException Processing error * @throws ServletException Servlet error * @return {@link HttpResponse} */ public HttpResponse doRawImageInfo(@QueryParameter(required = true) String id) throws IOException, ServletException { checkPermission(DockerTraceabilityPlugin.READ_DETAILS); final InspectImageResponse report = DockerTraceabilityHelper.getLastInspectImageResponse(id); if (report == null) { return HttpResponses.error(404, "No info available for the imageId=" + id); } // Return raw JSON in the response InspectImageResponse[] out = {report}; return toJSONResponse(out); }
/** * Serves the JSON response. * @param item Data to be serialized to JSON * @return HTTP response with application/json MIME type */ private static HttpResponse toJSONResponse(final Object item) { return new HttpResponse() { @Override public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { ObjectMapper mapper = new ObjectMapper(); rsp.setContentType("application/json;charset=UTF-8"); mapper.writeValue(rsp.getWriter(), item); } }; }
@Test @Bug(28656) public void createFingerPrintsOnDemand() throws Exception { // Read data from resources String inspectData = JSONSamples.inspectContainerData.readString(); InspectContainerResponse inspectResponse = JSONSamples.inspectContainerData. readObject(InspectContainerResponse[].class)[0]; final String containerId = inspectResponse.getId(); final String imageId = inspectResponse.getImageId(); // Retrieve instances final DockerTraceabilityRootAction action = DockerTraceabilityRootAction.getInstance(); assertNotNull(action); // Enable automatic fingerprints creation DockerTraceabilityPluginConfiguration config = new DockerTraceabilityPluginConfiguration(true, false); DockerTraceabilityPluginTest.configure(config); DockerTraceabilityPlugin plugin = DockerTraceabilityPlugin.getInstance(); assertTrue(plugin.getConfiguration().isCreateImageFingerprints()); // Submit JSON HttpResponse res = action.doSubmitContainerStatus(inspectData, null, null, null, 0, null, null); // Ensure that both container and images have been created with proper facets Fingerprint imageFP = DockerFingerprints.of(imageId); Fingerprint containerFP = DockerFingerprints.of(containerId); assertNotNull(imageFP); assertNotNull(DockerFingerprints.getFacet(imageFP, DockerDeploymentRefFacet.class)); assertNotNull(containerFP); assertNotNull(DockerFingerprints.getFacet(containerFP, DockerDeploymentFacet.class)); // TODO: JENKINS-28655 (Fingerprints cleanup) // Check original references - Docker Traceability Manager should create runs // assertNotNull(imageFP.getOriginal().getJob()); // assertNotNull(containerFP.getOriginal().getJob()); }
public HttpResponse doConfigSubmit(StaplerRequest req) throws ServletException, IOException { repository = null; // otherwise bindJSON will never clear it once set req.bindJSON(this, req.getSubmittedForm()); getConfigFile().write(this); ((VMRepositoryDescriptor)this.getDescriptor()).setVms(this.getVms()); return FormApply.success("."); }
public HttpResponse doConfigSubmit(StaplerRequest req) throws ServletException, IOException { repository = null; // otherwise bindJSON will never clear it once set req.bindJSON(this, req.getSubmittedForm()); getConfigFile().write(this); ((BlueprintsRepositoryDescriptor)this.getDescriptor()).setBlueprints(this.getBlueprints()); return FormApply.success("."); }
/** * Starts the deploy now action. * * @param req the request. * @return the response. */ @SuppressWarnings("unused") // used by stapler public HttpResponse doIndex(StaplerRequest req) { if (!isDeployPossible(owner)) { return HttpResponses.notFound(); } return HttpResponses.forwardToView(this, "configure"); }
@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("."); }
public HttpResponse doBuildJob(@QueryParameter String issueId) { @SuppressWarnings("rawtypes") AbstractProject project = PayLoadInterceptorAction.getMatchingJob(issueId); if (project != null && project.isBuildable()) { project.scheduleBuild2(0); } return HttpResponses.plainText("Buld triggered: "+issueId); }
public static HttpResponse cors(@CheckForNull String accessKey, final HttpResponse resp) { Jenkins jenkins = Jenkins.getInstance(); MetricsAccessKey.DescriptorImpl descriptor = jenkins == null ? null : jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class); if (descriptor == null) { throw new IllegalStateException(); } return descriptor.cors(accessKey, resp); }
/** * Binds the metrics to the CORS aware URL {@code /metrics/metrics} 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 public HttpResponse doMetrics(StaplerRequest req, @QueryParameter("key") String key) throws IllegalAccessException { requireCorrectMethod(req); if (StringUtils.isBlank(key)) { key = getKeyFromAuthorizationHeader(req); } Metrics.checkAccessKeyMetrics(key); return Metrics.cors(key, new MetricsResponse(Metrics.metricRegistry())); }
/** * Binds the metrics history to the CORS aware URL {@code /metrics/metricsHistory} 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 public HttpResponse doMetricsHistory(StaplerRequest req, @QueryParameter("key") String key) throws IllegalAccessException { if (!Sampler.isEnabled()) { return HttpResponses.notFound(); } requireCorrectMethod(req); if (StringUtils.isBlank(key)) { key = getKeyFromAuthorizationHeader(req); } Metrics.checkAccessKeyMetrics(key); return Metrics.cors(key, new MetricsHistoryResponse()); }
/** * Binds the ping check to the CORS aware URL {@code /metrics/ping} 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 public HttpResponse doPing(StaplerRequest req, @QueryParameter("key") String key) throws IllegalAccessException { requireCorrectMethod(req); if (StringUtils.isBlank(key)) { key = getKeyFromAuthorizationHeader(req); } Metrics.checkAccessKeyPing(key); return Metrics.cors(key, new PingResponse()); }
/** * 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()))); }
/** * Web binding for {@literal /healthcheck} * * @param req the request * @return the response */ @Restricted(NoExternalUse.class) // only for use by stapler web binding public HttpResponse doHealthcheck(StaplerRequest req) { long ifModifiedSince = req.getDateHeader("If-Modified-Since"); long maxAge = getCacheControlMaxAge(req); Metrics.HealthCheckData data = Metrics.getHealthCheckData(); if (data == null || (maxAge != -1 && data.getLastModified() + maxAge < System.currentTimeMillis())) { // if the max-age was specified, get live data data = new Metrics.HealthCheckData(Metrics.healthCheckRegistry().runHealthChecks()); } else if (ifModifiedSince != -1 && data.getLastModified() < ifModifiedSince) { return HttpResponses.status(HttpServletResponse.SC_NOT_MODIFIED); } return new HealthCheckResponse(data); }
/** * Web binding for {@literal /metricsHistory} * * @return the response */ @Restricted(NoExternalUse.class) // only for use by stapler web binding public HttpResponse doMetricsHistory() { if (!Sampler.isEnabled()) { return HttpResponses.notFound(); } return new MetricsHistoryResponse(); }