jenkins.model.JenkinsLocationConfiguration Java Examples

The following examples show how to use jenkins.model.JenkinsLocationConfiguration. 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: KafkaComputerLauncher.java    From remoting-kafka-plugin with MIT License 6 votes vote down vote up
/**
 * Returns Jenkins URL to be used by agents launched by this cloud. Always ends with a trailing slash.
 *
 * Uses in order:
 * * Cloud configuration (if launched by Cloud)
 * * Jenkins Location URL
 */
private URL retrieveJenkinsURL(Computer computer) throws RemotingKafkaConfigurationException {
    JenkinsLocationConfiguration locationConfiguration = JenkinsLocationConfiguration.get();
    String cloudJenkinsUrl = null;
    if (computer instanceof KafkaCloudComputer) {
        KafkaCloudSlave agent = (KafkaCloudSlave) computer.getNode();
        if (agent == null) {
            LOGGER.warning("Cannot find node for computer " + computer.getName());
        } else {
            cloudJenkinsUrl = agent.getCloud().getJenkinsUrl();
        }
    }

    String url = StringUtils.defaultIfBlank(cloudJenkinsUrl, locationConfiguration.getUrl());
    try {
        if (url == null)
            throw new RemotingKafkaConfigurationException(Messages.KafkaComputerLauncher_MalformedJenkinsURL());
        return new URL(url);
    } catch (MalformedURLException e) {
        throw new RemotingKafkaConfigurationException(Messages.KafkaComputerLauncher_MalformedJenkinsURL());
    }
}
 
Example #2
Source File: KubernetesTestUtil.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
public static void setupHost() throws Exception {
    // Agents running in Kubernetes (minikube) need to connect to this server, so localhost does not work
    URL url = new URL(JenkinsLocationConfiguration.get().getUrl());
    String hostAddress = System.getProperty("jenkins.host.address");
    if (org.apache.commons.lang3.StringUtils.isBlank(hostAddress)) {
        hostAddress = InetAddress.getLocalHost().getHostAddress();
    }
    System.err.println("Calling home to address: " + hostAddress);
    URL nonLocalhostUrl = new URL(url.getProtocol(), hostAddress, url.getPort(),
            url.getFile());
    // TODO better to set KUBERNETES_JENKINS_URL
    JenkinsLocationConfiguration.get().setUrl(nonLocalhostUrl.toString());

    Integer slaveAgentPort = Integer.getInteger("slaveAgentPort");
    if (slaveAgentPort != null) {
        Jenkins.get().setSlaveAgentPort(slaveAgentPort);
    }
}
 
Example #3
Source File: JmhBenchmarkState.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
private void launchInstance() throws Exception {
    ImmutablePair<Server, ServletContext> results = JenkinsRule._createWebServer(contextPath, localPort::setValue,
            getClass().getClassLoader(), localPort.getValue(), JenkinsRule::_configureUserRealm);

    server = results.left;
    ServletContext webServer = results.right;

    jenkins = new Hudson(temporaryDirectoryAllocator.allocate(), webServer);
    JenkinsRule._configureJenkinsForTest(jenkins);
    JenkinsRule._configureUpdateCenter(jenkins);
    jenkins.getActions().add(this);

    String url = Objects.requireNonNull(getJenkinsURL()).toString();
    Objects.requireNonNull(JenkinsLocationConfiguration.get()).setUrl(url);
    LOGGER.log(Level.INFO, "Running on {0}", url);
}
 
Example #4
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Returns Jenkins URL to be used by agents launched by this cloud. Always ends with a trailing slash.
 *
 * Uses in order:
 * * cloud configuration
 * * environment variable <b>KUBERNETES_JENKINS_URL</b>
 * * Jenkins Location URL
 *
 * @return Jenkins URL to be used by agents launched by this cloud. Always ends with a trailing slash.
 *         Null if no Jenkins URL could be computed.
 */
