org.jenkinsci.plugins.kubernetesworkflowsteps.KubeStepExecution.java Source code

Java tutorial

Introduction

Here is the source code for org.jenkinsci.plugins.kubernetesworkflowsteps.KubeStepExecution.java

Source

/*
 * Copyright 2014 Google Inc. All Rights Reserved.
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.jenkinsci.plugins.kubernetesworkflowsteps;

import com.google.common.net.HttpHeaders;

import groovy.json.JsonBuilder;
import groovy.json.JsonSlurper;

import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousStepExecution;

import hudson.EnvVars;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import javax.inject.Inject;
import javax.net.ssl.SSLContext;

/**
 * TODO: Insert description here. (generated by elibixby)
 */
public abstract class KubeStepExecution<S extends KubeStep> extends AbstractSynchronousStepExecution<Object> {

    private static final long serialVersionUID = -5260746262819154146L;

    private static final Map<String, String> env = EnvVars.masterEnvVars;

    private static final HttpHost host = new HttpHost(env.get("KUBERNETES_SERVICE_HOST"),
            Integer.valueOf(env.get("KUBERNETES_SERVICE_PORT")), "https");

    protected static final String prefix = "/api/v1beta1/";
    private static CloseableHttpClient client = null;
    private static Object client_lock = new Object();

    @Inject
    protected transient S step;

    protected <T extends HttpRequestBase> CloseableHttpResponse makeCall(T request) throws ClientProtocolException,
            IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        CloseableHttpResponse response;
        try {
            response = getClient().execute(host, request);
        } catch (ClientProtocolException e) {
            System.err.println(e.getMessage());
            throw e;
        }
        return response;
    }

    protected Object parse(CloseableHttpResponse resp) throws IOException {
        try {
            return (new JsonSlurper()).parse((new InputStreamReader(resp.getEntity().getContent())));
        } finally {
            resp.close();
        }

    }

    protected StringEntity toEntity(Object payload) throws UnsupportedEncodingException {
        return new StringEntity(new JsonBuilder(payload).toString());
    }

    private static CloseableHttpClient getClient()
            throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        if (client == null) {
            synchronized (client_lock) {
                if (client == null) {
                    SSLContextBuilder builder = SSLContexts.custom();
                    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

                    SSLContext sslContext = builder.build();

                    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                    Collection<BasicHeader> headers = new ArrayList<BasicHeader>();
                    headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
                    headers.add(new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + env.get("BEARER_TOKEN")));

                    client = HttpClients.custom().setDefaultHeaders(headers).setSSLSocketFactory(sslsf).build();
                }
            }
        }
        return client;
    }

}