/** * {@inheritDoc} */ @Override public void onChange(Saveable o, XmlFile file) { if (!(o instanceof Item)) { // must be an Item return; } SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem((Item) o); if (item == null) { // more specifically must be an SCMTriggerItem return; } SCMTrigger trigger = item.getSCMTrigger(); if (trigger == null || trigger.isIgnorePostCommitHooks()) { // must have the trigger enabled and not opted out of post commit hooks return; } for (SCM scm : item.getSCMs()) { if (scm instanceof GitSCM) { // we have a winner GiteaWebhookListener.register(item, (GitSCM) scm); } } }
public ListBoxModel doFillMirrorgateCredentialsIdItems( @AncestorInPath Item item, @QueryParameter("mirrorgateCredentialsId") String credentialsId) { StandardListBoxModel result = new StandardListBoxModel(); if (item == null) { if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) { return result.includeCurrentValue(credentialsId); } } else if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) { return result.includeCurrentValue(credentialsId); } return result .includeEmptyValue() .includeAs(ACL.SYSTEM, item, StandardUsernamePasswordCredentials.class); }
public FormValidation doCheckMirrorgateCredentialsId( @AncestorInPath Item item, @QueryParameter("mirrorgateCredentialsId") String credentialsId) { if (item == null) { if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) { return FormValidation.ok(); } } else if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) { return FormValidation.ok(); } if (StringUtils.isBlank(credentialsId)) { return FormValidation.ok(); } if (credentialsId.startsWith("${") && credentialsId.endsWith("}")) { return FormValidation.warning( "Cannot validate expression based credentials"); } return FormValidation.ok(); }
@SuppressWarnings("unused") public void doIndex() throws IOException { HttpServletRequest req = Stapler.getCurrentRequest(); GerritProjectEvent projectEvent = getBody(req); log.info("GerritWebHook invoked for event " + projectEvent); List<Item> jenkinsItems = Jenkins.getActiveInstance().getAllItems(); for (Item item : jenkinsItems) { if (item instanceof SCMSourceOwner) { SCMSourceOwner scmJob = (SCMSourceOwner) item; log.info("Found SCM job " + scmJob); List<SCMSource> scmSources = scmJob.getSCMSources(); for (SCMSource scmSource : scmSources) { if (scmSource instanceof GerritSCMSource) { GerritSCMSource gerritSCMSource = (GerritSCMSource) scmSource; if (projectEvent.matches(gerritSCMSource.getRemote())) { log.info( "Triggering SCM event for source " + scmSources.get(0) + " on job " + scmJob); scmJob.onSCMSourceUpdated(scmSource); } } } } } }
public ListBoxModel doFillCredentialsIdItems( @AncestorInPath Item context, @QueryParameter String remote, @QueryParameter String credentialsId) { if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER) || context != null && !context.hasPermission(Item.EXTENDED_READ)) { return new StandardListBoxModel().includeCurrentValue(credentialsId); } return new StandardListBoxModel() .includeEmptyValue() .includeMatchingAs( context instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) context) : ACL.SYSTEM, context, StandardUsernameCredentials.class, URIRequirementBuilder.fromUri(remote).build(), GitClient.CREDENTIALS_MATCHER) .includeCurrentValue(credentialsId); }
@Restricted(NoExternalUse.class) public ListBoxModel doFillCheckoutCredentialsIdItems(@AncestorInPath SCMSourceOwner context, @QueryParameter String connectionName, @QueryParameter String checkoutCredentialsId) { if (context == null && !Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) || context != null && !context.hasPermission(Item.EXTENDED_READ)) { return new StandardListBoxModel().includeCurrentValue(checkoutCredentialsId); } StandardListBoxModel result = new StandardListBoxModel(); result.add("- anonymous -", CHECKOUT_CREDENTIALS_ANONYMOUS); return result.includeMatchingAs( context instanceof Queue.Task ? Tasks.getDefaultAuthenticationOf((Queue.Task) context) : ACL.SYSTEM, context, StandardUsernameCredentials.class, SettingsUtils.gitLabConnectionRequirements(connectionName), GitClient.CREDENTIALS_MATCHER ); }
/** * Fills in the Host Connection selection box with applicable connections. * * @param context * filter for host connections * @param connectionId * an existing host connection identifier; can be null * @param project * the Jenkins project * * @return host connection selections */ public ListBoxModel doFillConnectionIdItems(@AncestorInPath Jenkins context, @QueryParameter String connectionId, @AncestorInPath Item project) { CpwrGlobalConfiguration globalConfig = CpwrGlobalConfiguration.get(); HostConnection[] hostConnections = globalConfig.getHostConnections(); ListBoxModel model = new ListBoxModel(); model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false)); for (HostConnection connection : hostConnections) { boolean isSelected = false; if (connectionId != null) { isSelected = connectionId.matches(connection.getConnectionId()); } model.add(new Option(connection.getDescription() + " [" + connection.getHostPort() + ']', //$NON-NLS-1$ connection.getConnectionId(), isSelected)); } return model; }
/** * Fills in the Login Credentials selection box with applicable connections. * * @param context * filter for login credentials * @param credentialsId * existing login credentials; can be null * @param project * the Jenkins project * * @return login credentials selection */ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId, @AncestorInPath Item project) { List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials( StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList()); ListBoxModel model = new ListBoxModel(); model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false)); for (StandardUsernamePasswordCredentials c : creds) { boolean isSelected = false; if (credentialsId != null) { isSelected = credentialsId.matches(c.getId()); } String description = Util.fixEmptyAndTrim(c.getDescription()); model.add(new Option(c.getUsername() + (description != null ? " (" + description + ')' : StringUtils.EMPTY), //$NON-NLS-1$ c.getId(), isSelected)); } return model; }
@Test public void testConfigureBuildFilterParameter() throws Exception { RunFilterParameter param = new RunFilterParameter( "PARAM", "description", new AndRunFilter( new ParametersRunFilter("PARAM1=VALUE1"), new SavedRunFilter() ) ); WorkflowJob job = j.jenkins.createProject( WorkflowJob.class, RandomStringUtils.randomAlphanumeric(7) ); job.addProperty(new ParametersDefinitionProperty(param)); j.configRoundtrip((Item)job); j.assertEqualDataBoundBeans( param, job.getProperty(ParametersDefinitionProperty.class) .getParameterDefinition("PARAM") ); }
/** * Fills in the Login Credentials selection box with applicable Jenkins credentials. * * @param context * filter for credentials * @param credentialsId * existing login credentials; can be null * @param project * the Jenkins project * * @return credential selections */ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId, @AncestorInPath Item project) { List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials( StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList()); StandardListBoxModel model = new StandardListBoxModel(); model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false)); for (StandardUsernamePasswordCredentials c : creds) { boolean isSelected = false; if (credentialsId != null) { isSelected = credentialsId.matches(c.getId()); } String description = Util.fixEmptyAndTrim(c.getDescription()); model.add(new Option(c.getUsername() + (description != null ? " (" + description + ')' : StringUtils.EMPTY), //$NON-NLS-1$ c.getId(), isSelected)); } return model; }
/** * Retrieves login information given a credential ID. * * @param project * the Jenkins project * * @return a Jenkins credential with login information */ protected StandardUsernamePasswordCredentials getLoginInformation(Item project) { StandardUsernamePasswordCredentials credential = null; List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials( StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList()); IdMatcher matcher = new IdMatcher(getCredentialsId()); for (StandardUsernamePasswordCredentials c : credentials) { if (matcher.matches(c)) { credential = c; } } return credential; }
/** * Retrieves login information given a credential ID * * @param project * the Jenkins project * * @return a Jenkins credential with login information */ protected StandardUsernamePasswordCredentials getLoginInformation(Item project) { StandardUsernamePasswordCredentials credential = null; List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials( StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList()); IdMatcher matcher = new IdMatcher(getCredentialsId()); for (StandardUsernamePasswordCredentials c : credentials) { if (matcher.matches(c)) { credential = c; } } return credential; }
/** * Search in Jenkins for a item with type T based on the job name * @param jobName job to find, for jobs inside a folder use : {@literal <folder>/<folder>/<jobName>} * @return the Job matching the given name, or {@code null} when not found */ static <T extends Item> T find(String jobName, Class<T> type) { Jenkins jenkins = Jenkins.getActiveInstance(); // direct search, can be used to find folder based items <folder>/<folder>/<jobName> T item = jenkins.getItemByFullName(jobName, type); if (item == null) { // not found in a direct search, search in all items since the item might be in a folder but given without folder structure // (to keep it backwards compatible) for (T allItem : jenkins.getAllItems(type)) { if (allItem.getName().equals(jobName)) { item = allItem; break; } } } return item; }
@CheckForNull private static FormValidation checkForDuplicates(String value, ModelObject context, ModelObject object) { for (CredentialsStore store : CredentialsProvider.lookupStores(object)) { if (!store.hasPermission(CredentialsProvider.VIEW)) { continue; } ModelObject storeContext = store.getContext(); for (Domain domain : store.getDomains()) { if (CredentialsMatchers.firstOrNull(store.getCredentials(domain), CredentialsMatchers.withId(value)) != null) { if (storeContext == context) { return FormValidation.error("This ID is already in use"); } else { return FormValidation.warning("The ID ‘%s’ is already in use in %s", value, storeContext instanceof Item ? ((Item) storeContext).getFullDisplayName() : storeContext.getDisplayName()); } } } } return null; }
public static ListBoxModel doFillCredentialsIDItems(@AncestorInPath Jenkins context) { if (context == null || !context.hasPermission(Item.CONFIGURE)) { return new StandardListBoxModel(); } List<DomainRequirement> domainRequirements = new ArrayList<DomainRequirement>(); return new StandardListBoxModel() .withEmptySelection() .withMatching( CredentialsMatchers.anyOf( CredentialsMatchers.instanceOf(ConduitCredentials.class)), CredentialsProvider.lookupCredentials( StandardCredentials.class, context, ACL.SYSTEM, domainRequirements)); }
public boolean executeCheck(Item item) { boolean notfound = true; if (Jenkins.getInstance().pluginManager.getPlugin("build-timeout") != null) { if (item.getClass().getName().endsWith("hudson.maven.MavenModuleSet")) { try { Method method = item.getClass().getMethod("getBuildWrappersList"); DescribableList<BuildWrapper,Descriptor<BuildWrapper>> buildWrapperList = ((DescribableList<BuildWrapper,Descriptor<BuildWrapper>>) method.invoke(item)); notfound = !isTimeout(buildWrapperList); } catch (Exception e) { LOG.log(Level.WARNING, "Exception " + e.getMessage(), e.getCause()); notfound = false; } } if (item instanceof Project) { notfound = !isTimeout(((Project) item).getBuildWrappersList()); } if (item instanceof MatrixProject) { notfound = !isTimeout(((MatrixProject) item).getBuildWrappersList()); } } return notfound; }
public boolean executeCheck(Item item) { boolean found = false; if (Jenkins.getInstance().pluginManager.getPlugin("gradle") != null) { if (Jenkins.getInstance().pluginManager.getPlugin("maven-plugin")!=null) { if (item instanceof MavenModuleSet) { found = isGradlew(((MavenModuleSet) item).getPrebuilders()); } } if (item instanceof Project) { found = isGradlew(((Project) item).getBuilders()); } if (item instanceof MatrixProject) { found = isGradlew(((MatrixProject) item).getBuilders()); } } return found; }
public boolean executeCheck(Item item) { LOG.log(Level.FINE, "executeCheck " + item); if (item instanceof Project) { Project project = (Project) item; DescribableList<Publisher, Descriptor<Publisher>> publishersList = project.getPublishersList(); for (Publisher publisher : publishersList) { if (publisher instanceof ArtifactArchiver) { LOG.log(Level.FINEST, "ArtifactChecker " + publisher); return (((ArtifactArchiver) publisher).getArtifacts() == null || (((ArtifactArchiver) publisher).getArtifacts() != null && ((ArtifactArchiver) publisher).getArtifacts().length() == 0)); } } } return false; }
public boolean executeCheck(Item item) { LOG.log(Level.FINE, "executeCheck " + item); boolean found = false; if (Jenkins.getInstance().pluginManager.getPlugin("maven-plugin")!=null) { if (item instanceof MavenModuleSet) { found = isBuilderHarcoded(((MavenModuleSet) item).getPrebuilders()); } } if (item instanceof Project) { found = isBuilderHarcoded (((Project)item).getBuilders()); } if (item instanceof MatrixProject) { found = isBuilderHarcoded (((MatrixProject)item).getBuilders()); } return found; }
public static void forEachJob(Callback<Job> callback) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins != null) { List<Item> items = jenkins.getAllItems(); if (items != null) { for (Item item : items) { Collection<? extends Job> jobs = item.getAllJobs(); if (jobs != null) { for (Job job : jobs) { if (job != null) { callback.invoke(job); } } } } } } }
/** * Plugins that want to refer to a {@link IdCredentials} should do so via ID string, * and use this method to resolve it and convert to {@link DockerRegistryToken}. * * @param context * If you are a build step trying to access DockerHub in the context of a build/job, * specify that job. Otherwise null. If you are scoped to something else, you might * have to interact with {@link CredentialsProvider} directly. */ public @CheckForNull DockerRegistryToken getToken(Item context) { if (credentialsId == null) { return null; } // as a build step, your access to credentials are constrained by what the build // can access, hence Jenkins.getAuthentication() List<DomainRequirement> requirements = Collections.emptyList(); try { requirements = Collections.<DomainRequirement>singletonList(new HostnameRequirement(getEffectiveUrl().getHost())); } catch (IOException e) { // shrug off this error and move on. We are matching with ID anyway. } // look for subtypes that know how to create a token, such as Google Container Registry return AuthenticationTokens.convert(DockerRegistryToken.class, firstOrNull(CredentialsProvider.lookupCredentials( IdCredentials.class, context, Jenkins.getAuthentication(),requirements), allOf(AuthenticationTokens.matcher(DockerRegistryToken.class), withId(credentialsId)))); }
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item) { if (item == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER) || item != null && !item.hasPermission(Item.EXTENDED_READ)) { return new StandardListBoxModel(); } // TODO may also need to specify a specific authentication and domain requirements return new StandardListBoxModel() .withEmptySelection() .withMatching(AuthenticationTokens.matcher(DockerRegistryToken.class), CredentialsProvider.lookupCredentials( StandardCredentials.class, item, null, Collections.<DomainRequirement>emptyList() ) ); }
/** * Makes the key materials available locally and returns {@link KeyMaterialFactory} that gives you the parameters * needed to access it. */ public KeyMaterialFactory newKeyMaterialFactory(@Nonnull Item context, @Nonnull VirtualChannel target) throws IOException, InterruptedException { // as a build step, your access to credentials are constrained by what the build // can access, hence Jenkins.getAuthentication() DockerServerCredentials creds=null; if (credentialsId!=null) { List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(getUri()).build(); domainRequirements.add(new DockerServerDomainRequirement()); creds = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( DockerServerCredentials.class, context, Jenkins.getAuthentication(), domainRequirements), CredentialsMatchers.withId(credentialsId) ); } // the directory needs to be outside workspace to avoid prying eyes FilePath dotDocker = dotDocker(target); dotDocker.mkdirs(); // ServerKeyMaterialFactory.materialize creates a random subdir if one is needed: return newKeyMaterialFactory(dotDocker, creds); }
@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; }