@CheckForNull
public String getJenkinsUrlOrNull() {
    JenkinsLocationConfiguration locationConfiguration = JenkinsLocationConfiguration.get();
    String url = StringUtils.defaultIfBlank(
            getJenkinsUrl(),
            StringUtils.defaultIfBlank(
                    System.getProperty("KUBERNETES_JENKINS_URL",System.getenv("KUBERNETES_JENKINS_URL")),
                    locationConfiguration.getUrl()
            )
    );
    if (url == null) {
        return null;
    }
    url = url.endsWith("/") ? url : url + "/";
    return url;
}
 
Example #5
Source File: ECSCloud.java    From amazon-ecs-plugin with MIT License 5 votes vote down vote up
@DataBoundSetter
public void setJenkinsUrl(String jenkinsUrl) {
    if(StringUtils.isNotBlank(jenkinsUrl)) {
        this.jenkinsUrl = jenkinsUrl;
    } else {
        JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get();
        if (config != null) {
            this.jenkinsUrl = config.getUrl();
        }
    }
}
 
Example #6
Source File: GitLabHookCreatorParameterizedTest.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void hookUrlFromCustomRootUrl() {
    Arrays.asList("http://", "https://").forEach(
        proto -> {
            String expected = proto + jenkinsUrl + expectedPath;
            JenkinsLocationConfiguration.get().setUrl("http://whatever");
            GitLabServer server = new GitLabServer("https://gitlab.com", "GitLab", null);
            server.setHooksRootUrl(proto + jenkinsUrl);
            String hookUrl = GitLabHookCreator.getHookUrl(server, hookType);
            GitLabHookCreator.checkURL(hookUrl);
            assertThat(hookUrl.replaceAll(proto, ""), not(containsString("//")));
            assertThat(hookUrl, is(expected));
        });
}
 
Example #7
Source File: SetCommitStatusExecution.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
protected Void run() throws Exception {
    // Figure out which GitHub repository to send the request to
    checkArgument(nonNull(config.getState()), "Missing required parameter 'state'");

    GHRepository repository = resolveRepository();
    String statusContext = resolveContext();

    final GitHubPRCause cause = run.getCause(GitHubPRCause.class);
    if (isNull(cause)) {
        throw new AbortException(FUNC_NAME + " requires run to be triggered by GitHub Pull Request");
    }

    // Update the commit status
    log.getLogger().printf("Setting pull request status %s to %s with message: %s%n",
            statusContext,
            config.getState(),
            config.getMessage()
    );
    String buildUrl = null;
    final JenkinsLocationConfiguration globalConfig = JenkinsLocationConfiguration.get();
    if (nonNull(globalConfig)) {
        buildUrl = globalConfig.getUrl();
    }
    if (isEmpty(buildUrl)) {
        log.error("Jenkins Location is not configured in system settings. Cannot create a 'details' link.");
        buildUrl = null;
    } else {
        buildUrl += run.getUrl();
    }

    repository.createCommitStatus(cause.getHeadSha(),
            config.getState(),
            buildUrl,
            config.getMessage(),
            statusContext);
    return null;
}
 
Example #8
Source File: KubernetesCloudTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void getJenkinsUrlOrNull_NoJenkinsUrl() {
    JenkinsLocationConfiguration.get().setUrl(null);
    KubernetesCloud cloud = new KubernetesCloud("name");
    String url = cloud.getJenkinsUrlOrNull();
    assertNull(url);
}
 
Example #9
Source File: KubernetesCloudTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void getJenkinsUrlOrDie_NoJenkinsUrl() {
    JenkinsLocationConfiguration.get().setUrl(null);
    KubernetesCloud cloud = new KubernetesCloud("name");
    String url = cloud.getJenkinsUrlOrDie();
    fail("Should have thrown IllegalStateException at this point but got " + url + " instead.");
}
 
Example #10
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused") // used by jelly
public FormValidation doCheckDirectConnection(@QueryParameter boolean value, @QueryParameter String jenkinsUrl, @QueryParameter boolean webSocket) throws IOException, ServletException {
    int slaveAgentPort = Jenkins.get().getSlaveAgentPort();
    if (slaveAgentPort == -1 && !webSocket) {
        return FormValidation.warning("'TCP port for inbound agents' is disabled in Global Security settings. Connecting Kubernetes agents will not work without this or WebSocket mode!");
    }

    if(value) {
        if (webSocket) {
            return FormValidation.error("Direct connection and WebSocket mode are mutually exclusive");
        }
        if(!isEmpty(jenkinsUrl)) return FormValidation.warning("No need to configure Jenkins URL when direct connection is enabled");

        if(slaveAgentPort == 0) return FormValidation.warning(
                "A random 'TCP port for inbound agents' is configured in Global Security settings. In 'direct connection' mode agents will not be able to reconnect to a restarted master with random port!");
    } else {
        if (isEmpty(jenkinsUrl)) {
            String url = StringUtils.defaultIfBlank(System.getProperty("KUBERNETES_JENKINS_URL", System.getenv("KUBERNETES_JENKINS_URL")), JenkinsLocationConfiguration.get().getUrl());
            if (url != null) {
                return FormValidation.ok("Will connect using " + url);
            } else {
                return FormValidation.warning("Configure either Direct Connection or Jenkins URL");
            }
        }
    }
    return FormValidation.ok();
}
 
Example #11
Source File: MattermostNotifier.java    From jenkins-mattermost-plugin with MIT License 5 votes vote down vote up
public String getBuildServerUrl() {
  if (buildServerUrl == null || buildServerUrl.equals("")) {
    // Note: current code should no longer use "new JenkinsLocationConfiguration()"
    // as only one instance per runtime is really supported by the current core.
    JenkinsLocationConfiguration jenkinsConfig = JenkinsLocationConfiguration.get();
    return jenkinsConfig.getUrl();
  } else {
    return buildServerUrl;
  }
}
 
Example #12
Source File: MattermostNotifier.java    From jenkins-mattermost-plugin with MIT License 5 votes vote down vote up
public String getBuildServerUrl() {
  if (buildServerUrl == null || buildServerUrl.equals("")) {
    // Note: current code should no longer use "new JenkinsLocationConfiguration()"
    // as only one instance per runtime is really supported by the current core.
    JenkinsLocationConfiguration jenkinsConfig = JenkinsLocationConfiguration.get();
    return jenkinsConfig.getUrl();
  } else {
    return buildServerUrl;
  }
}
 
Example #13
Source File: OpenShiftItemListener.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
private void updateRootURLConfig() {
    if (Jenkins.getInstance().getRootUrl() != null
            && JenkinsLocationConfiguration.get().getUrl() == null) {
        JenkinsLocationConfiguration.get().setUrl(
                Jenkins.getInstance().getRootUrl());
    }
}
 
Example #14
Source File: KubernetesPipelineTest.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
private void configureCloud(JenkinsRuleNonLocalhost r) throws Exception {
    // Slaves running in Kubernetes (minikube) need to connect to this server, so localhost does not work
    URL url = r.getURL();
    URL nonLocalhostUrl = new URL(url.getProtocol(), InetAddress.getLocalHost().getHostAddress(), url.getPort(),
            url.getFile());
    JenkinsLocationConfiguration.get().setUrl(nonLocalhostUrl.toString());

    r.jenkins.clouds.add(cloud);
}
 
