官方示例:https://github.com/kubernetes/client-go/blob/master/examples/out-of-cluster-client-configuration/main.go

/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/// Note: the example only works with the code within the same release/branch.
package mainimport ("context""flag""fmt""os""path/filepath""time""k8s.io/apimachinery/pkg/api/errors"metav1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/client-go/kubernetes""k8s.io/client-go/tools/clientcmd"//// Uncomment to load all auth plugins// _ "k8s.io/client-go/plugin/pkg/client/auth"//// Or uncomment to load specific auth plugins// _ "k8s.io/client-go/plugin/pkg/client/auth/azure"// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"// _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"// _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)func main() {var kubeconfig *stringif home := homeDir(); home != "" {kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")} else {kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")}flag.Parse()// use the current context in kubeconfigconfig, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)if err != nil {panic(err.Error())}// create the clientsetclientset, err := kubernetes.NewForConfig(config)if err != nil {panic(err.Error())}for {pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})if err != nil {panic(err.Error())}fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))// Examples for error handling:// - Use helper functions like e.g. errors.IsNotFound()// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Messagenamespace := "default"pod := "example-xxxxx"_, err = clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod, metav1.GetOptions{})if errors.IsNotFound(err) {fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)} else if statusError, isStatus := err.(*errors.StatusError); isStatus {fmt.Printf("Error getting pod %s in namespace %s: %v\n",pod, namespace, statusError.ErrStatus.Message)} else if err != nil {panic(err.Error())} else {fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)}time.Sleep(10 * time.Second)}
}func homeDir() string {if h := os.Getenv("HOME"); h != "" {return h}return os.Getenv("USERPROFILE") // windows
}

https://www.jianshu.com/p/d17f70369c35

Kubernetes的client-go库介绍

client-go的作用

github上client-go官方项目工程

基本介绍

Kubernetes官方从2016年8月份开始,将Kubernetes资源操作相关的核心源码抽取出来,独立出来一个项目Client-go,作为官方提供的Go client。Kubernetes的部分代码也是基于这个client实现的,所以对这个client的质量、性能等方面还是非常有信心的。

client-go是一个调用kubernetes集群资源对象API的客户端,即通过client-go实现对kubernetes集群中资源对象(包括deployment、service、ingress、replicaSet、pod、namespace、node等)的增删改查等操作。大部分对kubernetes进行前置API封装的二次开发都通过client-go这个第三方包来实现。

源码简介

主要package

主要的几个package包的功能说明:

  • kubernetes: 访问 Kubernetes API的一系列的clientset
  • discovery:通过Kubernetes API 进行服务发现
  • dynamic:对任意Kubernetes对象执行通用操作的动态client
  • transport:启动连接和鉴权auth
  • tools/cache:controllers控制器

Client结构

  • RESTClient:RESTClient是最基础的,相当于的底层基础结构,可以直接通过 是RESTClient提供的RESTful方法如Get(),Put(),Post(),Delete()进行交互

    • 同时支持Json 和 protobuf
    • 支持所有原生资源和CRDs
    • 但是,一般而言,为了更为优雅的处理,需要进一步封装,通过Clientset封装RESTClient,然后再对外提供接口和服务
  • Clientset:Clientset是调用Kubernetes资源对象最常用的client,可以操作所有的资源对象,包含RESTClient。需要指定Group、指定Version,然后根据Resource获取

    • 优雅的姿势是利用一个controller对象,再加上Informer
  • DynamicClient:Dynamic client 是一种动态的 client,它能处理 kubernetes 所有的资源。不同于 clientset,dynamic client 返回的对象是一个 map[string]interface{},如果一个 controller 中需要控制所有的 API,可以使用dynamic client,目前它在 garbage collector 和 namespace controller中被使用。

    • 只支持JSON

RESTClient

RESTClient 封装了指定资源URL的通用Kubernetes API的访问姿势

Clientset

/Users/meitu/Documents/work_Meitu/goDev/Applications/src/k8s.io/client-go/kubernetes/clientset.go

Clientset 是一系列的clients的group组合,注意每个group在一个Clientset中只包含一个版本。

Clientset包含了appsV1、coreV1,这中间包含了RESTClient,因此Clientset是基于RESTClient的。

dynamic client

dynamic client针对的是所有资源,但是只支持Json;

主要源码路径在:/Users/meitu/Documents/work_Meitu/goDev/Applications/src/k8s.io/client-go/dynamic

