Watch Mechanism
What is Watching?
In Kubernetes, "watching" is a mechanism that allows clients (like the Kubelet, scheduler, or custom controllers) to subscribe to changes in the state of resources. Instead of polling the API server for updates.
How Watching Works
-
Setting Up a Watch:
- A client (e.g., kubelet, scheduler, custom controller) initiates a watch request to the API server for a specific resource or a set of resources.
- The request typically specifies the resource type (e.g., Pods, Nodes, ConfigMaps) and any filtering criteria.
-
Initial List:
- The API server responds with the current state of the specified resources, essentially a snapshot at that point in time.
- This is often called a "list" operation, where the client gets the current items that match the criteria.
-
Watch Stream:
- After providing the initial list, the API server keeps the connection open and sends a stream of updates (events) as they occur.
- These updates can be of different types:
- ADDED: A new resource has been created.
- MODIFIED: An existing resource has been changed.
- DELETED: A resource has been deleted.
-
Handling Events:
- The client processes these events in real-time, updating its local state or taking appropriate actions based on the type of event.
- For example, a kubelet may start new containers, or a scheduler may assign new Pods to nodes.
-
Connection Management:
- The watch connection remains open as long as possible. If the connection is interrupted (e.g., network issues, API server restarts), the client needs to re-establish the watch.
- Kubernetes clients typically include logic to handle reconnections gracefully, resuming from the last known state using a resource version.
Summary
- Watching is a mechanism for subscribing to changes in Kubernetes resources.
- It is initiated by clients making a watch request to the API server.
- The API server provides an initial list and then streams updates in real-time.
- Clients handle these updates to maintain an up-to-date view of the resources and take necessary actions.
- Watching is crucial for efficiency, responsiveness, and scalability in Kubernetes.