com.openshift.restclient.ClientBuilder Java Examples

The following examples show how to use com.openshift.restclient.ClientBuilder. 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: ClientService.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private IClient openshiftClient() throws IOException {
    String kubeHost = serviceHost("kubernetes");
    int kubePort = servicePort("kubernetes");

    Path tokenFile = Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/token");
    String scheme = "http";
    String token = null;
    if (Files.exists(tokenFile)) {
        token = new String(Files.readAllBytes(tokenFile));
        scheme = "https";
    }

    return new ClientBuilder(scheme + "://" + kubeHost + ":" + kubePort)
            .usingToken(token)
            .build();
}
 
Example #2
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
default IClient getClient(TaskListener listener, String displayName,
        Map<String, String> overrides, String token) {
    Auth auth = getAuth();
    ClientBuilder cb = new ClientBuilder(getApiURL(overrides))
            .sslCertificateCallback(auth)
            .usingToken(token)
            .sslCertificateCollection(getApiURL(overrides), auth.getCerts());
    if (auth.useCert())
        cb.sslCertCallbackWithDefaultHostnameVerifier(true);
    IClient client = cb.build();
    if (client == null) {
        listener.getLogger().println(
                String.format(MessageConstants.CANNOT_GET_CLIENT,
                        displayName, getApiURL(overrides)));
    }
    return new RetryIClient(client, listener);
}
 
Example #3
Source File: IOpenShiftExec.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
default IClient getClient(TaskListener listener, String displayName,
        Map<String, String> overrides, String token) {
    Auth auth = getAuth();
    ClientBuilder cb = null;
    long timeoutInMS = this.getTimeout(listener,
            Boolean.parseBoolean(getVerbose(overrides)), overrides);
    if (timeoutInMS > Integer.MAX_VALUE) {
        int timeoutInMin = (int) (timeoutInMS / 60000);
        cb = new ClientBuilder(getApiURL(overrides))
                .sslCertificateCallback(auth)
                .withReadTimeout(timeoutInMin, TimeUnit.MINUTES)
                .withWriteTimeout(timeoutInMin, TimeUnit.MINUTES)
                .withConnectTimeout(timeoutInMin, TimeUnit.MINUTES)
                .usingToken(token)
                .sslCertificateCollection(getApiURL(overrides),
                        auth.getCerts());
    } else {
        cb = new ClientBuilder(getApiURL(overrides))
                .sslCertificateCallback(auth)
                .withReadTimeout((int) timeoutInMS, TimeUnit.MILLISECONDS)
                .withWriteTimeout((int) timeoutInMS, TimeUnit.MILLISECONDS)
                .withConnectTimeout((int) timeoutInMS,
                        TimeUnit.MILLISECONDS)
                .usingToken(token)
                .sslCertificateCollection(getApiURL(overrides),
                        auth.getCerts());
    }

    if (auth.useCert())
        cb.sslCertCallbackWithDefaultHostnameVerifier(true);
    IClient client = cb.build();
    if (client == null) {
        listener.getLogger().println(
                String.format(MessageConstants.CANNOT_GET_CLIENT,
                        displayName, getApiURL(overrides)));
    }
    return new RetryIClient(client, listener);

}
 
Example #4
Source File: OpenshiftClientStorageProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private IClient getClient(ClientStorageProviderModel providerModel) {
    synchronized (this) {
        if (client == null) {
            client = new ClientBuilder(providerModel.get(OpenshiftClientStorageProviderFactory.CONFIG_PROPERTY_OPENSHIFT_URI)).build();
        }
    }

    return client;
}
 
Example #5
Source File: IOpenShiftPluginDescriptor.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
default FormValidation doTestConnection(@QueryParameter String apiURL,
        @QueryParameter String authToken) {

    EnvVars allOverrides = buildEnvVars();

    if (apiURL == null || StringUtils.isEmpty(apiURL)) {
        if (allOverrides
                .containsKey(IOpenShiftPlugin.KUBERNETES_SERVICE_HOST_ENV_KEY)
                && !StringUtils
                        .isEmpty(allOverrides
                                .get(IOpenShiftPlugin.KUBERNETES_SERVICE_HOST_ENV_KEY))) {
            apiURL = "https://"
                    + allOverrides
                            .get(IOpenShiftPlugin.KUBERNETES_SERVICE_HOST_ENV_KEY);

            if (allOverrides
                    .containsKey(IOpenShiftPlugin.KUBERNETES_SERVICE_PORT_ENV_KEY)) {
                apiURL = apiURL
                        + ":"
                        + allOverrides
                                .get(IOpenShiftPlugin.KUBERNETES_SERVICE_PORT_ENV_KEY);
            }
        } else if (allOverrides
                .containsKey(IOpenShiftPlugin.KUBERNETES_MASTER_ENV_KEY)
                && !StringUtils.isEmpty(allOverrides
                        .get(IOpenShiftPlugin.KUBERNETES_MASTER_ENV_KEY))) {
            // this one already has the https:// prefix
            apiURL = allOverrides
                    .get(IOpenShiftPlugin.KUBERNETES_MASTER_ENV_KEY);
        } else {
            return FormValidation.error("Required fields not provided");
        }
    }

    try {

        Auth auth = Auth.createInstance(null,
                getOverride(apiURL, allOverrides), allOverrides);

        ClientBuilder cb = new ClientBuilder(getOverride(apiURL,
                allOverrides))
                .sslCertificateCallback(auth)
                .usingToken(
                        Auth.deriveBearerToken(
                                getOverride(authToken, allOverrides), null,
                                false, allOverrides))
                .sslCertificateCollection(
                        getOverride(apiURL, allOverrides), auth.getCerts());

        if (auth.useCert())
            cb.sslCertCallbackWithDefaultHostnameVerifier(true);
        
        LOGGER.info("OpenShift Pipeline Plugin: testing connection for " + getOverride(apiURL, allOverrides));

        DefaultClient client = (DefaultClient) cb.build();

        if (client == null) {
            return FormValidation.error("Connection unsuccessful");
        }

        String status = client.getServerReadyStatus();
        LOGGER.info("OpenShift Pipeline Plugin: server ready status: " + status);
        if (status == null || !status.equalsIgnoreCase("ok")) {
            return FormValidation
                    .error("Connection made but server status is:  "
                            + status);
        }

        // the ready status is good for verifying the apiURL, but not for a
        // bad token;
        // making this REST call against the api server to validate the
        // token
        Request request = client
                .newRequestBuilderTo(
                        getOverride(apiURL, allOverrides) + "/apis").get()
                .build();
        Response result = client.adapt(OkHttpClient.class).newCall(request)
                .execute();
        if (result != null)
            LOGGER.info("OpenShift Pipeline Plugin: HTTP get to " + getOverride(apiURL, allOverrides) + "/apis returned HTTP code " + result.code() + " and message " + result.message());
        else
            LOGGER.info("OpenShift Pipeline Plugin: HTTP get to " + getOverride(apiURL, allOverrides) + "/apis got a null response");

    } catch (Throwable e) {
        LOGGER.log(Level.SEVERE, "doTestConnection", e);
        // note, the UnauthorizedException from the restclient/okhttp3 had a
        // misleading suggestion of using Basic authentication,
        // so going with just the exception's class name
        return FormValidation.error("Connection unsuccessful: "
                + e.getClass().getName());
    }

    return FormValidation.ok("Connection successful");
}
 
Example #6
Source File: OpenshiftStartedEnvironment.java    From pnc with Apache License 2.0 4 votes vote down vote up
public OpenshiftStartedEnvironment(
        ExecutorService executor,
        OpenshiftBuildAgentConfig openshiftBuildAgentConfig,
        OpenshiftEnvironmentDriverModuleConfig environmentConfiguration,
        PollingMonitor pollingMonitor,
        RepositorySession repositorySession,
        String systemImageId,
        DebugData debugData,
        String accessToken,
        boolean tempBuild,
        Instant temporaryBuildExpireDate,
        MetricsConfiguration metricsConfiguration,
        Map<String, String> parameters) {

    creationPodRetry = DEFAULT_CREATION_POD_RETRY;

    if (environmentConfiguration.getCreationPodRetry() != null) {
        try {
            creationPodRetry = Integer.parseInt(environmentConfiguration.getCreationPodRetry());
        } catch (NumberFormatException e) {
            logger.error("Couldn't parse the value of creation pod retry from the configuration. Using default");
        }
    }

    logger.info("Creating new build environment using image id: " + environmentConfiguration.getImageId());

    this.executor = executor;
    this.openshiftBuildAgentConfig = openshiftBuildAgentConfig;
    this.environmentConfiguration = environmentConfiguration;
    this.pollingMonitor = pollingMonitor;
    this.repositorySession = repositorySession;
    this.imageId = systemImageId == null ? environmentConfiguration.getImageId() : systemImageId;
    this.debugData = debugData;
    if (metricsConfiguration != null) {
        this.gaugeMetric = Optional.of(metricsConfiguration.getGaugeMetric());
    }

    createRoute = environmentConfiguration.getExposeBuildAgentOnPublicUrl();

    client = new ClientBuilder(environmentConfiguration.getRestEndpointUrl())
            .usingToken(environmentConfiguration.getRestAuthToken())
            .build();
    client.getServerReadyStatus(); // make sure client is connected

    environmetVariables = new HashMap<>();

    final String buildAgentHost = environmentConfiguration.getBuildAgentHost();
    String expiresDateStamp = Long.toString(temporaryBuildExpireDate.toEpochMilli());

    Boolean proxyActive = !StringUtils.isEmpty(environmentConfiguration.getProxyServer())
            && !StringUtils.isEmpty(environmentConfiguration.getProxyPort());

    environmetVariables.put("image", imageId);
    environmetVariables
            .put("firewallAllowedDestinations", environmentConfiguration.getFirewallAllowedDestinations());
    // This property sent as Json
    environmetVariables.put(
            "allowedHttpOutgoingDestinations",
            toEscapedJsonString(environmentConfiguration.getAllowedHttpOutgoingDestinations()));
    environmetVariables.put("isHttpActive", proxyActive.toString().toLowerCase());
    environmetVariables.put("proxyServer", environmentConfiguration.getProxyServer());
    environmetVariables.put("proxyPort", environmentConfiguration.getProxyPort());
    environmetVariables.put("nonProxyHosts", environmentConfiguration.getNonProxyHosts());

    environmetVariables.put("AProxDependencyUrl", repositorySession.getConnectionInfo().getDependencyUrl());
    environmetVariables.put("AProxDeployUrl", repositorySession.getConnectionInfo().getDeployUrl());

    environmetVariables.put("build-agent-host", buildAgentHost);
    environmetVariables.put("containerPort", environmentConfiguration.getContainerPort());
    environmetVariables.put("buildContentId", repositorySession.getBuildRepositoryId());
    environmetVariables.put("accessToken", accessToken);
    environmetVariables.put("tempBuild", Boolean.toString(tempBuild));
    environmetVariables.put("expiresDate", "ts" + expiresDateStamp);
    MDCUtils.getUserId().ifPresent(v -> environmetVariables.put("logUserId", v));
    MDCUtils.getProcessContext().ifPresent(v -> environmetVariables.put("logProcessContext", v));
    environmetVariables.put("resourcesMemory", builderPodMemory(environmentConfiguration, parameters));

    createEnvironment();
}