type ResourceInterface interface {Create(obj *unstructured.Unstructured, options metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error)Update(obj *unstructured.Unstructured, options metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error)UpdateStatus(obj *unstructured.Unstructured, options metav1.UpdateOptions) (*unstructured.Unstructured, error)Delete(name string, options *metav1.DeleteOptions, subresources ...string) errorDeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) errorGet(name string, options metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error)List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error)Watch(opts metav1.ListOptions) (watch.Interface, error)Patch(name string, pt types.PatchType, data []byte, options metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error)
}

Informer

Client-go包中一个相对较为高端的设计在于Informer的设计,我们知道我们可以直接通过Kubernetes API交互,但是考虑一点就是交互的形式,Informer设计为List/Watch的方式。Informer在初始化的时先通过List去从Kubernetes API中取出资源的全部object对象,并同时缓存,然后后面通过Watch的机制去监控资源,这样的话,通过Informer及其缓存,我们就可以直接和Informer交互而不是每次都和Kubernetes API交互。

Informer另外一块内容在于提供了事件handler机制,并会触发回调,这样上层应用如Controller就可以基于回调处理具体业务逻辑。因为Informer通过List、Watch机制可以监控到所有资源的所有事件,因此只要给Informer添加ResourceEventHandler 实例的回调函数实例取实现OnAdd(obj interface{}) OnUpdate(oldObj, newObj interface{}) 和 OnDelete(obj interface{})这三个方法,就可以处理好资源的创建、更新和删除操作

Kubernetes中都是各种controller的实现,各种controller都会用到Informer。

对象资源的操作接口

默认的每一种资源对象都有一个interface,封装了对象的CURD方法和list/watch方法

如 Deployment(/文件路径Users/meitu/Documents/work_Meitu/goDev/Applications/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go):

type DeploymentInterface interface {Create(*v1.Deployment) (*v1.Deployment, error)Update(*v1.Deployment) (*v1.Deployment, error)UpdateStatus(*v1.Deployment) (*v1.Deployment, error)Delete(name string, options *metav1.DeleteOptions) errorDeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) errorGet(name string, options metav1.GetOptions) (*v1.Deployment, error)List(opts metav1.ListOptions) (*v1.DeploymentList, error)Watch(opts metav1.ListOptions) (watch.Interface, error)Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Deployment, err error)DeploymentExpansion
}

如Service(文件路径/Users/meitu/Documents/work_Meitu/goDev/Applications/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go)


// ServiceInterface has methods to work with Service resources.
type ServiceInterface interface {Create(*v1.Service) (*v1.Service, error)Update(*v1.Service) (*v1.Service, error)UpdateStatus(*v1.Service) (*v1.Service, error)Delete(name string, options *metav1.DeleteOptions) errorGet(name string, options metav1.GetOptions) (*v1.Service, error)List(opts metav1.ListOptions) (*v1.ServiceList, error)Watch(opts metav1.ListOptions) (watch.Interface, error)Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Service, err error)ServiceExpansion
}

这也就是说明,在Kubernetes中,所有对象资源的操作方式都是统一的,有个interface当做虚基类,包含资源的所有操作方法,然后各个子类继承然后实现它们,子类中的实现定义会针对不同的资源有不同诠释

client-go中的设计思想

client-go 和 controller的架构设计

github上关于client-go的设计有一副概览图如下:

image.png

主要是两大块:

  • client-go组件本身
  • controller上层控制器

上图相对较为复杂,有很多细节,我自己结合源码的理解如下:

image.png

client-go组件

  • Reflector:通过Kubernetes API监控Kubernetes的资源类型

    • 采用List、Watch机制
    • 可以Watch任何资源包括CRD
    • 添加object对象到FIFO队列,然后Informer会从队列里面取数据
  • Informer:controller机制的基础

    • 循环处理object对象

      • 从Reflector取出数据,然后将数据给到Indexer去缓存
    • 提供对象事件的handler接口
  • Indexer:提供object对象的索引,是线程安全的,缓存对象信息

controller组件

  • Informer reference: controller需要创建合适的Informer才能通过Informer reference操作资源对象

  • Indexer reference: controller创建Indexer reference然后去利用索引做相关处理

  • Resource Event Handlers:Informer会回调这些handlers

  • Work queue: Resource Event Handlers被回调后将key写到工作队列

    • 这里的key相当于事件通知,后面根据取出事件后,做后续的处理
  • Process Item:从工作队列中取出key后进行后续处理,具体处理可以通过Indexer reference

  • controller可以直接创建上述两个引用对象去处理,也可以采用工厂模式,官方都有相关示例

参考

Accessing Kubernetes CRDs from the client-go package

client-go under the hood

Kubernetes Deep Dive: Code Generation for CustomResources

kubernetes client-go

Kubernetes Informer 详解

