Skip to content

Instantly share code, notes, and snippets.

@sub-mod
Forked from songbinliu/Reflector.md
Created December 29, 2019 23:45
Show Gist options
  • Select an option

  • Save sub-mod/fe29ed45e89afdfdbf55613ac120ea0c to your computer and use it in GitHub Desktop.

Select an option

Save sub-mod/fe29ed45e89afdfdbf55613ac120ea0c to your computer and use it in GitHub Desktop.
description the implementation and usage of kubernetes reflector.

Kubernetes Reflector

Reflector is a key components for Kubernetes clients, kube-scheduler and Replication Controller. Reflector is in the middle between client and Kubernetes API-server.

Definition of Reflector

Here is the definition of Reflector. reflector define

As shown in the definition, there are two important compoents of a Reflector:

  • ListerWatcher

    It provides two functions: List and Watch. These two functions will call API-server, and get the Events.

  • Store

    It is usually a in-memory storage, such as HashMap, or Queue(for FIFO). Reflector will add the Events into this Store.

Also, It should be noted that the reflect.Type is usually a Kind of Kubernetes Object, such as Pod, Node.

Example Usage of Reflector

Before going deeper into the implementation of Reflector, let's have a look at how Reflector can be used from a example. This example will watch the changes(including ADD, DELETE, MODIFY) of all the Pods in the Kubernetes cluster, and print out the changes. In addition, it will also print all the names every 30 seconds.

func main() {
	client := getKubeClient()
	if client == nil {
		fmt.Println("failed to get kubeclient")
		return
	}

	stopCh := make(chan struct{})
	store := cache.NewStore(cache.MetaNamespaceKeyFunc)

	//selector := fields.SelectorFromSet(nil)
	selector := fields.Everything()
	namespace := ""
	listWatch := cache.NewListWatchFromClient(client.CoreV1Client.RESTClient(),
		"pods",
		namespace,
		selector)

	r := cache.NewReflector(listWatch, &v1.Pod{}, store, 0)

	r.RunUntil(stopCh)

	for i := 1; i < 20; i++ {
		time.Sleep(30 * time.Second)
		printContent(store.ListKeys())
	}

	time.Sleep(10 * time.Second)
	printContent(store.ListKeys())
	close(stopCh)
}
 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment