openshift/origin工作記錄(2)——RESTful編程接口使用

由於工作原因,需要對openshift進行二次開發,初步研究了一下RESTful編程接口使用。

本部分內容包括golang和java兩個版本,其中java版借鑑了開源項目 https://github.com/fabric8io/kubernetes-client ,目前是引用開源項目的jar包對openshift集羣進行操作。

golang獲取openshift token

package main

import (
	"crypto/tls"
	"fmt"
	"net/http"
    "encoding/base64"
    "strings"
)

func main() {
	const BEFORE_TOKEN, AFTER_TOKEN , AUTHORIZATION = "access_token=","&expires","Authorization"
	const MASTER_URL = "https://master.example.com:8443"
	const AUTHORIZE_PATH = "/oauth/authorize?response_type=token&client_id=openshift-challenging-client"
	//base64加密賬號密碼
	const username,password = "dev","dev"
	credential := "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password))

	//創建忽略證書的httpclient
	tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    
    url := MASTER_URL+AUTHORIZE_PATH
    request , err := http.NewRequest("GET", url, nil)
    if err != nil {
		// handle error
		fmt.Println(err)
		return
	}
    //Header添加賬號密碼信息
    request.Header.Add(AUTHORIZATION, credential)
    
    res, err := client.Do(request)
	if err != nil {
		// handle error
		fmt.Println(err)
		return
	}
	
	defer res.Body.Close()
	token := res.Request.URL.String()	
    token = token[strings.Index(token,BEFORE_TOKEN) + len(BEFORE_TOKEN):strings.Index(token,AFTER_TOKEN)];
	fmt.Println(token)
}

java簡單操作openshift集羣

demo工程放在了我的github上,地址爲https://github.com/hu12081/openshiftDemo.git。

代碼如下:

import io.fabric8.kubernetes.api.model.NamespaceList;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.utils.URLUtils;
import io.fabric8.openshift.client.DefaultOpenShiftClient;
import io.fabric8.openshift.client.OpenShiftConfig;
import io.fabric8.openshift.client.OpenShiftConfigBuilder;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.net.URL;

public class openshiftDemo {
    private static final String AUTHORIZATION = "Authorization";
    private static final String LOCATION = "Location";
    private static final String AUTHORIZE_PATH = "oauth/authorize?response_type=token&client_id=openshift-challenging-client";

    private static final String BEFORE_TOKEN = "access_token=";
    private static final String AFTER_TOKEN = "&expires";

    public static void main(String[] args) {
        OpenShiftConfig config = new OpenShiftConfigBuilder()
                .withOpenShiftUrl("https://master.example.com:8443")
                .withMasterUrl("https://master.example.com:8443")
                .withUsername("dev")
                .withPassword("dev")
                .withTrustCerts(true).build();
        DefaultOpenShiftClient client = new DefaultOpenShiftClient(config);
        openshiftDemo openshiftDemo=new openshiftDemo();
        //獲取用戶token
        System.out.println(openshiftDemo.authorize(client.getHttpClient(), config));
        //獲取工程列表,這裏必須是集羣管理員的賬號
        NamespaceList myNs = client.namespaces().list();
        //遍歷打印工程名
        for (Namespace ns : myNs.getItems())
            System.out.println(ns.getMetadata().getName());
    }

    //獲取token
    public String authorize(OkHttpClient client, OpenShiftConfig config) {
        try {
            OkHttpClient.Builder builder = client.newBuilder();
            builder.interceptors().remove(this);
            OkHttpClient clone = builder.build();

            String credential = Credentials.basic(config.getUsername(), new String(config.getPassword()));
            URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH));
            Response response = clone.newCall(new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()).execute();

            response.body().close();
            response = response.priorResponse() != null ? response.priorResponse() : response;
            response = response.networkResponse() != null ? response.networkResponse() : response;
            String token = response.header(LOCATION);
            if (token == null || token.isEmpty()) {
                throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + "), to the authorization request. Missing header:[" + LOCATION + "]!");
            }
            token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
            token = token.substring(0, token.indexOf(AFTER_TOKEN));
            return token;
        } catch (Exception e) {
            throw KubernetesClientException.launderThrowable(e);
        }
    }
}

代碼執行結果輸出如下:
這裏寫圖片描述

這裏能夠獲取用戶賬號的token。

可以自己基於openshift官方RESTful編程接口進行二次開發,也可以直接使用開源項目fabric8io/kubernetes-client的jar包提供的功能進行開發,甚至可以修改開源項目fabric8io/kubernetes-client的源碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章