Example #15
Source File: BitbucketPipelineCreateRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
@Override
protected SCMSource createSource(@Nonnull MultiBranchProject project, @Nonnull BlueScmConfig scmConfig) {
    /* scmConfig.uri presence is already validated in {@link #validate} but lets check just in case */
    if(StringUtils.isBlank(scmConfig.getUri())){
        throw new ServiceException.BadRequestException("scmConfig.uri must be present");
    }

    Set<ChangeRequestCheckoutStrategy> strategies = new HashSet<>();
    strategies.add(ChangeRequestCheckoutStrategy.MERGE);

    BitbucketSCMSource bitbucketSCMSource = new BitbucketSCMSourceBuilder(null, scmConfig.getUri(), computeCredentialId(scmConfig),
            (String)scmConfig.getConfig().get("repoOwner"),
            (String)scmConfig.getConfig().get("repository"))
            .withTrait(new BranchDiscoveryTrait(true, true)) //take all branches
            .withTrait(new ForkPullRequestDiscoveryTrait(strategies, new ForkPullRequestDiscoveryTrait.TrustTeamForks()))
            .withTrait(new OriginPullRequestDiscoveryTrait(strategies))
            .withTrait(new CleanBeforeCheckoutTrait())
            .withTrait(new CleanAfterCheckoutTrait())
            .withTrait(new LocalBranchTrait())
            .build();

    //Setup Jenkins root url, if not set bitbucket cloud notification will fail
    JenkinsLocationConfiguration jenkinsLocationConfiguration = JenkinsLocationConfiguration.get();
    if(jenkinsLocationConfiguration != null) {
        String url = jenkinsLocationConfiguration.getUrl();
        if (url == null) {
            url = Jenkins.getInstance().getRootUrl();
            if (url != null) {
                jenkinsLocationConfiguration.setUrl(url);
            }
        }
    }
    return bitbucketSCMSource;
}
 
Example #16
Source File: UseRecipesWithJenkinsRuleTest.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
@Test public void rightURL() throws Exception {
    assertEquals(rule.getURL(), new URL(JenkinsLocationConfiguration.get().getUrl()));
}
 
Example #17
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
@Override
protected void  setUp() throws Exception {
    if (Thread.interrupted()) { // JENKINS-30395
        LOGGER.warning("was interrupted before start");
    }

    if(Functions.isWindows()) {
        // JENKINS-4409.
        // URLConnection caches handles to jar files by default,
        // and it prevents delete temporary directories on Windows.
        // Disables caching here.
        // Though defaultUseCache is a static field,
        // its setter and getter are provided as instance methods.
        URLConnection aConnection = new File(".").toURI().toURL().openConnection();
        origDefaultUseCache = aConnection.getDefaultUseCaches();
        aConnection.setDefaultUseCaches(false);
    }
    
    env.pin();
    recipe();
    for (Runner r : recipes) {
        if (r instanceof WithoutJenkins.RunnerImpl)
            return; // no setup
    }
    AbstractProject.WORKSPACE.toString();
    User.clear();

    // just in case tearDown failed in the middle, make sure to really clean them up so that there's no left-over from earlier tests
    ExtensionList.clearLegacyInstances();
    DescriptorExtensionList.clearLegacyInstances();

    try {
        jenkins = hudson = newHudson();
    } catch (Exception e) {
        // if Jenkins instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up.
        Field f = Jenkins.class.getDeclaredField("theInstance");
        f.setAccessible(true);
        f.set(null,null);
        throw e;
    }
    jenkins.setNoUsageStatistics(true); // collecting usage stats from tests are pointless.
    
    jenkins.setCrumbIssuer(new TestCrumbIssuer());

    jenkins.servletContext.setAttribute("app", jenkins);
    jenkins.servletContext.setAttribute("version","?");
    WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.servletContext));
    JenkinsLocationConfiguration.get().setUrl(getURL().toString());

    // set a default JDK to be the one that the harness is using.
    jenkins.getJDKs().add(new JDK("default",System.getProperty("java.home")));

    configureUpdateCenter();

    // expose the test instance as a part of URL tree.
    // this allows tests to use a part of the URL space for itself.
    jenkins.getActions().add(this);

    // cause all the descriptors to reload.
    // ideally we'd like to reset them to properly emulate the behavior, but that's not possible.
    for( Descriptor d : jenkins.getExtensionList(Descriptor.class) )
        d.load();

    // allow the test class to inject Jenkins components
    jenkins.lookup(Injector.class).injectMembers(this);

    setUpTimeout();
}
 
