### Basic Kopf Command-Line Interface Usage Source: https://docs.kopf.dev/en/stable/install Examples demonstrating how to use the Kopf CLI for basic operations, including displaying help messages and running a minimal operator example. ```Shell kopf --help ``` ```Shell kopf run --help ``` ```Shell kopf run examples/01-minimal/example.py ``` -------------------------------- ### Install Kopf Python Package Source: https://docs.kopf.dev/en/stable/install Instructions for installing the Kopf Python library using pip, including options for full authentication support and enhanced I/O performance with uvloop. ```Shell pip install kopf ``` ```Shell pip install kopf[full-auth] ``` ```Shell pip install kopf[uvloop] ``` -------------------------------- ### Start Minikube Cluster and Access Dashboard Source: https://docs.kopf.dev/en/stable/_sources/minikube.rst These commands initiate the Minikube Kubernetes cluster on your local machine. Subsequently, they launch the Minikube dashboard, providing a web-based user interface to manage your cluster. ```bash minikube start minikube dashboard ``` -------------------------------- ### Start Minikube Cluster and Access Dashboard Source: https://docs.kopf.dev/en/stable/minikube This command sequence initiates the Minikube local Kubernetes cluster. After the cluster is running, `minikube dashboard` opens the Kubernetes dashboard in your default web browser, providing a graphical user interface for managing cluster resources. ```bash minikube start minikube dashboard ``` -------------------------------- ### Example log output of a running Kopf operator Source: https://docs.kopf.dev/en/stable/_sources/walkthrough/starting.rst This log snippet captures the console output when the Kopf operator processes an 'EphemeralVolumeClaim' creation event. It shows the operator's internal debugging, finalizer management, handler invocation (`create_fn`), and successful completion of the event. ```none [2019-05-31 10:42:11,870] kopf.config [DEBUG ] configured via kubeconfig file [2019-05-31 10:42:11,913] kopf.reactor.peering [WARNING ] Default peering object is not found, falling back to the standalone mode. [2019-05-31 10:42:12,037] kopf.reactor.handlin [DEBUG ] [default/my-claim] First appearance: {'apiVersion': 'kopf.dev/v1', 'kind': 'EphemeralVolumeClaim', 'metadata': {'annotations': {'kubectl.kubernetes.io/last-applied-configuration': '{"apiVersion":"kopf.dev/v1","kind":"EphemeralVolumeClaim","metadata":{"annotations":{},"name":"my-claim","namespace":"default"}}\n'}, 'creationTimestamp': '2019-05-29T00:41:57Z', 'generation': 1, 'name': 'my-claim', 'namespace': 'default', 'resourceVersion': '47720', 'selfLink': '/apis/kopf.dev/v1/namespaces/default/ephemeralvolumeclaims/my-claim', 'uid': '904c2b9b-81aa-11e9-a202-a6e6b278a294'}} [2019-05-31 10:42:12,038] kopf.reactor.handlin [DEBUG ] [default/my-claim] Adding the finalizer, thus preventing the actual deletion. [2019-05-31 10:42:12,038] kopf.reactor.handlin [DEBUG ] [default/my-claim] Patching with: {'metadata': {'finalizers': ['KopfFinalizerMarker']}} [2019-05-31 10:42:12,165] kopf.reactor.handlin [DEBUG ] [default/my-claim] Creation is in progress: {'apiVersion': 'kopf.dev/v1', 'kind': 'EphemeralVolumeClaim', 'metadata': {'annotations': {'kubectl.kubernetes.io/last-applied-configuration': '{"apiVersion":"kopf.dev/v1","kind":"EphemeralVolumeClaim","metadata":{"annotations":{},"name":"my-claim","namespace":"default"}}\n'}, 'creationTimestamp': '2019-05-29T00:41:57Z', 'finalizers': ['KopfFinalizerMarker'], 'generation': 1, 'name': 'my-claim', 'namespace': 'default', 'resourceVersion': '47732', 'selfLink': '/apis/kopf.dev/v1/namespaces/default/ephemeralvolumeclaims/my-claim', 'uid': '904c2b9b-81aa-11e9-a202-a6e6b278a294'}} [2019-05-31 10:42:12,166] root [INFO ] A handler is called with body: {'apiVersion': 'kopf.dev/v1', 'kind': 'EphemeralVolumeClaim', 'metadata': {'annotations': {'kubectl.kubernetes.io/last-applied-configuration': '{"apiVersion":"kopf.dev/v1","kind":"EphemeralVolumeClaim","metadata":{"annotations":{},"name":"my-claim","namespace":"default"}}\n'}, 'creationTimestamp': '2019-05-29T00:41:57Z', 'finalizers': ['KopfFinalizerMarker'], 'generation': 1, 'name': 'my-claim', 'namespace': 'default', 'resourceVersion': '47732', 'selfLink': '/apis/kopf.dev/v1/namespaces/default/ephemeralvolumeclaims/my-claim', 'uid': '904c2b9b-81aa-11e9-a202-a6e6b278a294'}, 'spec': {}, 'status': {}} [2019-05-31 10:42:12,168] kopf.reactor.handlin [DEBUG ] [default/my-claim] Invoking handler 'create_fn'. [2019-05-31 10:42:12,173] kopf.reactor.handlin [INFO ] [default/my-claim] Handler 'create_fn' succeeded. [2019-05-31 10:42:12,210] kopf.reactor.handlin [INFO ] [default/my-claim] All handlers succeeded for creation. [2019-05-31 10:42:12,223] kopf.reactor.handlin [DEBUG ] [default/my-claim] Patching with: {'status': {'kopf': {'progress': None}}, 'metadata': {'annotations': {'kopf.zalando.org/last-handled-configuration': '{"apiVersion": "kopf.dev/v1", "kind": "EphemeralVolumeClaim", "metadata": {"name": "my-claim", "namespace": "default"}, "spec": {}}'}}} ``` -------------------------------- ### Install and Configure Minikube with Hyperkit on macOS Source: https://docs.kopf.dev/en/stable/_sources/minikube.rst This snippet provides commands to install Minikube and the Hyperkit virtualization driver on macOS using Homebrew. It then configures Minikube to use Hyperkit as its default driver for local Kubernetes cluster creation. ```bash brew install minikube brew install hyperkit minikube start --driver=hyperkit minikube config set driver hyperkit ``` -------------------------------- ### Install Minikube and Hyperkit on macOS Source: https://docs.kopf.dev/en/stable/minikube This snippet demonstrates how to install Minikube and Hyperkit on a macOS system using Homebrew. It then configures Minikube to use Hyperkit as its virtualization driver, which is recommended for performance and integration on macOS. This setup provides an isolated Kubernetes cluster for development. ```bash brew install minikube brew install hyperkit minikube start --driver=hyperkit minikube config set driver hyperkit ``` -------------------------------- ### Kopf Memo Class Usage Examples Source: https://docs.kopf.dev/en/stable/packages/kopf Illustrates how to instantiate and interact with the `kopf.Memo` class, demonstrating attribute-style and dictionary-style access for storing and retrieving values. ```python memo = Memo() memo.f1 = 100 memo['f1'] # ... 100 memo['f2'] = 200 memo.f2 # ... 200 set(memo.keys()) # ... {'f1', 'f2'} ``` -------------------------------- ### Run Kopf Operator in Verbose Mode Source: https://docs.kopf.dev/en/stable/walkthrough/starting This command starts the Kopf operator, running the `ephemeral.py` script in verbose mode. It demonstrates how the operator handles objects that existed before its startup and how it avoids re-handling already processed objects upon restart. ```bash kopf run ephemeral.py --verbose ``` -------------------------------- ### Run Kopf Operator with Verbose Logging Source: https://docs.kopf.dev/en/stable/_sources/walkthrough/starting.rst This command starts the Kopf operator, executing the `ephemeral.py` script. The `--verbose` flag enables detailed logging, which is crucial for observing the operator's internal processes, such as object handling and reconciliation cycles, and for debugging its behavior upon startup or object changes. ```bash kopf run ephemeral.py --verbose ``` -------------------------------- ### Apply Kopf Kubernetes Custom Resources Source: https://docs.kopf.dev/en/stable/install Commands to apply essential Kopf-specific custom resources (peering and CRDs) to a Kubernetes cluster using kubectl, required for non-standalone mode and examples. ```Shell kubectl apply -f https://github.com/nolar/kopf/raw/main/peering.yaml ``` ```Shell kubectl apply -f https://github.com/nolar/kopf/raw/main/examples/crd.yaml ``` -------------------------------- ### Manage Kubectl Context for Minikube Cluster Source: https://docs.kopf.dev/en/stable/_sources/minikube.rst This sequence of commands helps verify and explicitly set the `minikube` context for `kubectl`. It's crucial for ensuring `kubectl` interacts with the correct Minikube cluster, especially when multiple Kubernetes contexts are present. ```bash kubectl config get-contexts kubectl config current-context kubectl config use-context minikube ``` -------------------------------- ### Define a basic Kopf operator for custom resource creation Source: https://docs.kopf.dev/en/stable/_sources/walkthrough/starting.rst This Python snippet illustrates a minimal Kopf operator using the `kopf` library. It defines a handler function `create_fn` decorated with `@kopf.on.create('ephemeralvolumeclaims')` to automatically execute when a new 'ephemeralvolumeclaims' custom resource is created, logging its body. ```python import kopf import logging @kopf.on.create('ephemeralvolumeclaims') def create_fn(body, **kwargs): logging.info(f"A handler is called with body: {body}") ``` -------------------------------- ### Kopf Resource Adoption with pykube-ng Source: https://docs.kopf.dev/en/stable/hierarchies This example shows how to use `kopf.adopt` with `pykube-ng` objects. It initializes a `pykube.HTTPClient`, creates a `pykube.objects.Pod`, and then uses `kopf.adopt` to set the owner reference, ensuring the Pod is managed by the Kopf operator. ```python import kopf import pykube @kopf.on.create('KopfExample') def create_fn(**_): api = pykube.HTTPClient(pykube.KubeConfig.from_env()) pod = pykube.objects.Pod(api, {}) kopf.adopt(pod) ``` -------------------------------- ### Execute a Kopf operator script using kopf CLI Source: https://docs.kopf.dev/en/stable/_sources/walkthrough/starting.rst This bash command demonstrates how to run a Kopf operator script, `ephemeral.py`, from the command line. The `--verbose` flag enables detailed logging, allowing observation of the operator's lifecycle and event processing. ```bash kopf run ephemeral.py --verbose ``` -------------------------------- ### Example Persistent Volume Status Output Source: https://docs.kopf.dev/en/stable/walkthrough/updates This output from `kubectl get pv` shows an example entry for a Persistent Volume (PV). It demonstrates how the `CAPACITY` field reflects the updated size (e.g., '2Gi') after a successful resizing operation orchestrated by the Kopf operator, confirming the PVC's underlying storage has been expanded. ```yaml NAME CAPACITY ACCESS MODES ... pvc-a37b65bd-8384-11e9-b857-42010a800265 2Gi RWO ... ``` -------------------------------- ### Execute a Kopf Operator from the Command Line Source: https://docs.kopf.dev/en/stable/walkthrough/starting This command-line snippet demonstrates how to run a Kopf operator defined in `ephemeral.py` using the `kopf run` command. The `--verbose` flag is used to enable detailed logging, providing insights into the operator's runtime behavior. ```shell kopf run ephemeral.py --verbose ``` -------------------------------- ### Configure Kopf Admission Webhook Server Settings Source: https://docs.kopf.dev/en/stable/admission This Python snippet demonstrates how to configure Kopf's admission webhook server settings based on the environment. It shows an example for local development using `kopf.WebhookK3dServer` for K3d/K3s clusters and a more general production-like setup using `kopf.WebhookServer` for manual configuration. ```Python @kopf.on.startup() def configure(settings: kopf.OperatorSettings, **_): if os.environ.get('ENVIRONMENT') is None: # Only as an example: settings.admission.server = kopf.WebhookK3dServer(port=54321) settings.admission.managed = 'auto.kopf.dev' else: # Assuming that the configuration is done manually: settings.admission.server = kopf.WebhookServer(addr='0.0.0.0', port=8080) settings.admission.managed = 'auto.kopf.dev' ``` -------------------------------- ### Stop and Delete Minikube Cluster Resources Source: https://docs.kopf.dev/en/stable/_sources/minikube.rst These commands are used for cleaning up Minikube resources. `minikube stop` halts the running cluster, while `minikube delete` permanently removes all associated virtual machine and disk resources, freeing up system resources. ```bash minikube stop minikube delete ``` -------------------------------- ### Define a Basic Kopf Operator for Kubernetes Resource Creation Source: https://docs.kopf.dev/en/stable/walkthrough/starting This Python snippet defines a minimal Kubernetes operator using the `kopf` framework. It registers a handler `create_fn` that is triggered upon the creation of `ephemeralvolumeclaims` custom resources, logging the resource's body for debugging. ```python import kopf import logging @kopf.on.create('ephemeralvolumeclaims') def create_fn(body, **kwargs): logging.info(f"A handler is called with body: {body}") ``` -------------------------------- ### Set up and run end-to-end tests with k3d and Pytest Source: https://docs.kopf.dev/en/stable/contributing These commands facilitate setting up a local Kubernetes cluster using k3d and then executing the project's end-to-end (e2e) tests. This allows for comprehensive functional testing against a realistic cluster environment, ensuring the application behaves as expected in a deployed setting. ```shell brew install k3d k3d cluster create pytest --only-e2e ``` -------------------------------- ### Configure Git Upstream Remote for Kopf Source: https://docs.kopf.dev/en/stable/contributing This snippet demonstrates how to add and fetch the 'upstream' remote repository for the Kopf project. This setup is crucial for contributors to easily sync their local forks with the main project repository and pull the latest changes. ```git git remote add upstream git@github.com:nolar/kopf.git git fetch upstream ``` -------------------------------- ### Kopf ConnectionInfo Configuration Parameters Source: https://docs.kopf.dev/en/stable/packages/kopf This documentation details the various parameters available for configuring connection information within the Kopf framework, including authentication credentials, certificate paths, and namespace settings. Each parameter's type and default value (if applicable) are provided for comprehensive setup. ```APIDOC Kopf ConnectionInfo Parameters: ca_data: Optional[bytes] = None ca_path: Optional[str] = None certificate_data: Optional[bytes] = None certificate_path: Optional[str] = None default_namespace: Optional[str] = None expiration: Optional[datetime] = None insecure: Optional[bool] = None password: Optional[str] = None priority: int = 0 private_key_data: Optional[bytes] = None private_key_path: Optional[str] = None scheme: Optional[str] = None token: Optional[str] = None username: Optional[str] = None ``` -------------------------------- ### Run pre-commit hooks for linting and styling Source: https://docs.kopf.dev/en/stable/contributing This command executes pre-commit hooks configured for the repository. It helps maintain consistent code quality by performing linting, minor code styling adjustments, import sorting, and layered module checks before committing changes. ```shell pre-commit run ``` -------------------------------- ### Kopf Python Library Installation and Import Source: https://docs.kopf.dev/en/stable/naming This code snippet illustrates the standard procedure for installing the Kopf Python library using the `pip` package manager and subsequently importing it into a Python application. It demonstrates the lower-cased convention for the library name when used in code. ```Python pip install kopf import kopf ``` -------------------------------- ### Manage Kubectl Context for Minikube Source: https://docs.kopf.dev/en/stable/minikube These commands are used to inspect and switch kubectl contexts. `get-contexts` lists all available Kubernetes contexts, `current-context` shows the active context, and `use-context minikube` explicitly sets the kubectl context to the Minikube cluster, ensuring commands are directed to the correct environment. ```bash kubectl config get-contexts kubectl config current-context kubectl config use-context minikube ``` -------------------------------- ### Illustrate Kopf index structure with example returns Source: https://docs.kopf.dev/en/stable/indexing This snippet illustrates how an index is populated based on return values from indexing functions. It shows that multiple values for the same key are collected into a list, demonstrating the `kopf.Store` collection behavior within the `kopf.Index` mapping. ```python return {'key1': 'valueA'} # 1st return {'key1': 'valueB'} # 2nd return {'key2': 'valueC'} # 3rd # {'key1': ['valueA', 'valueB'], ``` -------------------------------- ### Delete and Re-create Kubernetes Object with Kubectl Source: https://docs.kopf.dev/en/stable/_sources/walkthrough/starting.rst These commands demonstrate how to delete an existing Kubernetes object defined in `obj.yaml` and then immediately re-create it. This sequence is commonly used to force an operator to re-process an object, simulating a new creation event or a significant change, which is valuable for testing operator reactions and reconciliation logic. ```bash kubectl delete -f obj.yaml kubectl apply -f obj.yaml ``` -------------------------------- ### Kubernetes Event Structure via kubectl describe Source: https://docs.kopf.dev/en/stable/events Provides an example of the output format for Kubernetes events as displayed by `kubectl describe`. This output shows the `Type`, `Reason`, `Age`, `From`, and `Message` fields, illustrating how events reported by Kopf are presented to users. ```APIDOC ...Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal SomeReason 5s kopf Some message Normal Success 5s kopf Handler create_fn succeeded. SomeType SomeReason 6s kopf Some message Normal Finished 5s kopf All handlers succeeded. Error SomeReason 5s kopf Some exception: Exception text. Warning SomeReason 5s kopf Some message ``` -------------------------------- ### Build Kopf Operator Docker Image Source: https://docs.kopf.dev/en/stable/deployment This Dockerfile defines the steps to package a Kopf operator into a Docker image. It installs Python and Kopf, copies the handler code, and sets the command to run the operator in verbose mode. ```Dockerfile FROM python:3.13 RUN pip install kopf ADD . /src CMD kopf run /src/handlers.py --verbose ``` -------------------------------- ### Delete and Re-create Kubernetes Object with Kubectl Source: https://docs.kopf.dev/en/stable/walkthrough/starting These commands demonstrate how to delete and then re-create a Kubernetes object defined in `obj.yaml` using `kubectl`. This action simulates a fresh object creation, prompting the operator to react to the object's lifecycle events, useful for testing operator responsiveness. ```bash kubectl delete -f obj.yaml kubectl apply -f obj.yaml ``` -------------------------------- ### Testing a Kopf Operator with KopfRunner Source: https://docs.kopf.dev/en/stable/testing This Python example demonstrates how to use `kopf.testing.KopfRunner` to run a Kopf operator in a separate process while the test script interacts with the Kubernetes cluster. It shows how to apply and delete resources using `kubectl` and then assert the operator's exit code, exceptions, and output after its execution. ```python import time import subprocess from kopf.testing import KopfRunner def test_operator(): with KopfRunner(['run', '-A', '--verbose', 'examples/01-minimal/example.py']) as runner: # do something while the operator is running. subprocess.run("kubectl apply -f examples/obj.yaml", shell=True, check=True) time.sleep(1) # give it some time to react and to sleep and to retry subprocess.run("kubectl delete -f examples/obj.yaml", shell=True, check=True) time.sleep(1) # give it some time to react assert runner.exit_code == 0 assert runner.exception is None assert 'And here we are!' in runner.output assert 'Deleted, really deleted' in runner.output ``` -------------------------------- ### Run local unit tests with Pytest Source: https://docs.kopf.dev/en/stable/contributing This command executes the project's unit tests using Pytest. Running tests locally before submitting a contribution helps developers quickly identify and fix issues, saving time during the continuous integration and review process. ```shell pytest ``` -------------------------------- ### Manage Kubernetes Custom Resource Objects with kubectl Source: https://docs.kopf.dev/en/stable/walkthrough/resources These `kubectl` commands illustrate how to apply and retrieve instances of a custom resource. Applying `obj.yaml` creates a new 'EphemeralVolumeClaim' object, while the `get` commands demonstrate various ways to list existing objects using full names or short aliases defined in the CRD. ```shell kubectl apply -f obj.yaml ``` ```shell kubectl get EphemeralVolumeClaim kubectl get ephemeralvolumeclaims kubectl get ephemeralvolumeclaim kubectl get evcs kubectl get evc ``` -------------------------------- ### Kopf Operator Execution Functions Source: https://docs.kopf.dev/en/stable/packages/kopf Comprehensive API documentation for `kopf.operator` and `kopf.run`, the primary functions used to start and manage a Kopf-based Kubernetes operator. `kopf.operator` runs asynchronously within an event loop, while `kopf.run` provides a synchronous wrapper, handling event loop creation and finalization. ```APIDOC async kopf.operator(*, lifecycle=None, indexers=None, registry=None, settings=None, memories=None, insights=None, identity=None, standalone=None, priority=None, peering_name=None, liveness_endpoint=None, clusterwide=False, namespaces=(), namespace=None, stop_flag=None, ready_flag=None, vault=None, memo=None, _command=None) Description: Run the whole operator asynchronously. This function should be used to run an operator in an asyncio event-loop if the operator is orchestrated explicitly and manually. It is efficiently kopf.spawn_tasks + kopf.run_tasks with some safety. Return type: None Parameters: lifecycle: LifeCycleFn | None indexers: OperatorIndexers | None registry: OperatorRegistry | None settings: OperatorSettings | None memories: ResourceMemories | None insights: Insights | None identity: Identity | None standalone: bool | None priority: int | None peering_name: str | None liveness_endpoint: str | None clusterwide: bool namespaces: Collection[str | Pattern[str]] namespace: str | Pattern[str] | None stop_flag: Future | Event | Future[Any] | Event | None ready_flag: Future | Event | Future[Any] | Event | None vault: Vault | None memo: object | None _command: Coroutine[None, None, None] | None kopf.run(*, loop=None, lifecycle=None, indexers=None, registry=None, settings=None, memories=None, insights=None, identity=None, standalone=None, priority=None, peering_name=None, liveness_endpoint=None, clusterwide=False, namespaces=(), namespace=None, stop_flag=None, ready_flag=None, vault=None, memo=None, _command=None) Description: Run the whole operator synchronously. If the loop is not specified, the operator runs in the event loop of the current context (by asyncio’s default, the current thread). See: https://docs.python.org/3/library/asyncio-policy.html for details. Alternatively, use asyncio.run(kopf.operator(...)) with the same options. It will take care of a new event loop’s creation and finalization for this call. See: asyncio.run(). Return type: None Parameters: loop: AbstractEventLoop | None lifecycle: LifeCycleFn | None indexers: OperatorIndexers | None registry: OperatorRegistry | None settings: OperatorSettings | None memories: ResourceMemories | None insights: Insights | None identity: Identity | None standalone: bool | None priority: int | None peering_name: str | None liveness_endpoint: str | None clusterwide: bool namespaces: Collection[str | Pattern[str]] namespace: str | Pattern[str] | None stop_flag: Future | Event | Future[Any] | Event | None ready_flag: Future | Event | Future[Any] | Event | None vault: Vault | None memo: object | None _command: Coroutine[None, None, None] | None ``` -------------------------------- ### Kopf Webhook Server Configuration API Source: https://docs.kopf.dev/en/stable/genindex API components related to configuring webhook servers in Kopf, including default host settings for various server types and additional Subject Alternative Names (SANs). Detailed attribute types and usage examples are not available in this index. ```APIDOC Attribute: kopf.WebhookK3dServer.DEFAULT_HOST Attribute: kopf.WebhookMinikubeServer.DEFAULT_HOST Attribute: kopf.WebhookServer.DEFAULT_HOST Attribute: kopf.WebhookServer.extra_sans ``` -------------------------------- ### Create and Push a New Git Feature Branch Source: https://docs.kopf.dev/en/stable/contributing This snippet illustrates the process of creating a new local feature branch from the current branch and immediately pushing it to the 'origin' remote. This makes the feature branch available on GitHub for development and eventual pull request creation. ```git git checkout -b feature-x git push origin feature-x ``` -------------------------------- ### Implement Custom Webhook Server with Configurable Class Source: https://docs.kopf.dev/en/stable/admission This example illustrates how to implement a custom webhook server using a Python class. The class must define an `async __call__` method that acts as the async iterator, yielding `kopf.WebhookClientConfig`. This approach allows for passing arguments to the class constructor, making the server configurable. It is registered with `kopf.on.startup` by instantiating the class. ```python class MyTunnel: async def __call__(self, fn: kopf.WebhookFn) -> AsyncIterator[kopf.WebhookClientConfig]: ... yield client_config await asyncio.Event().wait() @kopf.on.startup() def configure(settings: kopf.OperatorSettings, **_): settings.admission.server = MyTunnel() # arguments are possible. ``` -------------------------------- ### Kopf Operator Memo for Background Worker Management Source: https://docs.kopf.dev/en/stable/memos This example illustrates the use of a global operator memo (`kopf.Memo`) to manage shared resources like background threads and queues across the entire operator lifecycle. It shows how to initialize these resources during operator startup and properly clean them up during operator shutdown, ensuring graceful management of long-running tasks. ```python import kopf import queue import threading @kopf.on.startup() def start_background_worker(memo: kopf.Memo, **_): memo.my_queue = queue.Queue() memo.my_thread = threading.Thread(target=background, args=(memo.my_queue,)) memo.my_thread.start() @kopf.on.cleanup() def stop_background_worker(memo: kopf.Memo, **_): memo['my_queue'].put(None) memo['my_thread'].join() def background(queue: queue.Queue): while True: item = queue.get() if item is None: break else: print(item) ``` -------------------------------- ### Configure kopf.WebhookK3dServer Class and DEFAULT_HOST Source: https://docs.kopf.dev/en/stable/packages/kopf Documentation for the `kopf.WebhookK3dServer` class, including its initialization parameters and the `DEFAULT_HOST` attribute. This class manages webhook servers specifically for k3d environments, providing necessary SSL configurations. ```APIDOC class kopf.WebhookK3dServer: Parameters: context (SSLContext | None): SSL context for the server. insecure (bool): Whether to allow insecure connections. certfile (str | PathLike | None): Path to the certificate file. pkeyfile (str | PathLike | None): Path to the private key file. password (str | None): Password for the private key. extra_sans (Iterable[str]): Additional Subject Alternative Names for the certificate. verify_mode (VerifyMode | None): SSL verification mode. verify_cafile (str | PathLike | None): Path to the CA certificate file. verify_capath (str | PathLike | None): Path to the directory containing CA certificates. verify_cadata (str | bytes | None): CA certificate data. DEFAULT_HOST: Optional[str] = 'host.k3d.internal' - Default host for the k3d webhook server. ``` -------------------------------- ### Define Kopf Timer with Sharp Interval Scheduling Source: https://docs.kopf.dev/en/stable/timers This example shows how to create a Kopf timer with a 'sharp' schedule. When `sharp=True`, the timer accounts for the handler's execution time, ensuring the handler is invoked precisely every specified interval from the start of the previous invocation, rather than from its completion. ```python import asyncio import time import kopf @kopf.timer('kopfexamples', interval=1.0, sharp=True) def ping_kex(spec, **kwargs): time.sleep(0.3) ``` -------------------------------- ### Kopf WebhookK3dServer Class Documentation Source: https://docs.kopf.dev/en/stable/packages/kopf Comprehensive documentation for the `kopf.WebhookK3dServer` class, detailing its purpose as a K3d/K3s tunnel and all its constructor parameters for configuring webhook server behavior, including SSL/TLS settings. ```APIDOC class kopf.WebhookK3dServer(**, addr=None, port=None, path=None, host=None, cadata=None, cafile=None, cadump=None, context=None, insecure=False, certfile=None, pkeyfile=None, password=None, extra_sans=(), verify_mode=None, verify_cafile=None, verify_capath=None, verify_cadata=None) Bases: kopf.WebhookServer Description: A tunnel from inside of K3d/K3s to its host where the operator is running. With this tunnel, a developer can develop the webhooks when fully offline, since all the traffic is local and never leaves the host machine. The forwarding is maintained by K3d itself. This tunnel only replaces the endpoints for the Kubernetes webhook and injects an SSL certificate with proper CN/SANs — to match Kubernetes’s SSL validity expectations. Parameters: pkeyfile: Union[str, PathLike, None] - Type: Path to the private key file. password: Optional[str] - Type: Password for the private key file. extra_sans: Iterable[str] - Type: Additional Subject Alternative Names for the certificate. verify_mode: Optional[ssl.VerifyMode] - Type: SSL verification mode. verify_cafile: Union[str, PathLike, None] - Type: Path to a file containing a set of concatenated CA certificates. verify_capath: Union[str, PathLike, None] - Type: Path to a directory containing CA certificates. verify_cadata: Union[str, bytes, None] - Type: String or bytes containing CA certificates. addr: str | None - Type: The address to bind the webhook server to. port: int | None - Type: The port to bind the webhook server to. path: str | None - Type: The URL path for the webhook endpoint. host: str | None - Type: The hostname for the webhook server. cadata: bytes | None - Type: Certificate authority data in bytes. cafile: str | PathLike | None - Type: Path to the certificate authority file. cadump: str | PathLike | None - Type: Path to dump the generated CA certificate. context: Any | None - Type: SSL context object. insecure: bool - Type: If True, disables SSL verification (use with caution). certfile: str | PathLike | None - Type: Path to the SSL certificate file. ``` -------------------------------- ### Example of Kopf Field Diff with Relative Paths Source: https://docs.kopf.dev/en/stable/walkthrough/diffs Demonstrates a Kopf diff object specifically for field handlers, where paths are relative to the handled field (e.g., 'metadata.labels'). This example shows changes to individual labels, such as adding, changing, and removing, using their relative names. ```Python (('add', ('label1',), null, 'new-value'), ('change', ('label2',), 'old-value', 'new-value'), ('remove', ('label3',), 'old-value', null)) ``` -------------------------------- ### Example of Kopf Object Diff with Full Paths Source: https://docs.kopf.dev/en/stable/walkthrough/diffs Illustrates a Kopf diff object showing various changes across different parts of a Kubernetes resource. This example includes adding a label, changing an existing label, removing a label, and modifying a spec field, all with their full paths. ```Python (('add', ('metadata', 'labels', 'label1'), null, 'new-value'), ('change', ('metadata', 'labels', 'label2'), 'old-value', 'new-value'), ('remove', ('metadata', 'labels', 'label3'), 'old-value', null), ('change', ('spec', 'size'), '1G', '2G')) ``` -------------------------------- ### Install Kopf with Development Dependencies Source: https://docs.kopf.dev/en/stable/admission To enable all development-mode features for Kopf's admission webhook servers and tunnels, such as SSL cryptography, certificate generation, and Ngrok integration, install Kopf with the 'dev' extra. Without this, Kopf will not generate self-signed certificates and will run with HTTP only or require externally provided certificates. ```Shell pip install kopf[dev] ``` -------------------------------- ### Kopf Connection Information API Source: https://docs.kopf.dev/en/stable/genindex Attributes providing details about the operator's connection context, such as default namespace and expiration. Detailed attribute types and usage examples are not available in this index. ```APIDOC Attribute: kopf.ConnectionInfo.default_namespace Attribute: kopf.ConnectionInfo.expiration ``` -------------------------------- ### Configure Kopf Operator Custom Finalizer Name Source: https://docs.kopf.dev/en/stable/configuration This example shows how to customize the finalizer name used by Kopf to block resource deletion. Setting `settings.persistence.finalizer` allows operators to use a domain-specific finalizer. ```python import kopf @kopf.on.startup() def configure(settings: kopf.OperatorSettings, **_): settings.persistence.finalizer = 'my-operator.example.com/kopf-finalizer' ``` -------------------------------- ### Configure Kubernetes Event Posting Level in Kopf Source: https://docs.kopf.dev/en/stable/configuration Sets the minimum logging level for messages to be posted as Kubernetes events using `settings.posting.level`. This example configures Kopf to post only messages at or above the `logging.ERROR` level. ```python import logging import kopf @kopf.on.startup() def configure(settings: kopf.OperatorSettings, **_): settings.posting.level = logging.ERROR ``` -------------------------------- ### Define Cluster-scoped Kopf Peering Custom Resource Source: https://docs.kopf.dev/en/stable/peering Example YAML definition for a `ClusterKopfPeering` custom resource. This resource is used by cluster-scoped Kopf operators to communicate with other operators across all namespaces, facilitating inter-operator coordination. ```yaml apiVersion: kopf.dev/v1 kind: ClusterKopfPeering metadata: name: example ``` -------------------------------- ### Configure kopf.WebhookMinikubeServer Class Source: https://docs.kopf.dev/en/stable/packages/kopf Documentation for the `kopf.WebhookMinikubeServer` class, which provides a tunnel from inside Minikube to the host machine for webhook development. It handles SSL certificate injection and Kubernetes webhook endpoint replacement. ```APIDOC class kopf.WebhookMinikubeServer(*, addr=None, port=None, path=None, host=None, cadata=None, cafile=None, cadump=None, context=None, insecure=False, certfile=None, pkeyfile=None, password=None, extra_sans=(), verify_mode=None, verify_cafile=None, verify_capath=None, verify_cadata=None): Bases: WebhookServer Description: A tunnel from inside of Minikube to its host where the operator is running. With this tunnel, a developer can develop the webhooks when fully offline, since all the traffic is local and never leaves the host machine. The forwarding is maintained by Minikube itself. This tunnel only replaces the endpoints for the Kubernetes webhook and injects an SSL certificate with proper CN/SANs — to match Kubernetes’s SSL validity expectations. Parameters: addr (str | None): The address to bind to. port (int | None): The port to listen on. path (str | None): The URL path for the webhook. host (str | None): The host to connect to. cadata (bytes | None): CA certificate data. cafile (str | PathLike | None): Path to the CA certificate file. cadump (str | PathLike | None): Path to dump the CA certificate. context (SSLContext | None): SSL context for the server. insecure (bool): Whether to allow insecure connections. certfile (str | PathLike | None): Path to the certificate file. pkeyfile (str | PathLike | None): Path to the private key file. password (str | None): Password for the private key. extra_sans (Iterable[str]): Additional Subject Alternative Names for the certificate. verify_mode (VerifyMode | None): SSL verification mode. verify_cafile (str | PathLike | None): Path to the CA certificate file. verify_capath (str | PathLike | None): Path to the directory containing CA certificates. verify_cadata (str | bytes | None): CA certificate data. ``` -------------------------------- ### Set Handler Execution Timeout in Kopf Source: https://docs.kopf.dev/en/stable/errors This example shows how to limit the total runtime of a Kopf handler. If the handler does not succeed within the specified timeout, it is considered fatally failed. For asynchronous coroutines, an `asyncio.TimeoutError` is raised. ```python import kopf @kopf.on.create('kopfexamples', timeout=60*60) def create_fn(spec, **_): raise kopf.TemporaryError(delay=60) ``` -------------------------------- ### Kopf Indexing: Indexing by Labels and Querying the Index Source: https://docs.kopf.dev/en/stable/indexing Illustrates indexing Kubernetes pods by their labels, allowing multiple entries for a single resource if it has multiple labels. It also demonstrates how to query the generated `kopf.Index` object within a Kopf timer to retrieve resources based on specific label-value pairs. ```Python import kopf @kopf.index('pods') def by_label(labels, name, **_): return {(label, value): name for label, value in labels.items()} # {('label1', 'value1a'): ['pod1', 'pod2', ...], # ('label1', 'value1b'): ['pod3', 'pod4', ...], # ('label2', 'value2a'): ['pod5', 'pod6', ...], # ('label2', 'value2b'): ['pod1', 'pod3', ...], # ...} @kopf.timer('kex', interval=5) def tick(by_label: kopf.Index, **_): print(list(by_label.get(('label2', 'value2b'), []))) # ['pod1', 'pod3'] for podname in by_label.get(('label2', 'value2b'), []): print(f"==> {podname}") # ==> pod1 # ==> pod3 ``` -------------------------------- ### Define Kopf Timer with Initial Delay and Idle Interval Source: https://docs.kopf.dev/en/stable/timers This example demonstrates how to configure a `kopf.timer` handler with an `initial_delay` for warming up and an `idle` interval to ping resources only when they are unmodified for a specified duration. The `interval` defines the regular ping frequency. ```python import kopf @kopf.timer('kopfexamples', initial_delay=60, interval=10, idle=600) def ping_kex(spec, **kwargs): pass ``` -------------------------------- ### Kopf Core API Reference: Classes, Attributes, and Methods Source: https://docs.kopf.dev/en/stable/genindex Details on core Kopf classes, their configurable attributes, and available methods for managing Kubernetes operators. This includes settings, webhook configurations, owner references, connection info, resource definitions, and progress/diff storage mechanisms. ```APIDOC Classes: kopf.Body: Represents the body of a Kubernetes object. kopf.BodyEssence: Core essence of a Kubernetes object body. kopf.cli.CLIControls: Provides control mechanisms for the Kopf CLI. kopf.ConnectionInfo: Stores connection details for Kubernetes API. Attributes: kopf.OperatorSettings: background: (attribute) batching: (attribute) kopf.WebhookNgrokTunnel: binary: (attribute) kopf.OwnerReference: blockOwnerDeletion: (attribute) controller: (attribute) kopf.ConnectionInfo: ca_data: (attribute) ca_path: (attribute) certificate_data: (attribute) certificate_path: (attribute) kopf.WebhookClientConfig: caBundle: (attribute) kopf.WebhookServer: cadata: (attribute) cadump: (attribute) cafile: (attribute) certfile: (attribute) context: (attribute) kopf.Resource: categories: (attribute) kopf.Meta: creation_timestamp: (property) Methods: kopf.AnnotationsDiffBaseStorage.build(): Builds annotations diff base storage. kopf.DiffBaseStorage.build(): Builds diff base storage. kopf.MultiDiffBaseStorage.build(): Builds multi diff base storage. kopf.StatusDiffBaseStorage.build(): Builds status diff base storage. kopf.WebhookServer.build_certificate(): (static method) Builds a webhook server certificate. kopf.AnnotationsProgressStorage.clear(): Clears annotations progress storage. kopf.MultiProgressStorage.clear(): Clears multi progress storage. kopf.ProgressStorage.clear(): Clears progress storage. kopf.StatusProgressStorage.clear(): Clears status progress storage. kopf.cli.LogFormatParamType.convert(): Converts log format parameter type. ``` -------------------------------- ### Specify Kubernetes Resources Using Keyword Arguments Source: https://docs.kopf.dev/en/stable/resources Shows how to explicitly specify resource names using keyword arguments such as `kind`, `plural`, `singular`, or `shortcut` for more precise and unambiguous matching. ```Python @kopf.on.event(kind='KopfExample') @kopf.on.event(plural='kopfexamples') @kopf.on.event(singular='kopfexample') @kopf.on.event(shortcut='kex') def fn(**_): pass ``` -------------------------------- ### Configure Kopf Login Handler with Retries Source: https://docs.kopf.dev/en/stable/authentication This snippet illustrates how to limit authentication attempts by specifying a `retries` parameter in the `@kopf.on.login()` decorator. This example uses `pykube-ng` and attempts authentication up to 3 times, preventing indefinite retries. ```python import kopf @kopf.on.login(retries=3) def login_fn(**kwargs): return kopf.login_via_pykube(**kwargs) ``` -------------------------------- ### Webhook Request HTTP Headers Example Source: https://docs.kopf.dev/en/stable/admission Illustrates a typical dictionary structure of HTTP headers received by a Kopf webhook, including `Host`, `Authorization` (Basic), `Content-Length`, and `Content-Type`. This data is passed to admission handlers for inspection. ```Python {'Host': 'localhost:54321', 'Authorization': 'Basic dXNzc2VyOnBhc3Nzdw==', # base64("ussser:passsw") 'Content-Length': '844', 'Content-Type': 'application/x-www-form-urlencoded'} ``` -------------------------------- ### Kopf Command-Line Interface (CLI) Options Source: https://docs.kopf.dev/en/stable/genindex Available command-line options for configuring and running Kopf operators, including namespace targeting, logging, and operational modes. ```APIDOC --all-namespaces (-A): Operates across all namespaces. --debug: Enables debug logging. --dev: Enables development mode. --liveness: Configures liveness probe. --log-format: Specifies log output format. --log-prefix: Specifies log prefix. --log-refkey: Specifies log reference key. --module (-m): Specifies the module to load. --namespace (-n): Specifies the namespace to watch. --no-log-prefix: Disables log prefix. --peering: Enables peering mode. --priority: Sets operator priority. --quiet: Suppresses verbose output. --standalone: Runs in standalone mode. --verbose: Enables verbose output. ``` -------------------------------- ### Define Namespace-scoped Kopf Peering Custom Resource Source: https://docs.kopf.dev/en/stable/peering Example YAML definition for a `KopfPeering` custom resource. This resource is used by namespace-scoped Kopf operators to communicate with other operators within a specific namespace, enabling coordination limited to that scope. ```yaml apiVersion: kopf.dev/v1 kind: KopfPeering metadata: namespace: default name: example ```