kopf icon indicating copy to clipboard operation
kopf copied to clipboard

Watch resources without update access?

Open jkupferer opened this issue 4 years ago • 2 comments

Custom resources often function as configuration for operators rather than items for the operator to act on. Is it possible with kopf to configure a watch on a resource that the operator does not have access to modify? For example, to watch for configuration changes?

It seems at present this is not possible because kopf always attempts to set the last-handled-configuration annotation.

jkupferer avatar Jul 30 '19 23:07 jkupferer

@jkupferer You can use @kopf.on.event() handlers: https://kopf.readthedocs.io/en/latest/handlers/#event-handlers — these are the "silent spy-handlers" by design, and do not store anything on the objects, just react.


As an advanced move, Kopf can also be embedded into other apps (soon: see #156) — so you can run it in a background thread, while the non-operator-like app runs in the main thread. And maintain a global state from that thread, to be consumed in the main app.

A draft (just for inspiration; not tested):

import asyncio
import threading
import kopf

CONFIG = {}
registry = kopf.GlobalRegistry()
operator = None


@kopf.on.event('example.com', 'v1', 'myconfigs', registry=registry)
def config_changed(name, spec, **_):
    if name == 'my-config-name':
        CONFIG.update(spec or {})


def kopf_thread():
    global operator
    loop = asyncio.get_event_loop()
    operator = kopf.operator(registry=registry)
    try:
        loop.run_until_complete(operator)
    except asyncio.CancelledError:
        pass


def main():
    thread = threading.Thread(target_fn=kopf_thread)
    thread.start()
    # .... do you app ... consume CONFIG ...
    operator.cancel()
    thread.join()

But if you do not need operator-/controller-like behaviour, and you app is not an operator/controller itself, then probably a simple watch-stream from a Kubernetes API client library (kubernetes or pykube-ng) should be sufficient, with no Kopf involved.

nolar avatar Jul 31 '19 10:07 nolar

@nolar Perfect! I'll try it out. Thank you!

jkupferer avatar Jul 31 '19 11:07 jkupferer