Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go开发k8s Service操作

Go语言开发k8s之Service操作解析

作者:开发运维玄德公

这篇文章主要为大家介绍了Go语言开发k8s之Service操作解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

1. 结构体

1.1 ServiceList

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

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

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

1.2 Service

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

type Service struct {
    v1.TypeMeta   `json:",inline"`
    v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    Spec              ServiceSpec   `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
    Status            ServiceStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

其中TypeMetaObjectMeta ServiceSpec ServiceStatus结构体如下:

1.3 TypeMeta

所在包:"k8s.io/apimachinery/pkg/apis/meta/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的yaml文件如下部分:

apiVersion: v1
kind: Service

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:
  ……

代码中实例化示例如下:

        ObjectMeta: metaV1.ObjectMeta{
            Name: "nginx",
            Labels: map[string]string{
                "app":"nginx",
            },
        },

1.5 ServiceSpec

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

type ServiceSpec struct {
    Ports                         []ServicePort                     `json:"ports,omitempty" patchStrategy:"merge" patchMergeKey:"port" protobuf:"bytes,1,rep,name=ports"`
    Selector                      map[string]string                 `json:"selector,omitempty" protobuf:"bytes,2,rep,name=selector"`
    ClusterIP                     string                            `json:"clusterIP,omitempty" protobuf:"bytes,3,opt,name=clusterIP"`
    ClusterIPs                    []string                          `json:"clusterIPs,omitempty" protobuf:"bytes,18,opt,name=clusterIPs"`
    Type                          ServiceType                       `json:"type,omitempty" protobuf:"bytes,4,opt,name=type,casttype=ServiceType"`
    ExternalIPs                   []string                          `json:"externalIPs,omitempty" protobuf:"bytes,5,rep,name=externalIPs"`
    SessionAffinity               ServiceAffinity                   `json:"sessionAffinity,omitempty" protobuf:"bytes,7,opt,name=sessionAffinity,casttype=ServiceAffinity"`
    LoadBalancerIP                string                            `json:"loadBalancerIP,omitempty" protobuf:"bytes,8,opt,name=loadBalancerIP"`
    LoadBalancerSourceRanges      []string                          `json:"loadBalancerSourceRanges,omitempty" protobuf:"bytes,9,opt,name=loadBalancerSourceRanges"`
    ExternalName                  string                            `json:"externalName,omitempty" protobuf:"bytes,10,opt,name=externalName"`
    ExternalTrafficPolicy         ServiceExternalTrafficPolicyType  `json:"externalTrafficPolicy,omitempty" protobuf:"bytes,11,opt,name=externalTrafficPolicy"`
    HealthCheckNodePort           int32                             `json:"healthCheckNodePort,omitempty" protobuf:"bytes,12,opt,name=healthCheckNodePort"`
    PublishNotReadyAddresses      bool                              `json:"publishNotReadyAddresses,omitempty" protobuf:"varint,13,opt,name=publishNotReadyAddresses"`
    SessionAffinityConfig         *SessionAffinityConfig            `json:"sessionAffinityConfig,omitempty" protobuf:"bytes,14,opt,name=sessionAffinityConfig"`
    IPFamilies                    []IPFamily                        `json:"ipFamilies,omitempty" protobuf:"bytes,19,opt,name=ipFamilies,casttype=IPFamily"`
    IPFamilyPolicy                *IPFamilyPolicy                   `json:"ipFamilyPolicy,omitempty" protobuf:"bytes,17,opt,name=ipFamilyPolicy,casttype=IPFamilyPolicy"`
    AllocateLoadBalancerNodePorts *bool                             `json:"allocateLoadBalancerNodePorts,omitempty" protobuf:"bytes,20,opt,name=allocateLoadBalancerNodePorts"`
    LoadBalancerClass             *string                           `json:"loadBalancerClass,omitempty" protobuf:"bytes,21,opt,name=loadBalancerClass"`
    InternalTrafficPolicy         *ServiceInternalTrafficPolicyType `json:"internalTrafficPolicy,omitempty" protobuf:"bytes,22,opt,name=internalTrafficPolicy"`
}

对应原生k8s创建service的 yml文件中spec的内容示例如下:(这一部分也是我们主要填写的)

spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30500
  selector:
    app: nginx

代码示例如下:

        Spec: coreV1.ServiceSpec{
            Type: coreV1.ServiceTypeNodePort,
            Selector: map[string]string{
                "app":"nginx",
            },
            Ports: []coreV1.ServicePort{
                {
                    Port: 80,
                    Protocol: coreV1.ProtocolTCP,
                    NodePort: nodePort,
                },
            },
        }

1.6 ServiceStatus

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

type ServiceStatus struct {
    LoadBalancer LoadBalancerStatus `json:"loadBalancer,omitempty" protobuf:"bytes,1,opt,name=loadBalancer"`
    Conditions   []v1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,2,rep,name=conditions"`
}

service 的状态,这个不用过多操作。

1.7 对照yml文件示例

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

apiVersion: v1
kind: Service
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["10.10.117.53"],"port":30051,"protocol":"TCP","serviceName":"liubei:nginx","allNodes":true}]'
  creationTimestamp: "2022-09-29T07:01:01Z"
  labels:
    app: nginx
  name: nginx
  namespace: liubei
  resourceVersion: "19646213"
  selfLink: /api/v1/namespaces/liubei/services/nginx
  uid: 7d05764c-87a7-46d1-8e4f-bed136755fb9
spec:
  clusterIP: 10.1.101.241
  clusterIPs:
  - 10.1.101.241
  externalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - nodePort: 30051
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: nginx
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}

2. Get List

语法

func (ServiceInterface) List(ctx context.Context, opts v1.ListOptions) (*v1.ServiceList, error)
serviceList,err = clientSet.CoreV1().Services(namespaceName).List(context.TODO(),metaV1.ListOptions{})

完整示例

package crowK8S
import (
    "context"
    "fmt"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func GetServiceList(clientSet *kubernetes.Clientset,namespaceName string) (serviceList *coreV1.ServiceList,err error) {
    serviceList,err = clientSet.CoreV1().Services(namespaceName).List(context.TODO(),metaV1.ListOptions{})
    if err != nil {
        return serviceList,err
    }
    return serviceList,nil
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceList,err := crowK8S.GetServiceList(clientSet,"kube-system")
    for _,serviceInfo := range serviceList.Items{
        fmt.Println(serviceInfo.Name)
    }
}

输出

kube-dns
metrics-server

3. Create

语法

func (ServiceInterface) Create(ctx context.Context, service *v1.Service, opts v1.CreateOptions) (*v1.Service, error)
serviceInfo,err = clientSet.CoreV1().Services(namespace).Create(context.TODO(),service,metaV1.CreateOptions{})

完整示例

以下是边这个yml文件为例,我们就照着这个内容写代码:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: test
  labels:
    app: nginx
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30500
  selector:
    app: nginx
func CreateService(clientSet *kubernetes.Clientset,namespaceName string) (serviceInfo *coreV1.Service,err error) {
    namespace := namespaceName
    service := &coreV1.Service{
        ObjectMeta: metaV1.ObjectMeta{
            Name: "nginx",
            Labels: map[string]string{
                "app":"nginx",
            },
        },
        Spec: coreV1.ServiceSpec{
            Type: coreV1.ServiceTypeNodePort,
            Selector: map[string]string{
                "app":"nginx",
            },
            Ports: []coreV1.ServicePort{
                {
                    Port: 80,
                    Protocol: coreV1.ProtocolTCP,
                    NodePort: 30050,
                },
            },
        },
    }
    serviceInfo,err = clientSet.CoreV1().Services(namespace).Create(context.TODO(),service,metaV1.CreateOptions{})
    return serviceInfo,nil
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceInfo,err := crowK8S.CreateService(clientSet ,"liubei")
    fmt.Println(serviceInfo)
}

本来是一个json字串,以下是我格式化之后贴上来的:

{
    ObjectMeta: {
        nginx liubei / api / v1 / namespaces / liubei / services / nginx 7 d05764c - 87 a7 - 46 d1 - 8e4 f - bed136755fb9 19389876 0 2022 - 09 - 29 15: 01: 01 + 0800 CST < nil > < nil > map[app: nginx] map[][][][{
            ___6go_build_main_go.exe Update v1 2022 - 09 - 29 15: 01: 01 + 0800 CST FieldsV1 {
                "f:metadata": {
                    "f:labels": {
                        ".": {},
                        "f:app": {}
                    }
                },
                "f:spec": {
                    "f:externalTrafficPolicy": {},
                    "f:ports": {
                        ".": {},
                        "k:{\"port\":80,\"protocol\":\"TCP\"}": {
                            ".": {},
                            "f:nodePort": {},
                            "f:port": {},
                            "f:protocol": {},
                            "f:targetPort": {}
                        }
                    },
                    "f:selector": {
                        ".": {},
                        "f:app": {}
                    },
                    "f:sessionAffinity": {},
                    "f:type": {}
                }
            }
        }]
    },
    Spec: ServiceSpec {
        Ports: [] ServicePort {
            ServicePort {
                Name: ,
                Protocol: TCP,
                Port: 80,
                TargetPort: {
                    0 80
                },
                NodePort: 30050,
                AppProtocol: nil,
            },
        },
        Selector: map[string] string {
            app: nginx,
        },
        ClusterIP: 10.1 .101 .241,
        Type: NodePort,
        ExternalIPs: [],
        SessionAffinity: None,
        LoadBalancerIP: ,
        LoadBalancerSourceRanges: [],
        ExternalName: ,
        ExternalTrafficPolicy: Cluster,
        HealthCheckNodePort: 0,
        PublishNotReadyAddresses: false,
        SessionAffinityConfig: nil,
        IPFamilyPolicy: * SingleStack,
        ClusterIPs: [10.1 .101 .241],
        IPFamilies: [IPv4],
        AllocateLoadBalancerNodePorts: nil,
        LoadBalancerClass: nil,
        InternalTrafficPolicy: nil,
    },
    Status: ServiceStatus {
        LoadBalancer: LoadBalancerStatus {
            Ingress: [] LoadBalancerIngress {},
        },
        Conditions: [] Condition {},
    },
}

4. Get Service

语法示例

func GetService(clientSet *kubernetes.Clientset,namespaceName string,serviceName string) (serviceInfo *coreV1.Service,err error) {
    serviceInfo,err = clientSet.CoreV1().Services(namespaceName).Get(context.TODO(),serviceName,metaV1.GetOptions{})
    if err != nil {
        return serviceInfo,err
    }
    return serviceInfo,nil
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceInfo,err := crowK8S.GetService(clientSet ,"liubei","nginx")
    fmt.Println(serviceInfo)
}

结果显示

同创建时的结果

5. Update Service

语法

func (ServiceInterface) Update(ctx context.Context, service *v1.Service, opts v1.UpdateOptions) (*v1.Service, error)
serviceInfo,err = clientSet.CoreV1().Services(namespaceName).Update(context.TODO(),service,metaV1.UpdateOptions{})

完整示例

package crowK8S
import (
    "context"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func ApplyServiceByNodePort(clientSet *kubernetes.Clientset,namespaceName string,serviceName string,nodePort int32)(serviceInfo *coreV1.Service,err error)  {
    service,err := clientSet.CoreV1().Services(namespaceName).Get(context.TODO(),serviceName,metaV1.GetOptions{})
    if err !=nil {
        return serviceInfo,err
    }
    service.Spec.Ports[0].NodePort = nodePort
    serviceInfo,err = clientSet.CoreV1().Services(namespaceName).Update(context.TODO(),service,metaV1.UpdateOptions{})
    if err !=nil {
        return serviceInfo,err
    }
    return serviceInfo,nil
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceInfo,err := crowK8S.ApplyServiceByNodePort(clientSet ,"liubei","nginx",30051)
    fmt.Println(serviceInfo)
}

6. Delete Service

语法

func (ServiceInterface) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
err = clientSet.CoreV1().Services(namespaceName).Delete(context.TODO(),serviceName,metaV1.DeleteOptions{})

完整示例

package crowK8S
import (
    "context"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func DeleteService(clientSet *kubernetes.Clientset,namespaceName string,serviceName string)(err error)  {
    err = clientSet.CoreV1().Services(namespaceName).Delete(context.TODO(),serviceName,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.DeleteService(clientSet,"liubei","nginx")
    if err != nil {
        fmt.Println(err)
    }else {
        fmt.Println("删除成功")
    }
}

结果打印

删除成功

以上就是Go语言开发k8s之Service操作解析的详细内容,更多关于Go开发k8s Service操作的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文