Example #18
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Override to set up your specific external resource.
 * @throws Throwable if setup fails (which will disable {@code after}
 */
public void before() throws Throwable {
    for (Handler h : Logger.getLogger("").getHandlers()) {
        if (h instanceof ConsoleHandler) {
            ((ConsoleHandler) h).setFormatter(new DeltaSupportLogFormatter());
        }
    }

    if (Thread.interrupted()) { // JENKINS-30395
        LOGGER.warning("was interrupted before start");
    }

    if(Functions.isWindows()) {
        // JENKINS-4409.
        // URLConnection caches handles to jar files by default,
        // and it prevents delete temporary directories on Windows.
        // Disables caching here.
        // Though defaultUseCache is a static field,
        // its setter and getter are provided as instance methods.
        URLConnection aConnection = new File(".").toURI().toURL().openConnection();
        origDefaultUseCache = aConnection.getDefaultUseCaches();
        aConnection.setDefaultUseCaches(false);
    }
    
    // Not ideal (https://github.com/junit-team/junit/issues/116) but basically works.
    if (Boolean.getBoolean("ignore.random.failures")) {
        RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
        if (rf != null) {
            throw new AssumptionViolatedException("Known to randomly fail: " + rf.value());
        }
    }

    env = new TestEnvironment(testDescription);
    env.pin();
    recipe();
    AbstractProject.WORKSPACE.toString();
    User.clear();

    try {
        Field theInstance = Jenkins.class.getDeclaredField("theInstance");
        theInstance.setAccessible(true);
        if (theInstance.get(null) != null) {
            LOGGER.warning("Jenkins.theInstance was not cleared by a previous test, doing that now");
            theInstance.set(null, null);
        }
    } catch (Exception x) {
        LOGGER.log(Level.WARNING, null, x);
    }

    try {
        jenkins = hudson = newHudson();
        // If the initialization graph is corrupted, we cannot expect that Jenkins is in the good shape.
        // Likely it is an issue in @Initializer() definitions (see JENKINS-37759).
        // So we just fail the test.
        if (jenkins.getInitLevel() != InitMilestone.COMPLETED) {
            throw new Exception("Jenkins initialization has not reached the COMPLETED initialization stage. Current state is " + jenkins.getInitLevel() +
                    ". Likely there is an issue with the Initialization task graph (e.g. usage of @Initializer(after = InitMilestone.COMPLETED)). See JENKINS-37759 for more info");
        }
    } catch (Exception e) {
        // if Hudson instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up.
        Field f = Jenkins.class.getDeclaredField("theInstance");
        f.setAccessible(true);
        f.set(null,null);
        throw e;
    }

    jenkins.setCrumbIssuer(new TestCrumbIssuer());  // TODO: Move to _configureJenkinsForTest after JENKINS-55240
    _configureJenkinsForTest(jenkins);
    configureUpdateCenter();

    // expose the test instance as a part of URL tree.
    // this allows tests to use a part of the URL space for itself.
    jenkins.getActions().add(this);

    JenkinsLocationConfiguration.get().setUrl(getURL().toString());
}
 
Example #19
Source File: KubernetesCloudTest.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void getJenkinsUrlOrDie_UrlInLocation() {
    JenkinsLocationConfiguration.get().setUrl("http://mylocation");
    KubernetesCloud cloud = new KubernetesCloud("name");
    assertEquals("http://mylocation/", cloud.getJenkinsUrlOrDie());
}
 
Example #20
Source File: KubernetesCloudTest.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void getJenkinsUrlOrNull_UrlInLocation() {
    JenkinsLocationConfiguration.get().setUrl("http://mylocation");
    KubernetesCloud cloud = new KubernetesCloud("name");
    assertEquals("http://mylocation/", cloud.getJenkinsUrlOrNull());
}
 
Example #21
Source File: UserNameNginxProxyAuthTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Override
        public Boolean call() throws Throwable {
            final String dockerLabel = "docker-label";
            final Jenkins jenkins = Jenkins.getActiveInstance();

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

            final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(
                    CredentialsScope.GLOBAL,
                    null,
                    "description",
                    "docker",
                    "docker"
            );

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

            // prepare Docker Cloud
            final DockerConnector dockerConnector = new DockerConnector(
                    String.format("tcp://%s:%d", dockerUri.getHost(), CONTAINER_PORT)
            );
            dockerConnector.setConnectTimeout(50 * 1000);
            dockerConnector.setConnectorType(JERSEY);
            dockerConnector.setCredentialsId(credentials.getId());
            dockerConnector.testConnection();
//            final Version version = dockerConnector.getClient().versionCmd().exec();
//            LOG.info("Version {}", version);

            final DockerComputerJNLPLauncher launcher = new DockerComputerJNLPLauncher();
            final DockerPullImage pullImage = new DockerPullImage();
            pullImage.setPullStrategy(PULL_ALWAYS);

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

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

            final DockerSlaveTemplate slaveTemplate = new DockerSlaveTemplate();
            slaveTemplate.setLabelString(dockerLabel);
            slaveTemplate.setLauncher(launcher);
            slaveTemplate.setMode(Node.Mode.EXCLUSIVE);
            slaveTemplate.setRetentionStrategy(new DockerOnceRetentionStrategy(10));
            slaveTemplate.setDockerContainerLifecycle(containerLifecycle);

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

            final DockerCloud dockerCloud = new DockerCloud(
                    "docker",
                    templates,
                    3,
                    dockerConnector
            );

            jenkins.clouds.add(dockerCloud);
            jenkins.save(); // either xmls a half broken

            return true;
        }
 
Example #22
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 #23
Source File: GiteaWebhookListener.java    From gitea-plugin with MIT License 4 votes vote down vote up
public static void register(SCMSourceOwner owner, GiteaSCMSource source,
                            WebhookRegistration mode, String credentialsId) {
    StandardCredentials credentials;
    String serverUrl = source.getServerUrl();
    switch (mode) {
        case SYSTEM:
            GiteaServer server = GiteaServers.get().findServer(serverUrl);
            if (server == null || !server.isManageHooks()) {
                return;
            }
            credentials = server.credentials();
            break;
        case ITEM:
            credentials = source.credentials();
            break;
        case DISABLE:
        default:
            return;
    }
    if (credentials == null) {
        return;
    }
    JenkinsLocationConfiguration locationConfiguration = JenkinsLocationConfiguration.get();
    String rootUrl = locationConfiguration.getUrl();
    if (StringUtils.isBlank(rootUrl) || rootUrl.startsWith("http://localhost:")) {
        // Jenkins URL not configured, can't register hooks
        LOGGER.log(Level.FINE, "JENKINS_URL is not defined. Cannot register a WebHook.");
        return;
    }
    String hookUrl =
            UriTemplate.buildFromTemplate(rootUrl).literal("gitea-webhook").literal("/post").build().expand();
    try (GiteaConnection c = connect(serverUrl, credentials)) {
        GiteaRepository repo = c.fetchRepository(source.getRepoOwner(), source.getRepository());
        if (repo == null) {
            return;
        }
        List<GiteaHook> hooks = c.fetchHooks(repo);
        GiteaHook hook = null;
        for (GiteaHook h : hooks) {
            if (hookUrl.equals(h.getConfig().getUrl())) {
                if (hook == null
                        && h.getType() == GiteaHookType.GITEA
                        && h.getConfig().getContentType() == GiteaPayloadType.JSON
                        && h.isActive()
                        && EnumSet.allOf(GiteaEventType.class).equals(h.getEvents())) {
                    hook = h;
                } else {
                    c.deleteHook(repo, h);
                }
            }
        }
        if (hook == null) {
            hook = new GiteaHook();
            GiteaHook.Configuration configuration = new GiteaHook.Configuration();
            configuration.setContentType(GiteaPayloadType.JSON);
            configuration.setUrl(hookUrl);
            hook.setType(GiteaHookType.GITEA);
            hook.setConfig(configuration);
            hook.setEvents(EnumSet.allOf(GiteaEventType.class));
            hook.setActive(true);
            c.createHook(repo, hook);
        }
    } catch (IOException | InterruptedException e) {
        LOGGER.log(Level.WARNING,
                "Could not manage repository hooks for " + source.getRepoOwner() + "/" + source.getRepository()
                        + " on " + serverUrl, e);
    }

}
 
Example #24
Source File: GiteaWebhookListener.java    From gitea-plugin with MIT License 4 votes vote down vote up
public static void register(SCMNavigatorOwner owner, GiteaSCMNavigator navigator,
                            WebhookRegistration mode, String credentialsId) {
    StandardCredentials credentials;
    String serverUrl = navigator.getServerUrl();
    switch (mode) {
        case SYSTEM:
            GiteaServer server = GiteaServers.get().findServer(serverUrl);
            if (server == null || !server.isManageHooks()) {
                return;
            }
            credentials = server.credentials();
            break;
        case ITEM:
            credentials = navigator.credentials(owner);
            break;
        case DISABLE:
        default:
            return;
    }
    if (credentials == null) {
        return;
    }
    JenkinsLocationConfiguration locationConfiguration = JenkinsLocationConfiguration.get();
    String rootUrl = locationConfiguration.getUrl();
    if (StringUtils.isBlank(rootUrl) || rootUrl.startsWith("http://localhost:")) {
        // Jenkins URL not configured, can't register hooks
        LOGGER.log(Level.FINE, "JENKINS_URL is not defined. Cannot register a WebHook.");
        return;
    }
    String hookUrl =
            UriTemplate.buildFromTemplate(rootUrl).literal("gitea-webhook").literal("/post").build().expand();
    try (GiteaConnection c = connect(serverUrl, credentials)) {
        GiteaUser user = c.fetchUser(navigator.getRepoOwner());
        if (StringUtils.isNotBlank(user.getEmail())) {
            // it's a user not an org
            return;
        }
        GiteaOrganization org = c.fetchOrganization(navigator.getRepoOwner());
        if (org == null) {
            return;
        }
        List<GiteaHook> hooks = c.fetchHooks(org);
        GiteaHook hook = null;
        for (GiteaHook h : hooks) {
            if (hookUrl.equals(h.getConfig().getUrl())) {
                if (hook == null
                        && h.getType() == GiteaHookType.GITEA
                        && h.getConfig().getContentType() == GiteaPayloadType.JSON
                        && h.isActive()
                        && EnumSet.allOf(GiteaEventType.class).equals(h.getEvents())) {
                    hook = h;
                } else {
                    c.deleteHook(org, h);
                }
            }
        }
        if (hook == null) {
            hook = new GiteaHook();
            GiteaHook.Configuration configuration = new GiteaHook.Configuration();
            configuration.setContentType(GiteaPayloadType.JSON);
            configuration.setUrl(hookUrl);
            hook.setType(GiteaHookType.GITEA);
            hook.setConfig(configuration);
            hook.setEvents(EnumSet.allOf(GiteaEventType.class));
            hook.setActive(true);
            c.createHook(org, hook);
        }
    } catch (IOException | InterruptedException e) {
        LOGGER.log(Level.WARNING,
                "Could not manage organization hooks for " + navigator.getRepoOwner() + " on " + serverUrl, e);
    }
}