如何用 client-go 拓展 Kubernetes 的 API

Using Kubernetes API from Go

Kubernetes的client-go库介绍相关推荐

  1. 容器编排技术 -- Kubernetes DNS Pod 与 Service 介绍

    容器编排技术 -- Kubernetes DNS Pod 与 Service 介绍 1 介绍 2 怎样获取 DNS 名字? 3 支持的 DNS 模式 3.1 Service 3.1.1 A 记录 3. ...

  2. RobotFramework全部内置库及第三方库介绍,以及安装方法

    RobotFramework全部内置标准库及第三方库介绍,以及安装方法 1.Libraries 1.1 Standard Libraries 内置标准库 1.2 External Libraries ...

  3. Kubernetes Python Client

    一.概述 Kubernetes官方维护的Python客户端client-python, 地址:https://github.com/kubernetes-client/python 安装模块 pip3 ...

  4. 2021年大数据ELK(三):Lucene全文检索库介绍

    全网最详细的大数据ELK文章系列,强烈建议收藏加关注! 新文章都已经列出历史文章目录,帮助大家回顾前面的知识重点. 目录 系列历史文章 一.什么是全文检索 1.结构化数据与非结构化数据 2.搜索结构化 ...

  5. 强化学习(三) - Gym库介绍和使用,Markov决策程序实例,动态规划决策实例

    强化学习(三) - Gym库介绍和使用,Markov决策程序实例,动态规划决策实例 1. 引言 在这个部分补充之前马尔科夫决策和动态规划部分的代码.在以后的内容我会把相关代码都附到相关内容的后面.本部 ...

  6. 实战篇一 python常用模块和库介绍

    # -_-@ coding: utf-8 -_-@ -- Python 常用模块和库介绍 第一部分:json模块介绍 import json 将一个Python数据结构转换为JSON: dict_ = ...

  7. Python进阶11-标准库介绍02

    摘要:Python标准库介绍 Python标准库是Python强大的动力所在,我们已经在前文中有所介绍.由于标准库所涉及的应用很广,所以需要学习一定的背景知识. 硬件原理 这一部份需要了解内存,CPU ...

  8. Python进阶10-标准库介绍01

    摘要:Python标准库介绍 Python的一大好处在于它有一套很有用的标准库(standard library).标准库是随着Python一起安装在你的电脑中的,是Python的一部分 (当然也有特 ...

  9. C++的iostream标准库介绍

    C++的iostream标准库介绍 0 为什么需要iostream 1 iostream: istream 和 ostream 2 fstream: ifstream 和 ofstream 3 str ...

最新文章

  1. R语言data.table导入数据实战:data.table中编写函数并使用SD数据对象
  2. 用到的 git 命令
  3. linux mint 18 mysql_linux mint下mysql中文支持问题
  4. PhotoShop更改图片背景色
  5. php获取服务器类型,php获取服务器操作系统类型的方法
  6. R实现地理位置与经纬度相互转换
  7. Python 中的几种矩阵乘法 np.dot, np.multiply, *【转】
  8. STM32_WS2811驱动
  9. Excel单元格自定义格式的一些基础知识
  10. C语言班主任管家系统
  11. 隐藏在计算机软硬件,隐匿在计算机软硬件背后的语言
  12. 七年级上册计算机工作计划,七年级上册班主任工作计划
  13. 谷歌、领英、汇丰、桥水、联合航空、联合利华、雷克萨斯、Expedia、OYO等公司高管变动情况...
  14. python基础之if嵌套与循环
  15. 网络编程(python语言)
  16. 计算机专业到底该不该考研?
  17. KISSY基础篇乄KISSY之HelloWorld
  18. 网上图书商城系统毕业设计,网上图书销售系统设计与实现,毕业设计论文毕设作品参考
  19. 高中数学必修二平面解析几何之两直线的位置关系(归纳与整理)
  20. 基于JAVA的网上订餐外卖系统(Java+MySQL)

热门文章

  1. linux能记录日志的终端,如何记录Linux终端下的操作日志
  2. mysql 表与表之间的条件比对_十六年老司机笔记:MySQL性能优化之必备技能
  3. 2006. 差的绝对值为 K 的数对数目
  4. 指针06:指针和数组
  5. python大小写转换_python字符串大小写转换
  6. 【bug】掘金md文本解析器bug
  7. vue-cli+webpack在生成的项目中使用bootstrap的方法
  8. spring boot / cloud (二十) 相同服务,发布不同版本,支撑并行的业务需求
  9. kafka-3-故障排错
  10. mysql public owner_OWNER支持配置文件目录的继承