美文网首页
Go语言的k8s开发-02-Namespace操作

Go语言的k8s开发-02-Namespace操作

作者: 玄德公笔记 | 来源:发表于2022-10-18 22:22 被阅读0次

    1. 结构体

    1.1 NamespaceList

    所在包:"k8s.io/api/core/v1"

    type NamespaceList struct {
        v1.TypeMeta `json:",inline"`
        v1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
        Items           []Namespace `json:"items" protobuf:"bytes,2,rep,name=items"`
    }
    

    其中Items的各元素结构体Namespace 如下:

    1.2 Namespace

    所在包:"k8s.io/api/core/v1"

    type Namespace struct {
        v1.TypeMeta   `json:",inline"`
        v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
        Spec              NamespaceSpec   `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
        Status            NamespaceStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
    

    其中各成员结构体如下:

    1.3 TypeMeta

    所在包 "k8s.io/apimachinery/pkg/apis/meta/v1"

    Package:
    v1
    type TypeMeta struct {
        Kind       string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"`
        APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,2,opt,name=apiVersion"`
    }
    

    对应k8s的yml文件中的如下部分

    apiVersion: v1
    kind: Namespace
    

    1.4 ObjectMeta

    所在包 "k8s.io/apimachinery/pkg/apis/meta/v1"

    type ObjectMeta struct {
        Name                       string               `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"`
        GenerateName               string               `json:"generateName,omitempty" protobuf:"bytes,2,opt,name=generateName"`
        Namespace                  string               `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"`
        SelfLink                   string               `json:"selfLink,omitempty" protobuf:"bytes,4,opt,name=selfLink"`
        UID                        types.UID            `json:"uid,omitempty" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"`
        ResourceVersion            string               `json:"resourceVersion,omitempty" protobuf:"bytes,6,opt,name=resourceVersion"`
        Generation                 int64                `json:"generation,omitempty" protobuf:"varint,7,opt,name=generation"`
        CreationTimestamp          Time                 `json:"creationTimestamp,omitempty" protobuf:"bytes,8,opt,name=creationTimestamp"`
        DeletionTimestamp          *Time                `json:"deletionTimestamp,omitempty" protobuf:"bytes,9,opt,name=deletionTimestamp"`
        DeletionGracePeriodSeconds *int64               `json:"deletionGracePeriodSeconds,omitempty" protobuf:"varint,10,opt,name=deletionGracePeriodSeconds"`
        Labels                     map[string]string    `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"`
        Annotations                map[string]string    `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"`
        OwnerReferences            []OwnerReference     `json:"ownerReferences,omitempty" patchStrategy:"merge" patchMergeKey:"uid" protobuf:"bytes,13,rep,name=ownerReferences"`
        Finalizers                 []string             `json:"finalizers,omitempty" patchStrategy:"merge" protobuf:"bytes,14,rep,name=finalizers"`
        ManagedFields              []ManagedFieldsEntry `json:"managedFields,omitempty" protobuf:"bytes,17,rep,name=managedFields"`
    }
    
    

    对应k8s的yml文件如下部分

    metadata:
      ……
    

    1.5 NamespaceSpec

    所在包:"k8s.io/api/core/v1"

    type NamespaceSpec struct {
        Finalizers []FinalizerName `json:"finalizers,omitempty" protobuf:"bytes,1,rep,name=finalizers,casttype=FinalizerName"`
    }
    

    对应k8s的yml文件如下部分

    spec:
      ……
    

    Namespace 的这一部分在使用中意义并不大

    1.6 NamespaceStatus

    所在包:"k8s.io/api/core/v1"

    type NamespaceStatus struct {
        Phase      NamespacePhase       `json:"phase,omitempty" protobuf:"bytes,1,opt,name=phase,casttype=NamespacePhase"`
        Conditions []NamespaceCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,2,rep,name=conditions"`
    }
    

    对应k8s的yml文件如下部分

    status:
      phase: Active
    

    1.7 对照yml文件示例

    附原生k8s集群上一个namespace 信息,大家可以对照理解一下以上结构体

    apiVersion: v1
    kind: Namespace
    metadata:
      annotations:
        cattle.io/status: '{"Conditions":[{"Type":"ResourceQuotaInit","Status":"True","Message":"","LastUpdateTime":"2022-09-28T05:22:19Z"},{"Type":"InitialRolesPopulated","Status":"True","Message":"","LastUpdateTime":"2022-09-28T05:22:19Z"}]}'
        lifecycle.cattle.io/create.namespace-auth: "true"
      creationTimestamp: "2022-09-28T05:23:29Z"
      finalizers:
      - controller.cattle.io/namespace-auth
      labels:
        kubernetes.io/metadata.name: liubei
      name: liubei
      resourceVersion: "19106479"
      selfLink: /api/v1/namespaces/liubei
      uid: 0aa2122e-2244-44cf-ba55-0437f50e2ff3
    spec:
      finalizers:
      - kubernetes
    status:
      phase: Active
    
    

    2. Namespace List

    语法

    • 语法
    func (NamespaceInterface) List(ctx context.Context, opts v1.ListOptions) (*v1.NamespaceList, error)
    
    • 语法示例
    namespaceList,err = clientSet.CoreV1().Namespaces().List(context.TODO(), metaV1.ListOptions{})
    

    完整示例

    • 定义函数
    package crowK8S
    
    import (
        "context"
        coreV1 "k8s.io/api/core/v1"
        metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/kubernetes"
    )
    
    func GetNamespaceList(clientSet *kubernetes.Clientset)(namespaceList *coreV1.NamespaceList,err error)  {
        namespaceList,err = clientSet.CoreV1().Namespaces().List(context.TODO(), metaV1.ListOptions{})
        if err != nil {
            return namespaceList,err
        }
        return namespaceList,nil
    }
    
    • 调用示例
    package main
    
    import (
        "fmt"
        "go-k8s/crowK8S"
    )
    
    func main()  {
        clientSet,err := crowK8S.ConnectK8s()
        if err !=nil {
            fmt.Println(err)
        }
    
        namespaceList,err := crowK8S.GetNamespaceList(clientSet)
        if err !=nil {
            fmt.Println(err)
        }
        for _,namespace := range namespaceList.Items {
            fmt.Printf("%+v\n",namespace.Name)
        }
    }
    
    • 结果
    cattle-system
    crust-v3x-sit
    default
    kube-node-lease
    kube-public
    kube-system
    ……
    

    3. Get Namespace

    语法

    • 语法
    func (NamespaceInterface) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1.Namespace, error)
    
    • 语法示例
    namespaceInfo,err = clientSet.CoreV1().Namespaces().Get(context.TODO(),namespaceName,metaV1.GetOptions{})
    

    完整示例

    • 函数
    package crowK8S
    
    import (
        "context"
        coreV1 "k8s.io/api/core/v1"
        metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/kubernetes"
    )
    func GetNamespace(clientSet *kubernetes.Clientset,namespaceName string)(namespaceInfo *coreV1.Namespace,err error)  {
        namespaceInfo,err = clientSet.CoreV1().Namespaces().Get(context.TODO(),namespaceName,metaV1.GetOptions{})
        if err != nil {
            return namespaceInfo,err
        }
        return namespaceInfo,nil
    }
    
    • 调用
    package main
    
    import (
        "fmt"
        "go-k8s/crowK8S"
    )
    
    func main()  {
        clientSet,err := crowK8S.ConnectK8s()
        if err !=nil {
            fmt.Println(err)
        }
    
        namespaceInfo,err := crowK8S.GetNamespace(clientSet,"kube-system")
        if err !=nil {
            fmt.Printf("%+v\n",namespaceInfo)
        }
    
    }
    
    • 结果
    &Namespace{ObjectMeta:{kube-system   /api/v1/namespaces/kube-system 273b218d-5a59-411d-8950-ab150b4e176a 6700369 0 2022-07-12 16:41:31 +0800 CST <nil> <nil> map[field.cattle.io/projectId:p-qc5f4 kubernetes.io/metadata.name:kube-system] map[cattle.io/status:{"Conditions":[{"Type":"ResourceQuotaInit","Status":"True","Message":"","LastUpdateTime":"2022-08-12T08:41:05Z"},{"Type":"InitialRolesPopulated","Status":"True","Message":"","LastUpdateTime":"2022-08-12T08:41:10Z"}]} field.cattle.io/projectId:c-c8rsj:p-qc5f4 lifecycle.cattle.io/create.namespace-auth:true] [] [controller.cattle.io/namespace-auth] [{kube-apiserver Update v1 2022-07-12 16:41:31 +0800 CST FieldsV1 {"f:metadata":{"f:labels":{".":{},"f:kubernetes.io/metadata.name":{}}}} } {rancher Update v1 2022-08-12 16:42:15 +0800 CST FieldsV1 {"f:metadata":{"f:annotations":{".":{},"f:cattle.io/status":{},"f:field.cattle.io/projectId":{},"f:lifecycle.cattle.io/create.namespace-auth":{}},"f:finalizers":{".":{},"v:\"controller.cattle.io/namespace-auth\"":{}}}} } {agent Update v1 2022-08-12 16:42:40 +0800 CST FieldsV1 {"f:metadata":{"f:labels":{"f:field.cattle.io/projectId":{}}}} }]},Spec:NamespaceSpec{Finalizers:[kubernetes],},Status:NamespaceStatus{Phase:Active,Conditions:[]NamespaceCondition{},},}
    

    4. Create Namespace

    • 创建namespace的yml文件如下:
    apiVersion: v1
    kind: Namespace
    metadata:
      name: liubei
    

    kindapiVersionSDK会给我们补充上,因此我们只需要填上名字即可

    语法

    • 语法
    func (NamespaceInterface) Create(ctx context.Context, namespace *v1.Namespace, opts v1.CreateOptions) (*v1.Namespace, error)
    
    • 语法示例
    namespaceInfo,err = clientSet.CoreV1().Namespaces().Create(context.TODO(),&namespace,metaV1.CreateOptions{})
    

    完整示例

    • 创建函数
    package crowK8S
    
    import (
        "context"
        coreV1 "k8s.io/api/core/v1"
        metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/kubernetes"
    )
    
    func CreateNamespace(clientSet *kubernetes.Clientset,namespaceName string)(namespaceInfo *coreV1.Namespace,err error)  {
        var namespace coreV1.Namespace
        namespace.Name = namespaceName
        namespaceInfo,err = clientSet.CoreV1().Namespaces().Create(context.TODO(),&namespace,metaV1.CreateOptions{})
        if err != nil {
            return namespaceInfo,err
        }
        return namespaceInfo,nil
    }
    
    • 引用
    package main
    
    import (
        "fmt"
        "go-k8s/crowK8S"
    )
    
    func main()  {
        clientSet,err := crowK8S.ConnectK8s()
        if err !=nil {
            fmt.Println(err)
        }
    
        namespaceInfo,err := crowK8S.CreateNamespace(clientSet,"liubei")
        if err !=nil {
            fmt.Println(err)
        }
        fmt.Printf("%+v\n",namespaceInfo)
    }
    
    • 输出
    &Namespace{ObjectMeta:{liubei   /api/v1/namespaces/liubei 68ae5eca-13a7-4720-b636-789a3b1776d2 19055960 0 2022-09-28 08:52:32 +0800 CST <nil> <nil> map[kubernetes.io/metadata.name:liubei] map[] [] [] [{___6go_build_main_go.exe Update v1 2022-09-28 08:52:32 +0800 CST FieldsV1 {"f:metadata":{"f:labels":{".":{},"f:kubernetes.io/metadata.name":{}}}} }]},Spec:NamespaceSpec{Finalizers:[kubernetes],},Status:NamespaceStatus{Phase:Active,Conditions:[]NamespaceCondition{},},}
    

    5. Delete Namespace

    语法

    • 语法
    func (NamespaceInterface) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
    
    • 语法示例
    err = clientSet.CoreV1().Namespaces().Delete(context.TODO(),namespaceName,metaV1.DeleteOptions{})
    

    完整示例

    • 创建函数
    package crowK8S
    
    import (
        "context"
        coreV1 "k8s.io/api/core/v1"
        metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/kubernetes"
    )
    func DeleteNamespace(clientSet *kubernetes.Clientset,namespaceName string)(err error)  {
        err = clientSet.CoreV1().Namespaces().Delete(context.TODO(),namespaceName,metaV1.DeleteOptions{})
        if err != nil {
            return err
        }
        return nil
    }
    
    • 引用
    package main
    
    import (
        "fmt"
        "go-k8s/crowK8S"
    )
    
    func main()  {
        clientSet,err := crowK8S.ConnectK8s()
        if err !=nil {
            fmt.Println(err)
        }
    
        err = crowK8S.DeleteNamespace(clientSet,"liubei")
        if err !=nil {
            fmt.Println(err)
        }
    
    }
    

    相关文章

      网友评论

          本文标题:Go语言的k8s开发-02-Namespace操作

          本文链接:https://www.haomeiwen.com/subject/tgbszrtx.html