"""Sidecars: what the node fronts (GRASP git, ncontainer OCI, magpie files,
or anything an operator brings a manifest for), whether each has passed its
self-tests, and a way to run those tests now. The daemon owns the answer -
it is the one that declared or withheld the capability on the descriptor.
`sidecar-manifest` is the offline half: write a starting manifest, lint one,
or run its checks against an endpoint with no node at all - what a developer
does before an operator ever configures it."""
from __future__ import annotations
import argparse
import json
from ..planes.services.sidecars import manifest as manifest_mod
from .base import add_command, fail
TEMPLATE = {
'sidecar': manifest_mod.VERSION,
'name': 'NAME',
'capability': 'https://YOUR-ORIGIN/NAME/1.0',
'endpoint_tag': 'NAME-endpoint',
'checks': [
{'name': 'http', 'method': 'HEAD', 'path': '/'},
{'name': 'PROTOCOL-ROUTE', 'method': 'GET', 'path': '/THE-ROUTE-THE-SPEC-MANDATES',
'expect': [200, 404], 'content_type': 'application/REPLACE-OR-DELETE'},
],
'docs': 'https://YOUR-ORIGIN/docs/NAME',
# How a deployer runs it (ops/roles/meshnode reads this; the node does
# not). Delete the block if the operator always runs it by hand.
'run': {'image': 'ghcr.io/YOUR-ORG/NAME:TAG', 'port': 7864,
'env': {'NAME_LISTEN': '0.0.0.0:7864'}},
}
def _show(r: dict) -> None:
rows = {k: v for k, v in r.items() if isinstance(v, dict)}
if not any(v.get('enabled') for v in rows.values()):
print('No sidecars configured.')
return
for name, v in rows.items():
if not v.get('enabled'):
print('%-11s off' % name)
continue
state = 'VERIFIED' if v.get('verified') else 'not verified'
print('%-11s %-13s %s' % (name, state, v.get('endpoint', '')))
for c in v.get('checks') or []:
why = (' - ' + c['why']) if c.get('why') and not c['ok'] else ''
print(' %-5s %-34s %s%s' % ('ok' if c['ok'] else 'FAIL', c['name'],
c.get('status') if c.get('status') is not None else 'no answer', why))
if r.get('redeclared'):
print('descriptor redeclared')
def _get_sidecar_command(key: str):
from ..planes.services.sidecars.compartment import Sidecars
for c in Sidecars.COMMANDS:
if c.key == key:
return c
raise KeyError(f'Sidecar command {key!r} not found')
from .adapter import CommandDispatcher
SIDECARS_DISPATCHER = CommandDispatcher('sidecars', default_action='status')
SIDECARS_DISPATCHER.add_command('status', _get_sidecar_command('sidecars'), human=_show, timeout=10.0)
SIDECARS_DISPATCHER.add_command('test', _get_sidecar_command('sidecar_test'), human=_show, timeout=60.0)
[docs]def cmd_sidecars(a: argparse.Namespace) -> int:
return SIDECARS_DISPATCHER.dispatch(a)
[docs]def cmd_manifest(a: argparse.Namespace) -> int:
if a.init:
doc = json.loads(json.dumps(TEMPLATE).replace('NAME', a.init))
with open(a.file, 'x', encoding='utf-8') as f:
json.dump(doc, f, indent=2); f.write('\n')
print('wrote %s - replace every CAPITALISED placeholder, then: meshnode sidecar-manifest %s' % (a.file, a.file))
return 0
try:
# Linted as a third party's: the reserved origin is refused even for
# a file that happens to sit in the tree.
from ..planes.services.sidecars.compartment import RESERVED_ORIGIN
s = manifest_mod.load_file(a.file, origin=RESERVED_ORIGIN)
except manifest_mod.ManifestError as e:
fail('not a usable sidecar manifest: %s' % e)
if not a.endpoint:
print('%s: ok - %s declares %s with %d check(s): %s' % (
a.file, s.name, s.capability, len(s.checks), ', '.join(c.name for c in s.checks)))
return 0
from ..planes.services.sidecars import compartment as sidecars_mod
results = [sidecars_mod.run_check(sidecars_mod._http, a.endpoint, c) for c in s.checks]
ok = all(r.ok for r in results)
if a.json:
print(json.dumps({'name': s.name, 'endpoint': a.endpoint, 'verified': ok,
'checks': [r._asdict() for r in results]}, indent=2))
else:
print('%s at %s: %s' % (s.name, a.endpoint, 'VERIFIED' if ok else 'not verified'))
for r in results:
why = (' - ' + r.why) if r.why and not r.ok else ''
print(' %-5s %-34s %s%s' % ('ok' if r.ok else 'FAIL', r.name,
r.status if r.status is not None else 'no answer', why))
return 0 if ok else 1
[docs]class SidecarsCommandProvider:
"""Registers the sidecars commands."""
[docs] @classmethod
def register(cls, sub: argparse._SubParsersAction) -> None:
g = add_command(sub, 'sidecars', cmd_sidecars,
'fronted sidecars (grasp, ncontainer, magpie, ...): self-test results, or run the tests now', js=True)
SIDECARS_DISPATCHER.register_arguments(g, action_choices=('status', 'test'))
m = sub.add_parser('sidecar-manifest',
help='write, lint or try a sidecar manifest with no node (for sidecar authors)')
m.add_argument('file', help='the manifest JSON')
m.add_argument('--init', metavar='NAME', help='write a starting manifest for NAME to FILE and exit')
m.add_argument('--endpoint', help='also run the checks against this URL, exit 1 if any fails')
m.add_argument('--json', action='store_true', help='print the check results as JSON')
m.set_defaults(fn=cmd_manifest)