Since controllers are in charge of meeting the desired state of the resources in Kubernetes, they somehow need to be informed about the changes on the resources and perform certain operations if needed. For this, controllers follow a special architecture to
- observe the resources,
- inform any events (updating, deleting, adding) done on the resources,
- keep a local cache to decrease the load on API Server,
- keep a work queue to pick up events,
- run workers to perform reconciliation on resources picked up from work queue.
Informer monitors the changes of target resource. An informer is created for each of the target resources if you need to handle multiple resources (e.g. podInformer, deploymentInformer).
1) Initialize the Controller
* The NewController function sets up the Kubernetes controller with a work queue, informer, and WebSocket connection.
* It listens for Deployment events (Add, Update, Delete) and enqueues them.
2) Run the Controller
* The Run method waits for cache synchronization and starts the worker loop.
* It continuously processes events from the work queue.
3) Process Deployment Events
* The processItem method retrieves Deployment events from the queue and determines the necessary action.
* It fetches the Deployment details and handles errors, deletions, and updates.
4) Handle Deployment Changes
* `handleAdd`, `handleUpdate`, and `handleDel` respond to Deployment changes.
* Updates track Replica count and Image changes and send logs via WebSocket.
5) Send Updates via WebSocket
* The updateLogs function logs and sends JSON messages about Deployment changes.
* The WebSocket connection ensures real-time updates for external systems.