开发operator一共分为5步骤
1、创建config
config的创建有两种方式
1、clientcmd.BuildConfigFromFlags
config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile) if err != nil { //访问集群内 inClusterConfig, err := rest.InClusterConfig() if err != nil { log.Fatalln("can't get config") } config = inClusterConfig }
clientcmd.RecommendedHomeFile可以自己指定路径一般为~/.kube/config
2、config,err :=config.GetConfig()
2、创建client
lientset, err := kubernetes.NewForConfig(config) if err != nil { log.Fatalln("can't create client") }
3、创建informer
factory := informers.NewSharedInformerFactory(clientset, 0) serviceInformer := factory.Core().V1().Services() ingressInformer := factory.Networking().V1().Ingresses()
4、add event handler
//注册到eventhandler controller := pkg.NewController(clientset, serviceInformer, ingressInformer) stopCh := make(chan struct{}) factory.Start(stopCh) //等待所有的informer缓存同步 factory.WaitForCacheSync(stopCh)
在注册到eventhandler中,会进行事件的操作,如:
func NewController(client kubernetes.Interface, serviceInformer informer.ServiceInformer, ingressInformer netInformer.IngressInformer) controller { c := controller{ client: client, ingressLister: ingressInformer.Lister(), serviceLister: serviceInformer.Lister(), queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "ingressManager"), } serviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: c.addService, UpdateFunc: c.updateService, }) //cache.Store() ingressInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ DeleteFunc: c.deleteIngress, }) return c }
5、启动informer
controller.Run(stopCh)
6、informer案例
案例1:
案例2: