Java Code Examples for jenkins.model.Jenkins#get()

The following examples show how to use jenkins.model.Jenkins#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LDAPTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@ConfiguredWithReadme("ldap/README.md")
public void configure_ldap() {
    final Jenkins jenkins = Jenkins.get();
    final LDAPSecurityRealm securityRealm = (LDAPSecurityRealm) jenkins.getSecurityRealm();
    assertEquals(1, securityRealm.getConfigurations().size());
    assertTrue(securityRealm.getUserIdStrategy() instanceof IdStrategy.CaseInsensitive);
    assertTrue(securityRealm.getGroupIdStrategy() instanceof IdStrategy.CaseSensitive);
    final LDAPConfiguration configuration = securityRealm.getConfigurations().get(0);
    assertEquals("ldap.acme.com", configuration.getServer());
    assertEquals("SECRET", configuration.getManagerPassword());
    assertEquals("manager", configuration.getManagerDN());
    assertEquals("(&(objectCategory=User)(sAMAccountName={0}))", configuration.getUserSearch());
    assertEquals("(&(cn={0})(objectclass=group))", configuration.getGroupSearchFilter());
    final FromGroupSearchLDAPGroupMembershipStrategy strategy = ((FromGroupSearchLDAPGroupMembershipStrategy) configuration.getGroupMembershipStrategy());
    assertEquals("(&(objectClass=group)(|(cn=GROUP_1)(cn=GROUP_2)))", strategy.getFilter());
}
 
Example 2
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Restricted(NoExternalUse.class)
private String getApiToken(String apiTokenId, Item item) {
    ItemGroup<?> context = null != item ? item.getParent() : Jenkins.get();
    StandardCredentials credentials = CredentialsMatchers.firstOrNull(
        lookupCredentials(
                StandardCredentials.class,
                context, 
                ACL.SYSTEM,
                URIRequirementBuilder.fromUri(url).build()),
        CredentialsMatchers.withId(apiTokenId));
    if (credentials != null) {
        if (credentials instanceof GitLabApiToken) {
            return ((GitLabApiToken) credentials).getApiToken().getPlainText();
        }
        if (credentials instanceof StringCredentials) {
            return ((StringCredentials) credentials).getSecret().getPlainText();
        }
    }
    throw new IllegalStateException("No credentials found for credentialsId: " + apiTokenId);
}
 
Example 3
Source File: JiraCloudSiteConfig.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter final String credentialsId) {
    Jenkins instance = Jenkins.get();
    if (!instance.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeMatchingAs(
                    ACL.SYSTEM,
                    instance,
                    StringCredentials.class,
                    URIRequirementBuilder.fromUri(ATLASSIAN_API_URL).build(),
                    CredentialsMatchers.always());
}
 
Example 4
Source File: GitLabServer.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @param credentialsId the credentials Id
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {
    Jenkins jenkins = Jenkins.get();
    if (!jenkins.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    return new StandardListBoxModel()
        .includeEmptyValue()
        .includeMatchingAs(ACL.SYSTEM,
            jenkins,
            StandardCredentials.class,
            fromUri(serverUrl).build(),
            CREDENTIALS_MATCHER
        );
}
 
Example 5
Source File: GlobalNodePropertiesTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void configure() throws Exception {
    final Jenkins jenkins = Jenkins.get();

    DescribableList<NodeProperty<?>, NodePropertyDescriptor> nodeProperties = jenkins.getGlobalNodeProperties();

    Set<Map.Entry<String, String>> entries = ((EnvironmentVariablesNodeProperty) nodeProperties.get(0)).getEnvVars().entrySet();
    assertEquals(1, entries.size());

    Map.Entry<String, String> envVar = entries.iterator().next();
    assertEquals("FOO", envVar.getKey());
    assertEquals("BAR", envVar.getValue());
}
 
Example 6
Source File: JenkinsConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("HeteroDescribable.yml")
public void jenkins_abstract_describable_attributes() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertTrue(jenkins.getSecurityRealm() instanceof HudsonPrivateSecurityRealm);
    assertTrue(jenkins.getAuthorizationStrategy() instanceof FullControlOnceLoggedInAuthorizationStrategy);
    assertFalse(((FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy()).isAllowAnonymousRead());
}
 
Example 7
Source File: YamlMaxAliasesCollectionTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void testAMaxOfTwoEnv() throws ConfiguratorException {
    env.set(ConfigurationContext.CASC_YAML_MAX_ALIASES_ENV, "2");
    ConfigurationAsCode.get().configure(getClass().getResource("maxAliasesLimit.yml").toExternalForm());
    final Jenkins jenkins = Jenkins.get();
    assertEquals(2, jenkins.getNodes().size());
    assertEquals("static-agent1", jenkins.getNode("static-agent1").getNodeName());
    assertEquals("static-agent2", jenkins.getNode("static-agent2").getNodeName());
}
 
Example 8
Source File: MailerTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("mailer/README.md")
public void configure_mailer() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
    assertEquals("4441", descriptor.getSmtpPort());
    assertEquals("[email protected]", descriptor.getReplyToAddress());
    assertEquals("smtp.acme.org", descriptor.getSmtpHost() );
}
 
Example 9
Source File: AdminWhitelistRuleConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("Issue #28")
@ConfiguredWithCode("AdminWhitelistRuleConfigurator/Agent2MasterSecurityKillSwitch_disabled.yml")
public void checkM2ASecurityKillSwitch_enabled() {
    final Jenkins jenkins = Jenkins.get();
    AdminWhitelistRule rule = jenkins.getInjector().getInstance(AdminWhitelistRule.class);
    Assert.assertTrue("MasterToAgent Security should be enabled", rule.getMasterKillSwitch());
}
 
Example 10
Source File: SeedJobTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("SeedJobTest.yml")
public void configure_seed_job() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertNotNull(jenkins.getItem("testJob1"));
    assertNotNull(jenkins.getItem("testJob2"));
}
 
Example 11
Source File: JenkinsConfigTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldExportEvenOnError() throws Exception {
    Jenkins j = Jenkins.get();
    j.setCrumbIssuer(new BrokenCrumbIssuer("bar"));
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ConfigurationAsCode.get().export(out);
    final String s = out.toString();
    assertThat(s, is(not(emptyOrNullString())));
}
 
Example 12
Source File: EssentialsTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("EssentialsTest.yml")
public void essentialsTest() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertEquals("Welcome to Jenkins Essentials!", jenkins.getSystemMessage());

    final ExtensionList<MetricsAccessKey.DescriptorImpl> metricsDescriptors = ExtensionList.lookup(MetricsAccessKey.DescriptorImpl.class);
    assertNotNull(metricsDescriptors);
    assertThat(metricsDescriptors, hasSize(1));

    MetricsAccessKey.DescriptorImpl metricsDescriptor = metricsDescriptors.get(0);

    final List<MetricsAccessKey> accessKeys = metricsDescriptor.getAccessKeys();
    assertThat(accessKeys, hasSize(1));

    MetricsAccessKey accessKey = accessKeys.get(0);
    assertThat(accessKey.getKey(), is("evergreen"));
    assertThat(accessKey.getDescription(), is("Key for evergreen health-check"));
    assertThat(accessKey.isCanHealthCheck(), is(true));
    assertThat(accessKey.isCanPing(), is(false));
    assertThat(accessKey.isCanPing(), is(false));
    assertThat(accessKey.isCanThreadDump(), is(false));
    assertThat(accessKey.isCanMetrics(), is(false));
    assertThat(accessKey.getOrigins(), is("*"));

    //metricsDescriptor.g
}
 
Example 13
Source File: AdminWhitelistRuleConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("Issue #172")
@ConfiguredWithCode("AdminWhitelistRuleConfigurator/Agent2MasterSecurityKillSwitch_enabled.yml")
public void checkA2MAccessControl_enabled() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    MasterKillSwitchConfiguration config = jenkins.getDescriptorByType(MasterKillSwitchConfiguration.class);
    Assert.assertTrue("Agent → Master Access Control should be enabled", config.getMasterToSlaveAccessControl());
    AdminWhitelistRule rule = jenkins.getInjector().getInstance(AdminWhitelistRule.class);
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Configurator c = context.lookupOrFail(AdminWhitelistRule.class);
    final CNode node = c.describe(rule, context);
    final Mapping agent = node.asMapping();
    assertEquals("true", agent.get("enabled").toString());
}
 
Example 14
Source File: AgentProtocolsTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode(value = "AgentProtocolsTest.yml")
public void configure_agent_protocols() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final Set<String> agentProtocols =
            Arrays.stream(new String[]{"JNLP4-connect", "Ping"}).collect(Collectors.toSet());
    assertEquals(agentProtocols, jenkins.getAgentProtocols());
}
 
Example 15
Source File: SeedJobTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@ConfiguredWithCode("SeedJobTest_withEnvVars.yml")
public void configure_seed_job_with_env_vars() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertNotNull(jenkins.getItem("seedJobWithEnvVars"));
}
 
Example 16
Source File: SystemCredentialsTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
    @ConfiguredWithCode("SystemCredentialsTest.yml")
    public void configure_system_credentials() throws Exception {
        Jenkins jenkins = Jenkins.get();

        List<UsernamePasswordCredentials> ups = CredentialsProvider.lookupCredentials(
                UsernamePasswordCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList()
        );
        assertThat(ups, hasSize(1));
        final UsernamePasswordCredentials up = ups.get(0);
        assertThat(up.getPassword().getPlainText(), equalTo("1234"));

        ConfiguratorRegistry registry = ConfiguratorRegistry.get();
        final ConfigurationContext context = new ConfigurationContext(registry);
        final CNode node = context.lookup(up.getClass()).describe(up, context);
        assertThat(node.asMapping().getScalarValue("password"), not(equals("1234")));


        List<CertificateCredentials> certs = CredentialsProvider.lookupCredentials(
                CertificateCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList()
        );
        assertThat(certs, hasSize(0));
//       TODO: add test for uploaded certificate
//        assertThat(certs.get(0).getPassword().getPlainText(), equalTo("ABCD"));

        List<BasicSSHUserPrivateKey> sshPrivateKeys = CredentialsProvider.lookupCredentials(
                BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList()
        );
        assertThat(sshPrivateKeys, hasSize(1));

        final BasicSSHUserPrivateKey ssh_with_passphrase = sshPrivateKeys.get(0);
        assertThat(ssh_with_passphrase.getPassphrase().getPlainText(), equalTo("ABCD"));

        final DirectEntryPrivateKeySource source = (DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
        assertThat(source.getPrivateKey().getPlainText(), equalTo("s3cr3t"));


        // credentials should not appear in plain text in log
        for (LogRecord logRecord : log.getRecords()) {
            assertThat(logRecord.getMessage(), not(containsString("1234")));
            assertThat(logRecord.getMessage(), not(containsString("ABCD")));
        }


    }
 
Example 17
Source File: GitLabPersonalAccessTokenCreator.java    From gitlab-branch-source-plugin with MIT License 4 votes vote down vote up
@SuppressWarnings("unused")
@RequirePOST
public FormValidation doCreateTokenByCredentials(
    @QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {

    Jenkins jenkins = Jenkins.get();
    jenkins.checkPermission(Jenkins.ADMINISTER);
    if (isEmpty(credentialsId)) {
        return FormValidation.error("Please specify credentials to create token");
    }

    StandardUsernamePasswordCredentials credentials = firstOrNull(lookupCredentials(
        StandardUsernamePasswordCredentials.class,
        jenkins,
        ACL.SYSTEM,
        fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build()),
        withId(credentialsId));

    if (credentials == null) {
        credentials = firstOrNull(lookupCredentials(
            StandardUsernamePasswordCredentials.class,
            jenkins,
            Jenkins.getAuthentication(),
            fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build()),
            withId(credentialsId));
    }

    if (Objects.isNull(credentials)) {
        return FormValidation.error("Can't create GitLab token, credentials are null");
    }
    try {
        String tokenName = UUID.randomUUID().toString();
        String token = AccessTokenUtils.createPersonalAccessToken(
            defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL),
            credentials.getUsername(),
            Secret.toString(credentials.getPassword()),
            tokenName,
            GL_PLUGIN_REQUIRED_SCOPE
        );
        tokenName = getShortName(tokenName);
        createCredentials(serverUrl, token, credentials.getUsername(), tokenName);
        return FormValidation.ok("Created credentials with id %s ", tokenName);
    } catch (GitLabApiException e) {
        return FormValidation.error(e, "Can't create GL token - %s", e.getMessage());
    }
}
 
Example 18
Source File: NoDelayProvisionerStrategy.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public NodeProvisioner.StrategyDecision apply(NodeProvisioner.StrategyState strategyState) {
    if (DISABLE_NODELAY_PROVISING) {
        LOGGER.log(Level.FINE, "Provisioning not complete, NoDelayProvisionerStrategy is disabled");
        return NodeProvisioner.StrategyDecision.CONSULT_REMAINING_STRATEGIES;
    }

    final Label label = strategyState.getLabel();

    LoadStatistics.LoadStatisticsSnapshot snapshot = strategyState.getSnapshot();
    int availableCapacity =
            snapshot.getAvailableExecutors()   // live executors
                    + snapshot.getConnectingExecutors()  // executors present but not yet connected
                    + strategyState.getPlannedCapacitySnapshot()     // capacity added by previous strategies from previous rounds
                    + strategyState.getAdditionalPlannedCapacity();  // capacity added by previous strategies _this round_
    int currentDemand = snapshot.getQueueLength();
    LOGGER.log(Level.FINE, "Available capacity={0}, currentDemand={1}",
            new Object[]{availableCapacity, currentDemand});
    if (availableCapacity < currentDemand) {
        List<Cloud> jenkinsClouds = new ArrayList<>(Jenkins.get().clouds);
        Collections.shuffle(jenkinsClouds);
        for (Cloud cloud : jenkinsClouds) {
            int workloadToProvision = currentDemand - availableCapacity;
            if (!(cloud instanceof KubernetesCloud)) continue;
            if (!cloud.canProvision(label)) continue;
            for (CloudProvisioningListener cl : CloudProvisioningListener.all()) {
                if (cl.canProvision(cloud, strategyState.getLabel(), workloadToProvision) != null) {
                    continue;
                }
            }
            Collection<NodeProvisioner.PlannedNode> plannedNodes = cloud.provision(label, workloadToProvision);
            LOGGER.log(Level.FINE, "Planned {0} new nodes", plannedNodes.size());
            fireOnStarted(cloud, strategyState.getLabel(), plannedNodes);
            strategyState.recordPendingLaunches(plannedNodes);
            availableCapacity += plannedNodes.size();
            LOGGER.log(Level.FINE, "After provisioning, available capacity={0}, currentDemand={1}", new Object[]{availableCapacity, currentDemand});
            break;
        }
    }
    if (availableCapacity >= currentDemand) {
        LOGGER.log(Level.FINE, "Provisioning completed");
        return NodeProvisioner.StrategyDecision.PROVISIONING_COMPLETED;
    } else {
        LOGGER.log(Level.FINE, "Provisioning not complete, consulting remaining strategies");
        return NodeProvisioner.StrategyDecision.CONSULT_REMAINING_STRATEGIES;
    }
}
 
Example 19
Source File: VaultHelper.java    From hashicorp-vault-plugin with MIT License 4 votes vote down vote up
@Override
public String call() throws IOException {
    Jenkins jenkins = Jenkins.get();

    String msg = String.format(
        "Retrieving vault secret path=%s key=%s engineVersion=%s",
        secretPath, secretKey, engineVersion);
    LOGGER.info(msg);

    GlobalVaultConfiguration globalConfig = GlobalConfiguration.all()
        .get(GlobalVaultConfiguration.class);

    if (globalConfig == null) {
        throw new IllegalStateException("Vault plugin has not been configured.");
    }

    ExtensionList<VaultBuildWrapper.DescriptorImpl> extensionList = jenkins
        .getExtensionList(VaultBuildWrapper.DescriptorImpl.class);
    VaultBuildWrapper.DescriptorImpl descriptor = extensionList.get(0);

    VaultConfiguration configuration = globalConfig.getConfiguration();

    if (descriptor == null || configuration == null) {
        throw new IllegalStateException("Vault plugin has not been configured.");
    }

    try {
        SslConfig sslConfig = new SslConfig()
            .verify(configuration.isSkipSslVerification())
            .build();

        VaultConfig vaultConfig = new VaultConfig()
            .address(configuration.getVaultUrl())
            .sslConfig(sslConfig)
            .engineVersion(engineVersion);

        if (isNotEmpty(configuration.getVaultNamespace())) {
            vaultConfig.nameSpace(configuration.getVaultNamespace());
        }

        if (isNotEmpty(configuration.getPrefixPath())) {
            vaultConfig.prefixPath(configuration.getPrefixPath());
        }

        VaultCredential vaultCredential = configuration.getVaultCredential();
        if (vaultCredential == null) vaultCredential = retrieveVaultCredentials(configuration.getVaultCredentialId());

        VaultAccessor vaultAccessor = new VaultAccessor(vaultConfig, vaultCredential);
        vaultAccessor.setMaxRetries(configuration.getMaxRetries());
        vaultAccessor.setRetryIntervalMilliseconds(configuration.getRetryIntervalMilliseconds());
        vaultAccessor.init();

        Map<String, String> values = vaultAccessor.read(secretPath, engineVersion).getData();

        if (!values.containsKey(secretKey)) {
            String message = String.format(
                "Key %s could not be found in path %s",
                secretKey, secretPath);
            throw new VaultPluginException(message);
        }

        return values.get(secretKey);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 20
Source File: FolderAuthorizationStrategyAPI.java    From folder-auth-plugin with MIT License 3 votes vote down vote up
/**
 * Checks the {@link AuthorizationStrategy} and runs the {@link Consumer} when it is an instance of
 * {@link FolderBasedAuthorizationStrategy}.
 * <p>
 * All attempts to access the {@link FolderBasedAuthorizationStrategy} must go through this method
 * for thread-safety.
 *
 * @param runner a function that consumes the current {@link FolderBasedAuthorizationStrategy} and returns a non
 *               null {@link FolderBasedAuthorizationStrategy} object. The object may be the same as the one
 *               consumed if no modification was needed.
 * @throws IllegalStateException when {@link Jenkins#getAuthorizationStrategy()} is not
 *                               {@link FolderBasedAuthorizationStrategy}
 */
private synchronized static void run(Function<FolderBasedAuthorizationStrategy, FolderBasedAuthorizationStrategy> runner) {
    Jenkins jenkins = Jenkins.get();
    AuthorizationStrategy strategy = jenkins.getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        FolderBasedAuthorizationStrategy newStrategy = runner.apply((FolderBasedAuthorizationStrategy) strategy);
        jenkins.setAuthorizationStrategy(newStrategy);
    } else {
        throw new IllegalStateException("FolderBasedAuthorizationStrategy is not the" + " current authorization strategy");
    }
}