Skip to content

Commit

Permalink
Demonstrate with an example (also a functional test)
Browse files Browse the repository at this point in the history
Signed-off-by: Sergey Vasilyev <[email protected]>
  • Loading branch information
nolar committed Mar 27, 2021
1 parent 1a1ea17 commit e89ac21
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 2 deletions.
59 changes: 59 additions & 0 deletions examples/17-admission/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import pathlib
from typing import Dict

import kopf


@kopf.on.startup()
def config(settings: kopf.OperatorSettings, **_):
ROOT = (pathlib.Path.cwd() / pathlib.Path(__file__)).parent.parent.parent
settings.admission.managed = 'auto.kopf.dev'
settings.admission.server = kopf.WebhookK3dServer(cadump=ROOT/'ca.pem')
## Other options (see the docs):
# settings.admission.server = kopf.WebhookServer()
# settings.admission.server = kopf.WebhookServer(certfile=ROOT/'cert.pem', pkeyfile=ROOT/'key.pem', port=1234)
# settings.admission.server = kopf.WebhookK3dServer(cadump=ROOT/'ca.pem')
# settings.admission.server = kopf.WebhookK3dServer(certfile=ROOT/'k3d-cert.pem', pkeyfile=ROOT/'k3d-key.pem', port=1234)
# settings.admission.server = kopf.WebhookMinikubeServer(port=1234, cadump=ROOT/'ca.pem', verify_cafile=ROOT/'client-cert.pem')
# settings.admission.server = kopf.WebhookNgrokTunnel()
# settings.admission.server = kopf.WebhookNgrokTunnel(binary="/usr/local/bin/ngrok", token='...', port=1234)
# settings.admission.server = kopf.WebhookNgrokTunnel(binary="/usr/local/bin/ngrok", port=1234, path='/xyz', region='eu')


@kopf.on.validate('kex')
def authhook(headers, sslpeer, warnings, **_):
# print(f'headers={headers}')
# print(f'sslpeer={sslpeer}')
if not sslpeer:
warnings.append("SSL peer is not identified.")
else:
common_name = None
for key, val in sslpeer['subject'][0]:
if key == 'commonName':
common_name = val
break
else:
warnings.append("SSL peer's common name is absent.")
if common_name is not None:
warnings.append(f"SSL peer is {common_name}.")


@kopf.on.validate('kex')
def validate1(spec, dryrun, **_):
if not dryrun and spec.get('field') == 'wrong':
raise kopf.AdmissionError("Meh! I don't like it. Change the field.")


@kopf.on.validate('kex', field='spec.field', value='not-allowed')
def validate2(**_):
raise kopf.AdmissionError("I'm too lazy anyway. Go away!", code=555)


@kopf.on.mutate('kex', labels={'somelabel': 'somevalue'})
def mutate1(patch: kopf.Patch, **_):
patch.spec['injected'] = 123


# Marks for the e2e tests (see tests/e2e/test_examples.py):
# We do not care: pods can have 6-10 updates here.
E2E_SUCCESS_COUNTS = {} # type: Dict[str, int]
2 changes: 1 addition & 1 deletion examples/99-all-at-once/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
E2E_CREATION_STOP_WORDS = ['Creation is processed:']
E2E_DELETION_STOP_WORDS = ['Deleted, really deleted']
E2E_SUCCESS_COUNTS = {'create_1': 1, 'create_2': 1, 'create_pod': 1, 'delete': 1, 'startup_fn_simple': 1, 'startup_fn_retried': 1, 'cleanup_fn': 1}
E2E_FAILURE_COUNTS: Dict[str, int] = {}
E2E_FAILURE_COUNTS = {} # type: Dict[str, int]
E2E_TRACEBACKS = True


Expand Down
4 changes: 3 additions & 1 deletion kopf/structs/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
from typing import TYPE_CHECKING, Any, Callable, Collection, \
Coroutine, List, NewType, Optional, TypeVar, Union

from kopf.structs import bodies, diffs, ephemera, patches, primitives, references, reviews
from kopf.structs import bodies, configuration, diffs, ephemera, \
patches, primitives, references, reviews

# A specialised type to highlight the purpose or origin of the data of type Any,
# to not be mixed with other arbitrary Any values, where it is indeed "any".
Expand Down Expand Up @@ -44,6 +45,7 @@
# when PEP 612 is released (https://www.python.org/dev/peps/pep-0612/)
ActivityFn = Callable[
[
NamedArg(configuration.OperatorSettings, "settings"),
NamedArg(ephemera.Index, "*"),
NamedArg(int, "retry"),
NamedArg(datetime.datetime, "started"),
Expand Down

0 comments on commit e89ac21

Please sign in to comment.