The ListWatcher component provides core functionality for the Reflector pattern in Kubernetes controllers. This mechenism enables efficient resource synchronization by combining initial list operations with subsequent watch events.
Constructing ListWatcher Instances
ListWatcher objects are created using factory functions that configure their list and watch behaviors:
func CreateListWatcher(client RESTAccessor, resource string, ns string, selector fields.Selector) *ListWatcher {
modifier := func(opts *metav1.ListOptions) {
opts.FieldSelector = selector.String()
}
return CreateFilteredListWatcher(client, resource, ns, modifier)
}
func CreateFilteredListWatcher(client RESTAccessor, resource string, ns string, modifier func(*metav1.ListOptions)) *ListWatcher {
listOperation := func(opts metav1.ListOptions) (runtime.Object, error) {
modifier(&opts)
request := client.Get()
request.Namespace(ns)
request.Resource(resource)
request.VersionedParams(&opts, metav1.ParameterCodec)
return request.Execute(context.TODO()).Retrieve()
}
watchOperation := func(opts metav1.ListOptions) (watch.Interface, error) {
opts.Watch = true
modifier(&opts)
request := client.Get()
request.Namespace(ns)
request.Resource(resource)
request.VersionedParams(&opts, metav1.ParameterCodec)
return request.Watch(context.TODO())
}
return &ListWatcher{
ListOperation: listOperation,
WatchOperation: watchOperation,
}
}
REST Client Integration
The ListWatcher depends on a REST client interface for API communication:
type RESTAccessor interface {
Get() *rest.Request
}
type RESTClient struct {
baseURL *url.URL
apiPath string
contentConfig ClientContentConfig
backoffStrategy func() BackoffManager
rateLimiter flowcontrol.RateLimiter
httpClient *http.Client
}
ListWatcher Structure
The ListWatcher implements the ListerWatcher interface through its dual operations:
type ListWatcher struct {
ListOperation func(metav1.ListOptions) (runtime.Object, error)
WatchOperation func(metav1.ListOptions) (watch.Interface, error)
ChunkingDisabled bool
}
type ListerWatcher interface {
Lister
Watcher
}
type Lister interface {
List(options metav1.ListOptions) (runtime.Object, error)
}
type Watcher interface {
Watch(options metav1.ListOptions) (watch.Interface, error)
}
Core Method Implementations
The List and Watch methods directly invoke their configured operations:
func (lw *ListWatcher) List(opts metav1.ListOptions) (runtime.Object, error) {
return lw.ListOperation(opts)
}
func (lw *ListWatcher) Watch(opts metav1.ListOptions) (watch.Interface, error) {
return lw.WatchOperation(opts)
}