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

The following examples show how to use jenkins.model.Jenkins#getInstance() . 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: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 7 votes vote down vote up
/**
 * Returns the proxy to be used when connecting to the given URI.
 */
private HttpHost getProxy(HttpUriRequest method) throws URIException {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxy = jenkins.proxy;
    if (proxy == null) {
        return null; // defensive check
    }

    Proxy p = proxy.createProxy(method.getURI().getHost());
    switch (p.type()) {
        case DIRECT:
            return null; // no proxy
        case HTTP:
            InetSocketAddress sa = (InetSocketAddress) p.address();
            return new HttpHost(sa.getHostName(), sa.getPort());
        case SOCKS:
        default:
            return null; // not supported yet
    }
}
 
Example 2
Source File: RepairnatorPostBuild.java    From repairnator with MIT License 6 votes vote down vote up
public void createGlobalEnvironmentVariables(String key, String value){

        Jenkins instance = Jenkins.getInstance();

        DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
        List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);

        EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
        EnvVars envVars = null;

        if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
            newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
            globalNodeProperties.add(newEnvVarsNodeProperty);
            envVars = newEnvVarsNodeProperty.getEnvVars();
        } else {
            envVars = envVarsNodePropertyList.get(0).getEnvVars();
        }
        envVars.put(key, value);
        try {
            instance.save();
        } catch(Exception e) {
            System.out.println("Failed to create env variable");
        }
    }
 
Example 3
Source File: FastNodeProvisionerStrategy.java    From docker-plugin with MIT License 5 votes vote down vote up
@Override
public void onEnterBuildable(Queue.BuildableItem item) {
    final Jenkins jenkins = Jenkins.getInstance();
    final Label label = item.getAssignedLabel();
    for (Cloud cloud : Jenkins.getInstance().clouds) {
        if (cloud instanceof DockerCloud && cloud.canProvision(label)) {
            final NodeProvisioner provisioner = (label == null
                    ? jenkins.unlabeledNodeProvisioner
                    : label.nodeProvisioner);
            provisioner.suggestReviewNow();
        }
    }
}
 
Example 4
Source File: EC2FleetCloud.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
private void removeNode(final String instanceId) {
    final Jenkins jenkins = Jenkins.getInstance();
    // If this node is dying, remove it from Jenkins
    final Node n = jenkins.getNode(instanceId);
    if (n != null) {
        try {
            jenkins.removeNode(n);
        } catch (final Exception ex) {
            throw new IllegalStateException(String.format("Error removing node %s", instanceId), ex);
        }
    }
}
 
Example 5
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Gets an image {@link Fingerprint} page.
 * @param req Stapler request
 * @param rsp Stapler response
 * @param id Image ID. Method supports full 64-char IDs only.
 * @throws IOException  Request processing error
 * @throws ServletException Servlet error
 */
public void doImage(StaplerRequest req, StaplerResponse rsp, 
        @QueryParameter(required = true) String id) 
        throws IOException, ServletException {  
    checkPermission(Jenkins.READ);
    Jenkins j = Jenkins.getInstance();
    if (j == null) {
        rsp.sendError(500, "Jenkins is not ready");
        return;
    }
    
    String fingerPrintHash = DockerTraceabilityHelper.getImageHash(id);
    rsp.sendRedirect2(j.getRootUrl()+"fingerprint/"+fingerPrintHash);
}
 
Example 6
Source File: DockerTemplateBase.java    From docker-plugin with MIT License 5 votes vote down vote up
/**
 * Calculates the value we use for the Docker label called
 * {@link DockerContainerLabelKeys#JENKINS_URL} that we put into every
 * container we make, so that we can recognize our own containers later.
 */
@Nonnull
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "It can be null during unit tests.")
static String getJenkinsUrlForContainerLabel() {
    final Jenkins jenkins = Jenkins.getInstance();
    // Note: While Jenkins.getInstance() claims to be @Nonnull it can
    // return null during unit-tests, so we need to null-proof here.
    final String rootUrl = jenkins == null ? null : jenkins.getRootUrl();
    return Util.fixNull(rootUrl);
}
 
Example 7
Source File: PipelineMetadataService.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private <T extends Describable<T>,D extends Descriptor<T>> void populateMetaSteps(List<Descriptor<?>> r, Class<T> c) {
    Jenkins j = Jenkins.getInstance();
    for (Descriptor<?> d : j.getDescriptorList(c)) {
        if (SimpleBuildStep.class.isAssignableFrom(d.clazz) && symbolForObject(d) != null) {
            r.add(d);
        } else if (SimpleBuildWrapper.class.isAssignableFrom(d.clazz) && symbolForObject(d) != null) {
            r.add(d);
        }
    }
}
 
Example 8
Source File: GitLabRequireOrganizationMembershipACL.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
private boolean currentUriPathEquals( String specificPath ) {
     String requestUri = requestURI();
     Jenkins jenkins = Jenkins.getInstance();
     if (jenkins != null && requestUri != null) {
String basePath = URI.create(jenkins.getRootUrl()).getPath();
         return URI.create(requestUri).getPath().equals(basePath + specificPath);
     } else {
         return false;
     }
 }
 
Example 9
Source File: DockerFingerprints.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
private static @Nonnull Fingerprint forDockerInstance(@CheckForNull Run<?,?> run, 
        @Nonnull String id, @CheckForNull String name, @Nonnull String prefix) throws IOException {
    final Jenkins j = Jenkins.getInstance();
    if (j == null) {
        throw new IOException("Jenkins instance is not ready");
    }
    final String imageName = prefix + (StringUtils.isNotBlank(name) ? name : id);
    return j.getFingerprintMap().getOrCreate(run, imageName, getFingerprintHash(id));
}
 
Example 10
Source File: DockerComputerAttachConnector.java    From docker-plugin with MIT License 5 votes vote down vote up
private static EnvVars calculateVariablesForVariableSubstitution(@Nonnull final String javaExe,
        @Nonnull final String jvmArgs, @Nonnull final String jarName, @Nonnull final String remoteFs,
        @Nonnull final String jenkinsUrl) throws IOException, InterruptedException {
    final EnvVars knownVariables = new EnvVars();
    final Jenkins j = Jenkins.getInstance();
    addEnvVars(knownVariables, j.getGlobalNodeProperties());
    for (final ArgumentVariables v : ArgumentVariables.values()) {
        // This switch statement MUST handle all possible
        // values of v.
        final String argValue;
        switch (v) {
            case JavaExe :
                argValue = javaExe;
                break;
            case JvmArgs :
                argValue = jvmArgs;
                break;
            case JarName :
                argValue = jarName;
                break;
            case RemoteFs :
                argValue = remoteFs;
                break;
            case JenkinsUrl :
                argValue = jenkinsUrl;
                break;
            default :
                final String msg = "Internal code error: Switch statement is missing \"case " + v.name()
                        + " : argValue = ... ; break;\" code.";
                // If this line throws an exception then it's because
                // someone has added a new variable to the enum without
                // adding code above to handle it.
                // The two have to be kept in step in order to
                // ensure that the help text stays in step.
                throw new RuntimeException(msg);
        }
        addEnvVar(knownVariables, v.getName(), argValue);
    }
    return knownVariables;
}
 
Example 11
Source File: WorkspaceCopyFileBuilder.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    listener.getLogger().println("Copying a " + fileName + " from " + jobName + "#" + buildNumber);
    
    Jenkins inst = Jenkins.getInstance();
    AbstractProject<?,?> item = inst.getItemByFullName(jobName, AbstractProject.class);
    if (item == null) {
        throw new AbortException("Cannot find a source job: " + jobName);
    }
    
    AbstractBuild<?,?> sourceBuild = item.getBuildByNumber(buildNumber);
    if (sourceBuild == null) {
        throw new AbortException("Cannot find a source build: " + jobName + "#" + buildNumber);
    }
    
    FilePath sourceWorkspace = sourceBuild.getWorkspace();
    if (sourceWorkspace == null) {
        throw new AbortException("Cannot get the source workspace from " + sourceBuild.getDisplayName());
    }
    
    FilePath workspace = build.getWorkspace();
    if (workspace == null) {
        throw new IOException("Cannot get the workspace of the build");
    }
    workspace.child(fileName).copyFrom(sourceWorkspace.child(fileName));
    
    return true;
}
 
Example 12
Source File: CacheWrapper.java    From jobcacher-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public List<CacheDescriptor> getCacheDescriptors() {
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        return jenkins.getDescriptorList(Cache.class);
    } else {
        return Collections.emptyList();
    }
}
 
Example 13
Source File: JenkinsAwareConnectionFactory.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
@Override
public HttpURLConnection openConnection(@Nonnull URL url) throws IOException, ClassCastException {
    Jenkins jenkins = Jenkins.getInstance();
    if(jenkins != null){
        ProxyConfiguration proxyConfig = jenkins.proxy;
        if (proxyConfig != null) {
            return (HttpURLConnection) url.openConnection(proxyConfig.createProxy(url.getHost()));
        }
    }
    return (HttpURLConnection) url.openConnection();
}
 
Example 14
Source File: GlobalItemStorage.java    From jobcacher-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public List<ItemStorageDescriptor> getStorageDescriptors() {
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        return jenkins.getDescriptorList(ItemStorage.class);
    } else {
        return Collections.emptyList();
    }
}
 
Example 15
Source File: DynamicProjectRepositoryTest.java    From DotCi with MIT License 5 votes vote down vote up
@Test
@LocalData
public void should_delete_a_project() {
    assertEquals(1L, repo.getDatastore().createQuery(DynamicProject.class).countAll());
    DynamicProject project = spy(repo.getProjectById(new ObjectId("5451e5ee30047b534b7bd50b")));
    OrganizationContainer parent = new OrganizationContainer(Jenkins.getInstance(), "groupon");
    doReturn(parent).when(project).getParent();
    repo.delete(project);
    assertEquals(0L, repo.getDatastore().createQuery(DynamicProject.class).countAll());
}
 
Example 16
Source File: SwarmNode.java    From docker-swarm-plugin with MIT License 4 votes vote down vote up
public Object[] getCurrentBuilds() {
    final Jenkins jenkins = Jenkins.getInstance();
    return getTasksWithRuns(jenkins).map(task -> getComputer(jenkins, task).getCurrentBuild()).toArray();
}
 
Example 17
Source File: BlueI18n.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@CheckForNull
static PluginWrapper getPlugin(String pluginName) {
    Jenkins jenkins = Jenkins.getInstance();
    return jenkins.getPluginManager().getPlugin(pluginName);
}
 
Example 18
Source File: BlueOceanConfigStatePreloader.java    From blueocean-plugin with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getStateJson() {
    StringWriter writer = new StringWriter();
    Jenkins jenkins = Jenkins.getInstance();
    VersionNumber versionNumber = Jenkins.getVersion();
    String version = versionNumber != null ? versionNumber.toString() : Jenkins.VERSION;

    AuthorizationStrategy authorizationStrategy = jenkins.getAuthorizationStrategy();
    boolean allowAnonymousRead = true;
    if(authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy){
        allowAnonymousRead = ((FullControlOnceLoggedInAuthorizationStrategy) authorizationStrategy).isAllowAnonymousRead();
    }

    String jwtTokenEndpointHostUrl = Jenkins.getInstance().getRootUrl();
    JwtTokenServiceEndpoint jwtTokenServiceEndpoint = JwtTokenServiceEndpoint.first();
    if(jwtTokenServiceEndpoint != null){
        jwtTokenEndpointHostUrl = jwtTokenServiceEndpoint.getHostUrl();
    }
    addFeatures(new JSONBuilder(writer)
        .object()
            .key("version").value(getBlueOceanPluginVersion())
            .key("jenkinsConfig")
            .object()
                .key("analytics").value(Analytics.isAnalyticsEnabled())
                .key("version").value(version)
                .key("security")
                .object()
                    .key("enabled").value(jenkins.isUseSecurity())
                    .key("loginUrl").value(jenkins.getSecurityRealm() == SecurityRealm.NO_AUTHENTICATION ? null : jenkins.getSecurityRealm().getLoginUrl())
                    .key("authorizationStrategy").object()
                        .key("allowAnonymousRead").value(allowAnonymousRead)
                    .endObject()
                    .key("enableJWT").value(BlueOceanConfigProperties.BLUEOCEAN_FEATURE_JWT_AUTHENTICATION)
                    .key("jwtServiceHostUrl").value(jwtTokenEndpointHostUrl)
                .endObject()
            .endObject()
            ) // addFeatures here
        .endObject();

    return writer.toString();
}
 
Example 19
Source File: FreestyleTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Override
        public Boolean call() throws Throwable {
            final Jenkins jenkins = Jenkins.getInstance();

            String logName = "com.github.kostyasha.yad";
            final LogRecorder logRecorder = new LogRecorder(logName);
            logRecorder.targets.add(new LogRecorder.Target("com.github.kostyasha.yad", Level.ALL));
            jenkins.getLog().logRecorders.put("logName", logRecorder);
            logRecorder.save();

            // prepare jenkins global (url, cred)
            JenkinsLocationConfiguration.get().setUrl(String.format("http://%s:%d", dockerUri.getHost(), jenkinsPort));

            SystemCredentialsProvider.getInstance().getCredentials().add(dockerServerCredentials);

            //verify doTestConnection
            final DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptor(DockerConnector.class);
            checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
                    dockerServerCredentials.getId(), connectorType, 10 * 1000, 11 * 1000));
//           checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
//                    dockerServerCredentials.getId(), JERSEY, 10 * 1000, 11 * 1000));
//           checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
//                    dockerServerCredentials.getId(), OKHTTP, 10 * 1000, 11 * 1000));

            // prepare Docker Cloud
            final DockerConnector dockerConnector = new DockerConnector(dockerUri.toString());
            dockerConnector.setCredentialsId(dockerServerCredentials.getId());
            dockerConnector.setConnectTimeout(10 * 1000);
            dockerConnector.setReadTimeout(0);
            dockerConnector.setConnectorType(connectorType);
            dockerConnector.testConnection();

            //launcher
            final DockerComputerJNLPLauncher launcher = new DockerComputerJNLPLauncher();
            launcher.setNoCertificateCheck(true);
            launcher.setJvmOpts("-XX:-PrintClassHistogram");
            final DockerPullImage pullImage = new DockerPullImage();
            pullImage.setPullStrategy(PULL_LATEST);

            //remove
            final DockerRemoveContainer removeContainer = new DockerRemoveContainer();
            removeContainer.setRemoveVolumes(true);
            removeContainer.setForce(true);

            //lifecycle
            final DockerContainerLifecycle containerLifecycle = new DockerContainerLifecycle();
            containerLifecycle.setImage(slaveImage);
            containerLifecycle.setPullImage(pullImage);
            containerLifecycle.setRemoveContainer(removeContainer);

            //template
            final Entry entry = new Entry("super-key", TEST_VALUE);
            final EnvironmentVariablesNodeProperty nodeProperty = new EnvironmentVariablesNodeProperty(entry);

            final ArrayList<NodeProperty<?>> nodeProperties = new ArrayList<>();
            nodeProperties.add(nodeProperty);
            nodeProperties.add(new DockerNodeProperty(CONTAINER_ID, CLOUD_ID, DOCKER_HOST));


            final DockerSlaveTemplate slaveTemplate = new DockerSlaveTemplate();
            slaveTemplate.setMaxCapacity(4);
            slaveTemplate.setLabelString(DOCKER_CLOUD_LABEL);
            slaveTemplate.setLauncher(launcher);
            slaveTemplate.setMode(Node.Mode.EXCLUSIVE);
            slaveTemplate.setRetentionStrategy(new DockerOnceRetentionStrategy(10));
            slaveTemplate.setDockerContainerLifecycle(containerLifecycle);
            slaveTemplate.setNodeProperties(nodeProperties);

            final List<DockerSlaveTemplate> templates = new ArrayList<>();
            templates.add(slaveTemplate);

            final DockerCloud dockerCloud = new DockerCloud(
                    DOCKER_CLOUD_NAME,
                    templates,
                    3,
                    dockerConnector
            );
            jenkins.clouds.add(dockerCloud);
            jenkins.save(); // either xmls a half broken

            return true;
        }
 
Example 20
Source File: DockerTraceabilityHelper.java    From docker-traceability-plugin with MIT License 3 votes vote down vote up
/**
 * Get a fingerprint by the specified container ID.
 * This method allows to handle exception in the logic.
 * Use {@link #of(java.lang.String)} to get a default behavior.
 * @param containerId Full 64-symbol container id. Short forms are not supported.
 * @return Fingerprint. null if it does not exist (or if Jenkins has not been initialized yet)
 * @throws IOException Fingerprint loading error
 */
public static @CheckForNull Fingerprint ofValidated(@Nonnull String containerId) throws IOException {
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        return null;
    }
    return jenkins.getFingerprintMap().get(getContainerHash(containerId));
}