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

 更新时间:2023年06月21日 14:13:58   作者:开发运维玄德公  
这篇文章主要为大家介绍了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文件对照

以下是边这个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操作的资料请关注脚本之家其它相关文章!

相关文章

  • 在golang中使用Sync.WaitGroup解决等待的问题

    在golang中使用Sync.WaitGroup解决等待的问题

    这篇文章主要介绍了在golang中使用Sync.WaitGroup解决等待的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-04-04
  • golang中的三个点 ''...''的用法示例详解

    golang中的三个点 ''...''的用法示例详解

    这篇文章主要介绍了golang中的三个点 '...' 的用法示例详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • Golang Defer基础操作详解

    Golang Defer基础操作详解

    在golang当中,defer代码块会在函数调用链表中增加一个函数调用。这个函数调用不是普通的函数调用,而是会在函数正常返回,也就是return之后添加一个函数调用。因此,defer通常用来释放函数内部变量
    2022-10-10
  • golang gorm错误处理事务以及日志用法示例

    golang gorm错误处理事务以及日志用法示例

    这篇文章主要为大家介绍了golang gorm错误处理事务以及日志用法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2022-04-04
  • go内存队列list VS slice实现方式对比分析

    go内存队列list VS slice实现方式对比分析

    这篇文章主要为大家介绍了go内存队列list VS slice实现方式对比分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • Go中recover与panic区别详解

    Go中recover与panic区别详解

    这篇文章主要介绍了Go中recover与panic区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • Golang 串口通信的实现示例

    Golang 串口通信的实现示例

    串口通信是一种常见的硬件通信方式,用于在计算机和外部设备之间传输数据,本文主要介绍了Golang 串口通信的实现示例,具有一定的参考价值,感兴趣的可以了解一下
    2024-03-03
  • go语言题解LeetCode674最长连续递增序列

    go语言题解LeetCode674最长连续递增序列

    这篇文章主要为大家介绍了go语言题解LeetCode674最长连续递增序列示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • Golang中如何使用lua进行扩展详解

    Golang中如何使用lua进行扩展详解

    这篇文章主要给大家介绍了关于Golang中如何使用lua进行扩展的相关资料,这是最近在工作中遇到的一个问题,觉着有必要分享出来给大家学习,文中给出了详细的示例,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-10-10
  • 解决goland 导入项目后import里的包报红问题

    解决goland 导入项目后import里的包报红问题

    这篇文章主要介绍了解决goland 导入项目后import里的包报红问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-05-05

最新评论