Kubernetes two development (mainly to develop the API to meet their own business)

Source: Internet
Author: User
Tags k8s
kubernetes clinet-go Development (I.)

Kubernetes currently provides two ways to create the required pod,service,replicationcontroller, one is through Kubectl create-f, a restful interface via HTTP, because of the work item's reason, Need to be customized according to the actual business needs of the development of K8s API, I used the library is the official, code base address: Https://github.com/kubernetes/client-go, the following is my development in some of the idea of finishing, due to the level of limited, Speak well, but also ask the vast number of Bo friends understanding. Initialization of Connection code create namespace create pod create replicationcontroller Create service Initialize connection way one:

Directly on the code:

Package main

Import (
    "FMT"
    "Time"

    "K8s.io/client-go/1.4/kubernetes"
    k8s.io/client-go/1.4/ Pkg/api "
    " K8s.io/client-go/1.4/rest "
)

func main () {
    //creates the In-cluster Config
    config, ERR: = rest. Inclusterconfig ()
    If err!= nil {
        panic (err. Error ())
    }
    //creates the Clientset
    clientset, err: = Kubernetes. Newforconfig (config)
    If err!= nil {
        panic (err. Error ())
    }
}
Code Interpretation

The above code is to get a client of a kubernetes cluster

Config, err: = rest. Inclusterconfig ()

The bank code is to initialize a default k8s rest. Config, the config source code is as follows:

Type Config struct {//host must is a host string, a Host:port pair, or a URL to the base of the apiserver.//If a URL I s given then the (optional) Path of that URL represents a prefix that must/is appended to all request URIs used to ACCE SS the Apiserver.
This is allows a frontend//proxy to easily relocate all of the apiserver endpoints.
Host string//Apipath is a sub-path the points to a API root. Apipath string//Prefix is the sub path of the server.  If not specified, the client would set//a default value. Use '/' to indicate the server root should is used Prefix string//Contentconfig contains settings that affect how Objec
TS are transformed when//sent to the server. Contentconfig//server requires Basic authentication Username string Password string//Server requires bearer Authenti cation.
This client won't attempt to use//refresh tokens for a OAuth2 flow.
Todo:demonstrate an OAuth2 compatible client. Bearertoken string//impersonate is the username tHat this restclient would impersonate impersonate string//Server requires plugin-specified authentication. Authprovider *clientcmdapi.
Authproviderconfig//Callback to persist config for Authprovider. Authconfigpersister authproviderconfigpersister//Tlsclientconfig contains settings to enable Transport Layer Security T Lsclientconfig//Server should be accessed without verifying the TLS//certificate.
For testing.
insecure bool//useragent is a optional field that specifies the caller of this request. UserAgent string//transport may is used for custom HTTP behavior. This attribute may is not//is specified with the TLS client certificate options.
Use Wraptransport//For most client level operations. Transport HTTP. Roundtripper//Wraptransport'll be invoked for custom HTTP behavior after the underlying//transport is initialized (E Ither the transport created from tlsclientconfig,//transport, or HTTP. Defaulttransport). The config may layer other roundtrippers//On Top of the returned roundtripper. Wraptransport func (Rt http. Roundtripper) http.
Roundtripper//QPS indicates the maximum QPS to the master from this client.
If it ' s zero, the created restclient'll use defaultqps:5 QPS float32//Maximum burst for throttle.
If it ' s zero, the created restclient'll use Defaultburst:10. Burst int//Rate limiter for limiting connections to the master from this client. If present overwrites Qps/burst Ratelimiter FlowControl.
Ratelimiter//version forces a specific version to is used (if registered)//Do we need this?
 Version string

}

This config contains some information that the connection Apiserver needs, I include the API connection IP port (i.e. hostname), used for authentication some information, such as: Username,password, as well as API call return value type, serialization and so on.

Back to the Inclusterconfig () method:

Func inclusterconfig () (*config, error) {host, Port: = OS. Getenv ("Kubernetes_service_host"), OS. Getenv ("Kubernetes_service_port") If Len (host) = = 0 | | Len (port) = = 0 {return nil, fmt.

Errorf ("Unable to load In-cluster configuration, Kubernetes_service_host and Kubernetes_service_port must is defined")} token, err: = Ioutil. ReadFile ("/var/run/secrets/kubernetes.io/serviceaccount/" + API). Serviceaccounttokenkey) If Err!= nil {return nil, err} tlsclientconfig: = tlsclientconfig{} rootcafile: = "/var/run /secrets/kubernetes.io/serviceaccount/"+ API. Serviceaccountrootcakey If _, err: = Crypto. Certpoolfromfile (Rootcafile); Err!= Nil {glog. Errorf ("Expected to load Root CA config from%s, but got err:%v", Rootcafile, Err)} else {tlsclientconfig.cafile =
    Rootcafile} return &config{//Todo:switch to using cluster DNS. Host: "https://" + net. Joinhostport (host, Port), bearertoken:string (token), Tlsclientconfig:tlsclientconfig,}, NIl}
 

The first is to get the kubernetes_service_host and kubernetes_service_port environment variables, so you have to set these two environment variables (that is, the IP and port of Apiserver) and then get/var/run The authentication file under/secrets/kubernetes.io/serviceaccount/, the initialization of Config, so as to prepare for the next connection. If there is no corresponding CA file in the appropriate environment, the method will error, initializing the k8s client unsuccessful way two:

var (
    kubeconfig = flag. String ("Kubeconfig", "./config", "absolute path to the Kubeconfig file")

func main () {
    flag. Parse ()
    //uses
    in Kubeconfig config, err: = Clientcmd. Buildconfigfromflags ("183.131.19.231:8080", *kubeconfig)
    If err!= nil {
        panic (err. Error ())
    }
    //creates the Clientset
    clientset, err: = Kubernetes. Newforconfig (config)
    If err!= nil {
        panic (err. Error ())
    }
}

Where the config profile information is as follows:

APIVERSION:V1
Clusters:
-cluster:
    api-version:v1
    server:http://183.131.19.231:8080
  Name: K8s-cluster
Contexts:
-Context:
    cluster:k8s-server
    user:myself
  name:default-context
Current-context:default-context
kind:config
Preferences:
  colors:true
users:
-Name: Myself
  User:
    password:admin
    username:admin11232

This approach is through the configuration file to link Kube-apiserver, so as to obtain Clientset, configuration file settings and access to the official documentation: http://kubernetes.io/docs/user-guide/ kubeconfig-file/ Create namespace

First of all, the reason for creating NAMESAPCE is because the subsequent creation of Pod,replicationcontroller,service, which is associated with NAMESAPCE in the usual business, is actually equivalent to the concept of a tenant, or the equivalent of group, the role of resource isolation.

First look at the client. The Core () method includes those interfaces and the implementation of the interface:

Func (c *coreclient) componentstatuses () Componentstatusinterface {return newcomponentstatuses (c)} func (c *corecli ENT) Configmaps (namespace string) Configmapinterface {return newconfigmaps (c, namespace)} func (c *coreclient) ENDP Oints (Namespace String) Endpointsinterface {return newendpoints (c, namespace)} func (c *coreclient) Events (Namespac E string) Eventinterface {return newevents (c, namespace)} func (c *coreclient) Limitranges (namespace string) Limitr Angeinterface {return newlimitranges (c, namespace)} func (c *coreclient) namespaces () Namespaceinterface {Retu RN newnamespaces (c)} func (c *coreclient) Nodes () Nodeinterface {return newnodes (c)} func (c *coreclient) Persist Entvolumes () Persistentvolumeinterface {return newpersistentvolumes (c)} func (c *coreclient) persistentvolumeclaims (Namespace String)  Persistentvolumeclaiminterface {return newpersistentvolumeclaims (c, namespace)} func (c *coreclient) Pods (namespace StriNG) Podinterface {return newpods (c, namespace)} func (c *coreclient) Podtemplates (namespace string) Podtemplateinte Rface {return newpodtemplates (c, namespace)} func (c *coreclient) Replicationcontrollers (namespace string) Replicat Ioncontrollerinterface {return newreplicationcontrollers (c, namespace)} func (c *coreclient) Resourcequotas (Namespa Ce string) resourcequotainterface {return Newresourcequotas (c, namespace)} func (c *coreclient) Secrets (namespace S Tring) Secretinterface {return newsecrets (c, namespace)} func (c *coreclient) Services (namespace string) Serviceint Erface {return newservices (c, namespace)} func (c *coreclient) serviceaccounts (namespace string) Serviceaccountinte Rface {return newserviceaccounts (c, namespace)}

One of the main things we use here is

Func (c *coreclient) namespaces () Namespaceinterface {return
    newnamespaces (c)
}

Looking at the method in the Namespaceinterface interface:

Type Namespaceinterface Interface {
    Create (*V1). Namespace) (*V1. Namespace, error)
    Update (*v1. Namespace) (*V1. Namespace, error)
    UpdateStatus (*v1. Namespace) (*V1. Namespace, error)
    Delete (name string, Options *api. deleteoptions) Error
    deletecollection (Options *api. Deleteoptions, Listoptions API. listoptions) Error Get
    (name string) (*v1. Namespace, error)
    List (OPTs API. listoptions) (*V1. Namespacelist, error)
    Watch (OPTs API. listoptions) (watch. Interface, error)
    Patch (name string, PT API. Patchtype, data []byte, Subresources ... string) (Result *v1. Namespace, err Error)
    namespaceexpansion
}

Here we mainly explain the creation of namespace:
Creating namespace requires incoming v1. Namespace this struct pointer, we're looking at the structure of this STRUTC:

Type Namespace struct {
    unversioned. Typemeta ' JSON:, inline '
    //Standard object ' s metadata.
    More Info:http://releases.k8s.io/head/docs/devel/api-conventions.md#metadata
    Objectmeta ' JSON: ' metadata, Omitempty "Protobuf:" Bytes,1,opt,name=metadata "

    //Spec defines the behavior of the Namespace.
    More info:http://releases.k8s.io/head/docs/devel/api-conventions.md#spec-and-status
    spec NamespaceSpec ' JSON: "Spec,omitempty" Protobuf: "Bytes,2,opt,name=spec"

    //Status describes the current status of a Namespace.
    More Info:http://releases.k8s.io/head/docs/devel/api-conventions.md#spec-and-status
    status NamespaceStatus ' JSON: ' Status,omitempty ' protobuf: ' Bytes,3,opt,name=status '
}

Three of these struct are in the Yaml type, metadata, and space is one by one corresponding.

    Create a namespace
    NC: = new (v1. Namespace)
    Nctypemeta: = unversioned. Typemeta{kind: "NameSpace", Apiversion: "v1"}
    NC. Typemeta = Nctypemeta

    nc. Objectmeta = v1. objectmeta{
        Name: "K8s-test",
    }

    NC. Spec = v1. namespacespec{}

This is actually equivalent to the following definition in the Yaml file:

APIVERSION:V1
kind:namespace
metadata:
  name: "K8s-test"
Spec:

If you have settings like Lable,space, check the relevant code plus.

Then create namespace:

RESULTNC, err: = DAO. Clientset.core (). Namespaces (). Create (NC)

After successful completion, the namespace is returned and the corresponding error message is returned if it fails.

After that, the KUBECTL command is used to view the created namespace in the K8s cluster, creating success. Similarly, delete changes and other operations, here is not one by one demo. Create pod

The way to create the pod and Rc,service is basically consistent with the namaspace, so I'll just post the code directly:

    Pod:=new (v1. POD) pod. typemeta=unversioned. Typemeta{kind: "Pod", Apiversion: "V1"} pod. Objectmeta=v1. Objectmeta{name:app. Name, Namespace:app. UserName, labels:map[string]string{"name": App. Name} pod. Spec=v1. podspec{Restartpolicy:v1. Restartpolicyalways, containers: []v1. container{v1. container{Name:app. Name, Image:app. Image, Ports: []v1. containerport{v1. containerport{containerport:9080, Protocol:v1. Protocoltcp,},}, Resources:v1. resourcerequirements{Requests:v1. resourcelist{v1. Resourcecpu:resource. Mustparse (app. CPU), v1. Resourcememory:resource. Mustparse (app.
 Memory),                           },},},}, Resul T, err: = DAO. Clientset.core (). Pods (NameSpace). Create (POD)
Create Replicationcontroller
Create a Replicationcontroller RC: = new (v1. Replicationcontroller) Rctypemeta: = unversioned. Typemeta{kind: "Replicationcontroller", Apiversion: "v1"} RC. Typemeta = Rctypemeta Rcobjectmeta: = v1. Objectmeta{name:app. Name, Namespace:app. UserName, labels:map[string]string{"name": App. Name} RC. Objectmeta = Rcobjectmeta Rcspec: = v1. replicationcontrollerspec{Replicas: &app. InstanceCount, selector:map[string]string{"name": App. Name,}, Template: &v1. podtemplatespec{v1. objectmeta{Name:app. Name, Namespace:app. UserName, labels:map[string]string{"name": App. Name,},}, V1. podspec{Restartpolicy:v1. Restartpolicyalways, containers: []v1. container{v1. container{Name:app. Name, Image: App. Image, Ports: []v1. containerport{v1. containerport{containerport:9080, Protocol:v1. Protocoltcp,},}, Resources:v1. resourcerequirements{Requests:v1. resourcelist{v1. Resourcecpu:resource. Mustparse (app. CPU), v1. Resourcememory:resource. Mustparse (app. Memory),},},},},} ,},} RC. Spec = Rcspec result, err: = DAO. Clientset.core (). Replicationcontrollers (NameSpace). Create (RC)
Create service
Create service service: = new (v1. Service) Svtypemeta: = unversioned. Typemeta{kind: "Service", Apiversion: "v1"} service. Typemeta = Svtypemeta Svobjectmeta: = v1. Objectmeta{name:app. Name, Namespace:app. UserName, labels:map[string]string{"name": App. Name} service. Objectmeta = Svobjectmeta Svservicespec: = v1. servicespec{Ports: []v1. serviceport{v1. serviceport{Name:app. Name, port:9080, Targetport:intstr.
            Fromint (9080), Protocol: "TCP",//nodeport:32107,}, }, selector:map[string]string{"name": App. Name}, Type:v1. Servicetypenodeport,//Loadbalancerip: "172.17.11.2",//STATUS:V1. servicestatus{//LOADBALANCER:V1. loadbalancerstatus{//ingress: []v1.
    loadbalanceringress{        V1. Loadbalanceringress{ip: "172.17.11.2"},///},//},///}, serv Ice. Spec = Svservicespec _, Err: = DAO. Clientset.core (). Services (NameSpace). Create (Service)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.