Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(k8s): serverkit-k8s extension — manage remote clusters via kubectl

Juan Denisbde4647fdc50
diff --git a/backend/tests/test_serverkit_k8s_extension.py b/backend/tests/test_serverkit_k8s_extension.py
new file mode 100644
index 00000000..855386ba
--- /dev/null
+++ b/backend/tests/test_serverkit_k8s_extension.py
@@ -0,0 +1,385 @@
+"""serverkit-k8s extension tests — manifest, models, kubectl engine, service, blueprint.
+
+Loads the builtin the way production does:
+``plugin_service._ensure_builtin_backend_importable`` registers
+``builtin-extensions/serverkit-k8s/backend`` as the dashed package
+``app.plugins.serverkit-k8s``. The models module is imported at module top so
+its ``ext_serverkit_k8s_*`` table registers on ``db.metadata`` before the ``app``
+fixture runs ``db.create_all()``.
+
+Proven here: manifest validity + permissions + entry point + lifecycle keys +
+frontend export; the K8sCluster model (encryption round-trip, ``to_dict`` never
+leaks the kubeconfig, single-default invariant); the kubectl engine (argv build,
+temp-file materialize + guaranteed cleanup, error mapping); the cluster_service
+normalizers turning canned ``kubectl -o json`` into compact UI dicts; and the
+blueprint RBAC + kubectl-availability guards.
+"""
+import importlib
+import json
+import os
+from types import SimpleNamespace
+
+import pytest
+
+from app.services import plugin_service
+
+SLUG = 'serverkit-k8s'
+EXT_DIR = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
+ 'builtin-extensions', SLUG,
+)
+
+
+def _load_ext():
+ assert plugin_service._ensure_builtin_backend_importable(SLUG), (
+ f'builtin extension backend not importable from {EXT_DIR}')
+ models = importlib.import_module(f'app.plugins.{SLUG}.models')
+ kubectl = importlib.import_module(f'app.plugins.{SLUG}.kubectl_service')
+ cluster = importlib.import_module(f'app.plugins.{SLUG}.cluster_service')
+ bp = importlib.import_module(f'app.plugins.{SLUG}.k8s')
+ return models, kubectl, cluster, bp
+
+
+models_mod, kubectl_mod, cluster_mod, bp_mod = _load_ext()
+K8sCluster = models_mod.K8sCluster
+
+
+def _proc(returncode=0, stdout='', stderr=''):
+ return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
+
+
+def _mk_cluster(app, name='c1', kubeconfig='apiVersion: v1\nkind: Config\n', context=None, default=False):
+ from app import db
+ c = K8sCluster(name=name, context=context, is_default=default)
+ c.set_kubeconfig(kubeconfig)
+ db.session.add(c)
+ db.session.commit()
+ return c
+
+
+# ---------------------------------------------------------------------------
+# manifest
+# ---------------------------------------------------------------------------
+def _manifest():
+ with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:
+ return json.load(f)
+
+
+def test_manifest_passes_validator():
+ m = _manifest()
+ assert plugin_service._validate_manifest(m) is True
+ assert m['name'] == SLUG
+ assert m['category'] == 'deployment'
+ assert m['entry_point'] == 'k8s:k8s_bp'
+ assert m['url_prefix'] == '/api/v1/k8s'
+ assert m['models'] == 'models:register'
+ nav = m['contributions']['nav'][0]
+ assert nav['route'] == '/k8s' and nav['id'] == 'k8s'
+ routes = m['contributions']['routes']
+ assert {'path': 'k8s', 'component': 'K8sPage'} in routes
+ assert m['contributions']['page_titles']['/k8s'] == 'Kubernetes'
+
+
+def test_manifest_permissions_are_known():
+ from app.plugins_sdk import permissions as sdk_perms
+ assert sdk_perms.unknown_permissions(_manifest()['permissions']) == []
+
+
+def test_manifest_description_has_no_em_or_en_dash():
+ desc = _manifest().get('description', '')
+ assert '—' not in desc and '–' not in desc
+
+
+def test_lifecycle_hook_keys_resolve():
+ lifecycle = _manifest()['lifecycle']
+ assert set(lifecycle) <= {'install', 'upgrade', 'uninstall'}
+ assert 'install' in lifecycle and 'uninstall' in lifecycle
+ for ref in lifecycle.values():
+ module_name, func_name = ref.split(':')
+ mod = importlib.import_module(f'app.plugins.{SLUG}.{module_name}')
+ assert callable(getattr(mod, func_name, None)), ref
+
+
+def test_entry_point_resolves_to_blueprint():
+ assert getattr(bp_mod, 'k8s_bp', None) is not None
+ assert bp_mod.k8s_bp.name == 'k8s'
+
+
+def test_models_register_returns_model_list():
+ from app import db
+ assert models_mod.register(db) == [K8sCluster]
+
+
+def test_frontend_exports_route_component():
+ index = os.path.join(EXT_DIR, 'frontend', 'index.jsx')
+ if not os.path.isfile(index):
+ pytest.skip('serverkit-k8s frontend/index.jsx not present in this build')
+ with open(index, encoding='utf-8') as f:
+ src = f.read()
+ assert 'export { default as K8sPage }' in src
+ assert 'export default' not in src
+
+
+# ---------------------------------------------------------------------------
+# model
+# ---------------------------------------------------------------------------
+def test_cluster_persists_and_to_dict_hides_kubeconfig(app):
+ c = _mk_cluster(app, name='prod', context='ctx-a')
+ d = c.to_dict()
+ assert d['name'] == 'prod'
+ assert d['context'] == 'ctx-a'
+ # The secret must never appear in the serialized form (any key or value).
+ assert 'kubeconfig' not in d
+ assert 'kubeconfig_encrypted' not in d
+ blob = json.dumps(d)
+ assert 'apiVersion' not in blob
+
+
+def test_kubeconfig_encryption_round_trips(app):
+ secret = 'apiVersion: v1\nclusters:\n- name: x\n'
+ c = _mk_cluster(app, name='enc', kubeconfig=secret)
+ # Round-trips back to plaintext...
+ assert c.get_kubeconfig() == secret
+ # ...and (when a key is configured) is not stored verbatim.
+ from app.utils.crypto import is_encryption_configured
+ if is_encryption_configured():
+ assert c.kubeconfig_encrypted != secret
+
+
+def test_name_is_unique(app):
+ from app import db
+ _mk_cluster(app, name='dup')
+ dupe = K8sCluster(name='dup')
+ dupe.set_kubeconfig('x')
+ db.session.add(dupe)
+ with pytest.raises(Exception):
+ db.session.commit()
+ db.session.rollback()
+
+
+# ---------------------------------------------------------------------------
+# cluster_service CRUD + invariants
+# ---------------------------------------------------------------------------
+def test_create_first_cluster_is_default(app):
+ c = cluster_mod.create_cluster('a', 'kc')
+ assert c.is_default is True
+
+
+def test_set_default_is_exclusive(app):
+ a = cluster_mod.create_cluster('a', 'kc')
+ b = cluster_mod.create_cluster('b', 'kc')
+ assert a.is_default and not b.is_default
+ cluster_mod.set_default(b.id)
+ from app import db
+ db.session.refresh(a)
+ db.session.refresh(b)
+ assert b.is_default and not a.is_default
+
+
+def test_delete_default_promotes_another(app):
+ a = cluster_mod.create_cluster('a', 'kc')
+ b = cluster_mod.create_cluster('b', 'kc')
+ cluster_mod.delete_cluster(a.id) # a was default
+ from app import db
+ db.session.refresh(b)
+ assert b.is_default is True
+
+
+def test_create_rejects_blank_name_and_kubeconfig(app):
+ with pytest.raises(ValueError):
+ cluster_mod.create_cluster('', 'kc')
+ with pytest.raises(ValueError):
+ cluster_mod.create_cluster('x', '')
+
+
+# ---------------------------------------------------------------------------
+# kubectl engine
+# ---------------------------------------------------------------------------
+def test_build_argv_with_and_without_context():
+ no_ctx = SimpleNamespace(context=None)
+ assert kubectl_mod.build_argv(no_ctx, ['get', 'pods']) == ['kubectl', 'get', 'pods']
+ with_ctx = SimpleNamespace(context='prod')
+ assert kubectl_mod.build_argv(with_ctx, ['get', 'nodes']) == [
+ 'kubectl', '--context', 'prod', 'get', 'nodes']
+
+
+def test_run_materializes_kubeconfig_and_cleans_up(monkeypatch, app):
+ c = _mk_cluster(app, name='run', kubeconfig='THE-CONFIG')
+ monkeypatch.setattr(kubectl_mod, 'is_available', lambda: True)
+
+ seen = {}
+
+ def fake_run(argv, **kwargs):
+ # --kubeconfig <path> is appended; capture it and prove the file exists now.
+ assert '--kubeconfig' in argv
+ path = argv[argv.index('--kubeconfig') + 1]
+ seen['path'] = path
+ with open(path, encoding='utf-8') as f:
+ seen['contents'] = f.read()
+ return _proc(returncode=0, stdout='ok')
+
+ monkeypatch.setattr(kubectl_mod.subprocess, 'run', fake_run)
+ out = kubectl_mod.run(c, ['version'])
+ assert out == 'ok'
+ assert seen['contents'] == 'THE-CONFIG'
+ # Temp kubeconfig is deleted after the call regardless of success.
+ assert not os.path.exists(seen['path'])
+
+
+def test_run_raises_kubectlerror_on_nonzero(monkeypatch, app):
+ c = _mk_cluster(app, name='err')
+ monkeypatch.setattr(kubectl_mod, 'is_available', lambda: True)
+ monkeypatch.setattr(kubectl_mod.subprocess, 'run',
+ lambda argv, **kw: _proc(returncode=1, stderr='boom'))
+ with pytest.raises(kubectl_mod.KubectlError) as ei:
+ kubectl_mod.run(c, ['get', 'pods'])
+ assert 'boom' in str(ei.value)
+
+
+def test_run_raises_when_kubectl_absent(monkeypatch, app):
+ c = _mk_cluster(app, name='absent')
+ monkeypatch.setattr(kubectl_mod, 'is_available', lambda: False)
+ with pytest.raises(kubectl_mod.KubectlError):
+ kubectl_mod.run(c, ['version'])
+
+
+# ---------------------------------------------------------------------------
+# cluster_service normalizers (canned kubectl -o json)
+# ---------------------------------------------------------------------------
+def _patch_json(monkeypatch, payload):
+ monkeypatch.setattr(cluster_mod.kubectl_service, 'run_json', lambda cluster, args, **kw: payload)
+
+
+NODE_JSON = {'items': [{
+ 'metadata': {'name': 'node-1', 'labels': {'node-role.kubernetes.io/control-plane': ''}},
+ 'status': {
+ 'conditions': [{'type': 'Ready', 'status': 'True'}],
+ 'nodeInfo': {'kubeletVersion': 'v1.29.0', 'osImage': 'Ubuntu 22.04'},
+ 'capacity': {'cpu': '4', 'memory': '8Gi'},
+ },
+}]}
+
+POD_JSON = {'items': [{
+ 'metadata': {'name': 'web-abc', 'namespace': 'default'},
+ 'spec': {'nodeName': 'node-1', 'containers': [{'name': 'web'}]},
+ 'status': {'phase': 'Running', 'podIP': '10.0.0.5',
+ 'containerStatuses': [{'ready': True, 'restartCount': 2}]},
+}]}
+
+DEPLOY_JSON = {'items': [{
+ 'metadata': {'name': 'web', 'namespace': 'default'},
+ 'spec': {'replicas': 3, 'template': {'spec': {'containers': [{'image': 'nginx:1.25'}]}}},
+ 'status': {'readyReplicas': 3, 'availableReplicas': 3},
+}]}
+
+
+def test_get_nodes_normalizes(monkeypatch, app):
+ c = _mk_cluster(app)
+ _patch_json(monkeypatch, NODE_JSON)
+ nodes = cluster_mod.get_nodes(c)
+ assert nodes[0]['name'] == 'node-1'
+ assert nodes[0]['ready'] is True
+ assert 'control-plane' in nodes[0]['roles']
+ assert nodes[0]['kubelet_version'] == 'v1.29.0'
+ assert nodes[0]['cpu'] == '4'
+
+
+def test_get_pods_normalizes(monkeypatch, app):
+ c = _mk_cluster(app)
+ _patch_json(monkeypatch, POD_JSON)
+ pods = cluster_mod.get_pods(c, 'default')
+ assert pods[0]['name'] == 'web-abc'
+ assert pods[0]['ready'] == '1/1'
+ assert pods[0]['restarts'] == 2
+ assert pods[0]['phase'] == 'Running'
+
+
+def test_get_workloads_marks_healthy(monkeypatch, app):
+ c = _mk_cluster(app)
+ _patch_json(monkeypatch, DEPLOY_JSON)
+ w = cluster_mod.get_workloads(c, 'default', 'deployment')
+ assert w[0]['name'] == 'web'
+ assert w[0]['desired'] == 3 and w[0]['ready'] == 3
+ assert w[0]['healthy'] is True
+ assert w[0]['images'] == ['nginx:1.25']
+
+
+def test_scale_rejects_negative(monkeypatch, app):
+ c = _mk_cluster(app)
+ monkeypatch.setattr(cluster_mod.kubectl_service, 'run', lambda *a, **kw: '')
+ with pytest.raises(ValueError):
+ cluster_mod.scale_deployment(c, 'default', 'web', -1)
+
+
+def test_delete_resource_rejects_unknown_kind(monkeypatch, app):
+ c = _mk_cluster(app)
+ monkeypatch.setattr(cluster_mod.kubectl_service, 'run', lambda *a, **kw: '')
+ with pytest.raises(ValueError):
+ cluster_mod.delete_resource(c, 'namespace', 'kube-system', 'kube-system')
+
+
+def test_apply_rejects_empty_manifest(app):
+ c = _mk_cluster(app)
+ with pytest.raises(ValueError):
+ cluster_mod.apply_manifest(c, ' ')
+
+
+def test_test_connection_caches_result(monkeypatch, app):
+ c = _mk_cluster(app, name='probe')
+ monkeypatch.setattr(cluster_mod.kubectl_service, 'run_json',
+ lambda cluster, args, **kw: {'serverVersion': {'gitVersion': 'v1.29.3'}})
+ res = cluster_mod.test_connection(c)
+ assert res['ok'] is True and res['server_version'] == 'v1.29.3'
+ assert c.last_reachable is True
+ assert json.loads(c.last_status)['server_version'] == 'v1.29.3'
+
+
+def test_test_connection_records_unreachable(monkeypatch, app):
+ c = _mk_cluster(app, name='down')
+
+ def boom(cluster, args, **kw):
+ raise kubectl_mod.KubectlError('connection refused')
+ monkeypatch.setattr(cluster_mod.kubectl_service, 'run_json', boom)
+ res = cluster_mod.test_connection(c)
+ assert res['ok'] is False
+ assert 'refused' in res['error']
+ assert c.last_reachable is False
+
+
+# ---------------------------------------------------------------------------
+# blueprint (RBAC + kubectl guard)
+# ---------------------------------------------------------------------------
+def k8s_client(app):
+ """Register the extension blueprint on the test app and return a client."""
+ if 'k8s' not in app.blueprints:
+ app.register_blueprint(bp_mod.k8s_bp, url_prefix='/api/v1/k8s')
+ return app.test_client()
+
+
+def test_status_route_lists_clusters(monkeypatch, k8s_client, auth_headers, app):
+ _mk_cluster(app, name='s1', default=True)
+ monkeypatch.setattr(bp_mod.kubectl_service, 'is_available', lambda: True)
+ r = k8s_client.get('/api/v1/k8s/status', headers=auth_headers)
+ assert r.status_code == 200
+ body = r.get_json()
+ assert body['kubectl_available'] is True
+ assert any(c['name'] == 's1' for c in body['clusters'])
+
+
+def test_read_route_503_when_kubectl_absent(monkeypatch, k8s_client, auth_headers, app):
+ c = _mk_cluster(app, name='nok')
+ monkeypatch.setattr(bp_mod.kubectl_service, 'is_available', lambda: False)
+ r = k8s_client.get(f'/api/v1/k8s/clusters/{c.id}/nodes', headers=auth_headers)
+ assert r.status_code == 503
+
+
+def test_routes_require_auth(k8s_client):
+ assert k8s_client.get('/api/v1/k8s/status').status_code in (401, 422)
+
+
+def test_create_cluster_route(monkeypatch, k8s_client, auth_headers):
+ r = k8s_client.post('/api/v1/k8s/clusters', headers=auth_headers,
+ json={'name': 'viaroute', 'kubeconfig': 'kc-blob'})
+ assert r.status_code == 201
+ assert r.get_json()['name'] == 'viaroute'
diff --git a/builtin-extensions/serverkit-k8s/backend/__init__.py b/builtin-extensions/serverkit-k8s/backend/__init__.py
new file mode 100644
index 00000000..c7cb3d27
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/backend/__init__.py
@@ -0,0 +1,4 @@
+"""ServerKit Kubernetes extension backend package (kubectl engine)."""
+from .k8s import k8s_bp
+
+__all__ = ['k8s_bp']
diff --git a/builtin-extensions/serverkit-k8s/backend/cluster_service.py b/builtin-extensions/serverkit-k8s/backend/cluster_service.py
new file mode 100644
index 00000000..d2ba464f
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/backend/cluster_service.py
@@ -0,0 +1,365 @@
+"""High-level operations for the serverkit-k8s extension.
+
+This is the layer the blueprint calls. It owns:
+
+- CRUD for saved cluster connections (:class:`K8sCluster` rows), including the
+ single-default invariant.
+- ``test_connection`` -- probe ``kubectl version`` and cache the result on the row.
+- Read helpers (nodes, namespaces, workloads, pods, logs, services, ingresses,
+ overview) that run ``kubectl get ... -o json`` and **normalize** the verbose
+ Kubernetes objects down to the small flat dicts the UI actually consumes.
+- Mutations (scale, restart, delete, apply) as thin ``kubectl`` wrappers.
+
+Nothing here trusts the cluster to stay reachable: every read that hits the
+cluster is wrapped by the blueprint and surfaces a clean error rather than a
+stack trace.
+"""
+import json
+import logging
+from datetime import datetime
+
+from app import db
+
+from .models import K8sCluster
+from . import kubectl_service
+from .kubectl_service import KubectlError
+
+logger = logging.getLogger(__name__)
+
+
+# --------------------------------------------------------------------------
+# CRUD
+# --------------------------------------------------------------------------
+def list_clusters():
+ return [c.to_dict() for c in K8sCluster.query.order_by(K8sCluster.name.asc()).all()]
+
+
+def get_cluster(cluster_id):
+ return K8sCluster.query.get(cluster_id)
+
+
+def get_default_cluster():
+ return (K8sCluster.query.filter_by(is_default=True).first()
+ or K8sCluster.query.order_by(K8sCluster.id.asc()).first())
+
+
+def create_cluster(name, kubeconfig, context=None, make_default=False):
+ name = (name or '').strip()
+ if not name:
+ raise ValueError('A cluster name is required.')
+ if not (kubeconfig or '').strip():
+ raise ValueError('A kubeconfig is required.')
+ if K8sCluster.query.filter_by(name=name).first():
+ raise ValueError(f'A cluster named "{name}" already exists.')
+
+ cluster = K8sCluster(name=name, context=(context or None) or None)
+ cluster.set_kubeconfig(kubeconfig)
+
+ # First cluster is default automatically; otherwise honor the flag.
+ if make_default or K8sCluster.query.count() == 0:
+ _clear_default()
+ cluster.is_default = True
+
+ db.session.add(cluster)
+ db.session.commit()
+ return cluster
+
+
+def update_cluster(cluster_id, name=None, kubeconfig=None, context=None):
+ cluster = get_cluster(cluster_id)
+ if not cluster:
+ raise ValueError('Cluster not found.')
+ if name is not None:
+ name = name.strip()
+ if not name:
+ raise ValueError('A cluster name is required.')
+ existing = K8sCluster.query.filter_by(name=name).first()
+ if existing and existing.id != cluster.id:
+ raise ValueError(f'A cluster named "{name}" already exists.')
+ cluster.name = name
+ if kubeconfig is not None and kubeconfig.strip():
+ cluster.set_kubeconfig(kubeconfig)
+ if context is not None:
+ cluster.context = context.strip() or None
+ db.session.commit()
+ return cluster
+
+
+def delete_cluster(cluster_id):
+ cluster = get_cluster(cluster_id)
+ if not cluster:
+ raise ValueError('Cluster not found.')
+ was_default = cluster.is_default
+ db.session.delete(cluster)
+ db.session.commit()
+ # Promote another cluster to default if we removed the default one.
+ if was_default:
+ nxt = K8sCluster.query.order_by(K8sCluster.id.asc()).first()
+ if nxt:
+ nxt.is_default = True
+ db.session.commit()
+ return True
+
+
+def set_default(cluster_id):
+ cluster = get_cluster(cluster_id)
+ if not cluster:
+ raise ValueError('Cluster not found.')
+ _clear_default()
+ cluster.is_default = True
+ db.session.commit()
+ return cluster
+
+
+def _clear_default():
+ for c in K8sCluster.query.filter_by(is_default=True).all():
+ c.is_default = False
+
+
+# --------------------------------------------------------------------------
+# Connectivity
+# --------------------------------------------------------------------------
+def test_connection(cluster):
+ """Probe the cluster and cache the result on the row. Never raises."""
+ result = {'ok': False, 'server_version': None, 'error': None}
+ try:
+ data = kubectl_service.run_json(cluster, ['version', '-o', 'json'], timeout=15)
+ server = (data or {}).get('serverVersion') or {}
+ version = server.get('gitVersion')
+ if not version:
+ raise KubectlError('cluster did not report a server version (unreachable?)')
+ result['ok'] = True
+ result['server_version'] = version
+ except KubectlError as e:
+ result['error'] = str(e)
+ except Exception as e: # noqa: BLE001 - defensive: never let a probe crash the request
+ result['error'] = str(e)
+
+ cluster.last_reachable = result['ok']
+ cluster.last_status = json.dumps({'server_version': result['server_version'], 'error': result['error']})
+ cluster.last_checked_at = datetime.utcnow()
+ db.session.commit()
+ return result
+
+
+# --------------------------------------------------------------------------
+# Reads (normalized)
+# --------------------------------------------------------------------------
+def _items(cluster, args):
+ data = kubectl_service.run_json(cluster, args)
+ return (data or {}).get('items', []) or []
+
+
+def _ns_args(namespace):
+ if namespace and namespace != 'all':
+ return ['-n', namespace]
+ return ['--all-namespaces']
+
+
+def get_nodes(cluster):
+ out = []
+ for n in _items(cluster, ['get', 'nodes', '-o', 'json']):
+ meta = n.get('metadata', {})
+ status = n.get('status', {})
+ conditions = {c.get('type'): c.get('status') for c in status.get('conditions', [])}
+ ready = conditions.get('Ready') == 'True'
+ info = status.get('nodeInfo', {})
+ roles = [k.split('/', 1)[1] for k in meta.get('labels', {})
+ if k.startswith('node-role.kubernetes.io/')]
+ out.append({
+ 'name': meta.get('name'),
+ 'ready': ready,
+ 'roles': roles or ['worker'],
+ 'kubelet_version': info.get('kubeletVersion'),
+ 'os_image': info.get('osImage'),
+ 'kernel_version': info.get('kernelVersion'),
+ 'container_runtime': info.get('containerRuntimeVersion'),
+ 'cpu': status.get('capacity', {}).get('cpu'),
+ 'memory': status.get('capacity', {}).get('memory'),
+ 'created_at': meta.get('creationTimestamp'),
+ })
+ return out
+
+
+def get_namespaces(cluster):
+ out = []
+ for ns in _items(cluster, ['get', 'namespaces', '-o', 'json']):
+ meta = ns.get('metadata', {})
+ out.append({
+ 'name': meta.get('name'),
+ 'phase': ns.get('status', {}).get('phase'),
+ 'created_at': meta.get('creationTimestamp'),
+ })
+ return out
+
+
+_WORKLOAD_KINDS = {
+ 'deployment': 'deployments',
+ 'statefulset': 'statefulsets',
+ 'daemonset': 'daemonsets',
+}
+
+
+def get_workloads(cluster, namespace='all', kind='deployment'):
+ resource = _WORKLOAD_KINDS.get(kind, 'deployments')
+ out = []
+ for w in _items(cluster, ['get', resource] + _ns_args(namespace) + ['-o', 'json']):
+ meta = w.get('metadata', {})
+ spec = w.get('spec', {})
+ status = w.get('status', {})
+ if resource == 'daemonsets':
+ desired = status.get('desiredNumberScheduled', 0)
+ ready = status.get('numberReady', 0)
+ else:
+ desired = spec.get('replicas', 0)
+ ready = status.get('readyReplicas', 0) or 0
+ out.append({
+ 'name': meta.get('name'),
+ 'namespace': meta.get('namespace'),
+ 'kind': kind,
+ 'desired': desired,
+ 'ready': ready,
+ 'available': status.get('availableReplicas', ready) if resource != 'daemonsets' else status.get('numberAvailable', ready),
+ 'healthy': bool(desired) and ready == desired,
+ 'images': [c.get('image') for c in spec.get('template', {}).get('spec', {}).get('containers', [])],
+ 'created_at': meta.get('creationTimestamp'),
+ })
+ return out
+
+
+def get_pods(cluster, namespace='all'):
+ out = []
+ for p in _items(cluster, ['get', 'pods'] + _ns_args(namespace) + ['-o', 'json']):
+ meta = p.get('metadata', {})
+ status = p.get('status', {})
+ container_statuses = status.get('containerStatuses', []) or []
+ restarts = sum(cs.get('restartCount', 0) for cs in container_statuses)
+ ready_count = sum(1 for cs in container_statuses if cs.get('ready'))
+ total = len(container_statuses) or len(p.get('spec', {}).get('containers', []))
+ out.append({
+ 'name': meta.get('name'),
+ 'namespace': meta.get('namespace'),
+ 'phase': status.get('phase'),
+ 'ready': f'{ready_count}/{total}',
+ 'restarts': restarts,
+ 'node': p.get('spec', {}).get('nodeName'),
+ 'pod_ip': status.get('podIP'),
+ 'containers': [c.get('name') for c in p.get('spec', {}).get('containers', [])],
+ 'created_at': meta.get('creationTimestamp'),
+ })
+ return out
+
+
+def get_pod_logs(cluster, namespace, pod, container=None, tail=200):
+ args = ['logs', pod, '-n', namespace, '--tail', str(int(tail))]
+ if container:
+ args += ['-c', container]
+ return kubectl_service.run(cluster, args, timeout=30)
+
+
+def get_services(cluster, namespace='all'):
+ out = []
+ for s in _items(cluster, ['get', 'services'] + _ns_args(namespace) + ['-o', 'json']):
+ meta = s.get('metadata', {})
+ spec = s.get('spec', {})
+ ports = ['{}/{}'.format(p.get('port'), p.get('protocol', 'TCP')) for p in spec.get('ports', [])]
+ ingress = s.get('status', {}).get('loadBalancer', {}).get('ingress', []) or []
+ external = ', '.join(filter(None, [i.get('ip') or i.get('hostname') for i in ingress])) or None
+ out.append({
+ 'name': meta.get('name'),
+ 'namespace': meta.get('namespace'),
+ 'type': spec.get('type'),
+ 'cluster_ip': spec.get('clusterIP'),
+ 'external_ip': external,
+ 'ports': ports,
+ 'created_at': meta.get('creationTimestamp'),
+ })
+ return out
+
+
+def get_ingresses(cluster, namespace='all'):
+ out = []
+ for ing in _items(cluster, ['get', 'ingresses'] + _ns_args(namespace) + ['-o', 'json']):
+ meta = ing.get('metadata', {})
+ spec = ing.get('spec', {})
+ hosts = [r.get('host') for r in spec.get('rules', []) if r.get('host')]
+ out.append({
+ 'name': meta.get('name'),
+ 'namespace': meta.get('namespace'),
+ 'class': spec.get('ingressClassName'),
+ 'hosts': hosts,
+ 'created_at': meta.get('creationTimestamp'),
+ })
+ return out
+
+
+def get_overview(cluster):
+ """A compact dashboard payload. Best-effort; partial data on partial failure."""
+ overview = {
+ 'cluster': cluster.to_dict(),
+ 'reachable': False,
+ 'server_version': None,
+ 'counts': {'nodes': 0, 'nodes_ready': 0, 'namespaces': 0, 'pods': 0, 'pods_running': 0, 'deployments': 0},
+ 'error': None,
+ }
+ conn = test_connection(cluster)
+ overview['reachable'] = conn['ok']
+ overview['server_version'] = conn['server_version']
+ if not conn['ok']:
+ overview['error'] = conn['error']
+ return overview
+ try:
+ nodes = get_nodes(cluster)
+ namespaces = get_namespaces(cluster)
+ pods = get_pods(cluster, 'all')
+ deployments = get_workloads(cluster, 'all', 'deployment')
+ overview['counts'] = {
+ 'nodes': len(nodes),
+ 'nodes_ready': sum(1 for n in nodes if n['ready']),
+ 'namespaces': len(namespaces),
+ 'pods': len(pods),
+ 'pods_running': sum(1 for p in pods if p['phase'] == 'Running'),
+ 'deployments': len(deployments),
+ }
+ except KubectlError as e:
+ overview['error'] = str(e)
+ return overview
+
+
+# --------------------------------------------------------------------------
+# Mutations
+# --------------------------------------------------------------------------
+def scale_deployment(cluster, namespace, name, replicas):
+ replicas = int(replicas)
+ if replicas < 0:
+ raise ValueError('replicas must be >= 0')
+ kubectl_service.run(
+ cluster,
+ ['scale', 'deployment', name, '-n', namespace, f'--replicas={replicas}'],
+ )
+ return {'name': name, 'namespace': namespace, 'replicas': replicas}
+
+
+def restart_deployment(cluster, namespace, name):
+ kubectl_service.run(cluster, ['rollout', 'restart', 'deployment', name, '-n', namespace])
+ return {'name': name, 'namespace': namespace, 'restarted': True}
+
+
+_DELETABLE_KINDS = {'pod', 'deployment', 'statefulset', 'daemonset', 'service', 'ingress'}
+
+
+def delete_resource(cluster, kind, name, namespace):
+ kind = (kind or '').lower()
+ if kind not in _DELETABLE_KINDS:
+ raise ValueError(f'Refusing to delete unsupported resource kind "{kind}".')
+ if not name or not namespace:
+ raise ValueError('name and namespace are required.')
+ kubectl_service.run(cluster, ['delete', kind, name, '-n', namespace])
+ return {'kind': kind, 'name': name, 'namespace': namespace, 'deleted': True}
+
+
+def apply_manifest(cluster, manifest_text):
+ if not (manifest_text or '').strip():
+ raise ValueError('An empty manifest cannot be applied.')
+ out = kubectl_service.run(cluster, ['apply', '-f', '-'], input_text=manifest_text, timeout=60)
+ return {'output': out.strip()}
diff --git a/builtin-extensions/serverkit-k8s/backend/k8s.py b/builtin-extensions/serverkit-k8s/backend/k8s.py
new file mode 100644
index 00000000..7d67087d
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/backend/k8s.py
@@ -0,0 +1,277 @@
+"""Kubernetes API endpoints (serverkit-k8s extension).
+
+Mounted under ``/api/v1/k8s`` via the manifest's ``url_prefix``. Thin routing
+layer over :mod:`cluster_service` -- all kubectl work happens there. Reads need
+viewer, mutations need admin (same split as the serverkit-mail and
+serverkit-dns-server extensions).
+
+Cluster CRUD works even when ``kubectl`` is absent so an operator can stage a
+connection first; only routes that actually talk to a cluster are guarded by
+``_kubectl_or_error`` (503 when the binary is missing).
+"""
+from flask import Blueprint, jsonify, request
+
+from app.middleware.rbac import admin_required, viewer_required
+
+from . import cluster_service
+from . import kubectl_service
+from .kubectl_service import KubectlError
+
+k8s_bp = Blueprint('k8s', __name__)
+
+
+def _kubectl_or_error():
+ if not kubectl_service.is_available():
+ return jsonify({
+ 'error': 'kubectl is not installed on the panel host. Install kubectl '
+ 'to talk to clusters.'
+ }), 503
+ return None
+
+
+def _cluster_or_404(cluster_id):
+ return cluster_service.get_cluster(cluster_id)
+
+
+def _kubectl_call(fn):
+ """Run a cluster read/mutation, converting KubectlError to a clean 502."""
+ try:
+ return jsonify(fn())
+ except KubectlError as e:
+ return jsonify({'error': str(e)}), 502
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+
+
+# --------------------------------------------------------------------------
+# Status + cluster CRUD (no kubectl required)
+# --------------------------------------------------------------------------
+@k8s_bp.route('/status', methods=['GET'])
+@viewer_required
+def status():
+ default = cluster_service.get_default_cluster()
+ return jsonify({
+ 'kubectl_available': kubectl_service.is_available(),
+ 'clusters': cluster_service.list_clusters(),
+ 'default_cluster_id': default.id if default else None,
+ })
+
+
+@k8s_bp.route('/clusters', methods=['GET'])
+@viewer_required
+def list_clusters():
+ return jsonify({'clusters': cluster_service.list_clusters()})
+
+
+@k8s_bp.route('/clusters', methods=['POST'])
+@admin_required
+def create_cluster():
+ data = request.get_json(silent=True) or {}
+ try:
+ cluster = cluster_service.create_cluster(
+ name=data.get('name'),
+ kubeconfig=data.get('kubeconfig'),
+ context=data.get('context'),
+ make_default=bool(data.get('make_default')),
+ )
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+ return jsonify(cluster.to_dict()), 201
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>', methods=['GET'])
+@viewer_required
+def get_cluster(cluster_id):
+ cluster = _cluster_or_404(cluster_id)
+ if not cluster:
+ return jsonify({'error': 'Cluster not found'}), 404
+ return jsonify(cluster.to_dict())
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>', methods=['PUT'])
+@admin_required
+def update_cluster(cluster_id):
+ data = request.get_json(silent=True) or {}
+ try:
+ cluster = cluster_service.update_cluster(
+ cluster_id,
+ name=data.get('name'),
+ kubeconfig=data.get('kubeconfig'),
+ context=data.get('context'),
+ )
+ except ValueError as e:
+ code = 404 if 'not found' in str(e).lower() else 400
+ return jsonify({'error': str(e)}), code
+ return jsonify(cluster.to_dict())
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>', methods=['DELETE'])
+@admin_required
+def delete_cluster(cluster_id):
+ try:
+ cluster_service.delete_cluster(cluster_id)
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 404
+ return jsonify({'deleted': True})
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/default', methods=['POST'])
+@admin_required
+def set_default(cluster_id):
+ try:
+ cluster = cluster_service.set_default(cluster_id)
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 404
+ return jsonify(cluster.to_dict())
+
+
+# --------------------------------------------------------------------------
+# Cluster-talking routes (kubectl required)
+# --------------------------------------------------------------------------
+@k8s_bp.route('/clusters/<int:cluster_id>/test', methods=['POST'])
+@viewer_required
+def test_connection(cluster_id):
+ guard = _kubectl_or_error()
+ if guard:
+ return guard
+ cluster = _cluster_or_404(cluster_id)
+ if not cluster:
+ return jsonify({'error': 'Cluster not found'}), 404
+ return jsonify(cluster_service.test_connection(cluster))
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/overview', methods=['GET'])
+@viewer_required
+def overview(cluster_id):
+ guard = _kubectl_or_error()
+ if guard:
+ return guard
+ cluster = _cluster_or_404(cluster_id)
+ if not cluster:
+ return jsonify({'error': 'Cluster not found'}), 404
+ return jsonify(cluster_service.get_overview(cluster))
+
+
+def _read_route(cluster_id, fn_name):
+ guard = _kubectl_or_error()
+ if guard:
+ return guard
+ cluster = _cluster_or_404(cluster_id)
+ if not cluster:
+ return jsonify({'error': 'Cluster not found'}), 404
+ namespace = request.args.get('namespace', 'all')
+ fn = getattr(cluster_service, fn_name)
+ if fn_name in ('get_nodes', 'get_namespaces'):
+ return _kubectl_call(lambda: {'items': fn(cluster)})
+ return _kubectl_call(lambda: {'items': fn(cluster, namespace)})
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/nodes', methods=['GET'])
+@viewer_required
+def nodes(cluster_id):
+ return _read_route(cluster_id, 'get_nodes')
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/namespaces', methods=['GET'])
+@viewer_required
+def namespaces(cluster_id):
+ return _read_route(cluster_id, 'get_namespaces')
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/pods', methods=['GET'])
+@viewer_required
+def pods(cluster_id):
+ return _read_route(cluster_id, 'get_pods')
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/services', methods=['GET'])
+@viewer_required
+def services(cluster_id):
+ return _read_route(cluster_id, 'get_services')
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/ingresses', methods=['GET'])
+@viewer_required
+def ingresses(cluster_id):
+ return _read_route(cluster_id, 'get_ingresses')
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/workloads', methods=['GET'])
+@viewer_required
+def workloads(cluster_id):
+ guard = _kubectl_or_error()
+ if guard:
+ return guard
+ cluster = _cluster_or_404(cluster_id)
+ if not cluster:
+ return jsonify({'error': 'Cluster not found'}), 404
+ namespace = request.args.get('namespace', 'all')
+ kind = request.args.get('kind', 'deployment')
+ return _kubectl_call(lambda: {'items': cluster_service.get_workloads(cluster, namespace, kind)})
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/pods/<namespace>/<pod>/logs', methods=['GET'])
+@viewer_required
+def pod_logs(cluster_id, namespace, pod):
+ guard = _kubectl_or_error()
+ if guard:
+ return guard
+ cluster = _cluster_or_404(cluster_id)
+ if not cluster:
+ return jsonify({'error': 'Cluster not found'}), 404
+ container = request.args.get('container')
+ tail = request.args.get('tail', 200)
+ return _kubectl_call(lambda: {'logs': cluster_service.get_pod_logs(cluster, namespace, pod, container, tail)})
+
+
+# --------------------------------------------------------------------------
+# Mutations (admin + kubectl required)
+# --------------------------------------------------------------------------
+def _mutation_setup(cluster_id):
+ guard = _kubectl_or_error()
+ if guard:
+ return None, guard
+ cluster = _cluster_or_404(cluster_id)
+ if not cluster:
+ return None, (jsonify({'error': 'Cluster not found'}), 404)
+ return cluster, None
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/deployments/<namespace>/<name>/scale', methods=['POST'])
+@admin_required
+def scale(cluster_id, namespace, name):
+ cluster, err = _mutation_setup(cluster_id)
+ if err:
+ return err
+ data = request.get_json(silent=True) or {}
+ return _kubectl_call(lambda: cluster_service.scale_deployment(cluster, namespace, name, data.get('replicas', 0)))
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/deployments/<namespace>/<name>/restart', methods=['POST'])
+@admin_required
+def restart(cluster_id, namespace, name):
+ cluster, err = _mutation_setup(cluster_id)
+ if err:
+ return err
+ return _kubectl_call(lambda: cluster_service.restart_deployment(cluster, namespace, name))
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/delete-resource', methods=['POST'])
+@admin_required
+def delete_resource(cluster_id):
+ cluster, err = _mutation_setup(cluster_id)
+ if err:
+ return err
+ data = request.get_json(silent=True) or {}
+ return _kubectl_call(lambda: cluster_service.delete_resource(
+ cluster, data.get('kind'), data.get('name'), data.get('namespace')))
+
+
+@k8s_bp.route('/clusters/<int:cluster_id>/apply', methods=['POST'])
+@admin_required
+def apply(cluster_id):
+ cluster, err = _mutation_setup(cluster_id)
+ if err:
+ return err
+ data = request.get_json(silent=True) or {}
+ return _kubectl_call(lambda: cluster_service.apply_manifest(cluster, data.get('manifest')))
diff --git a/builtin-extensions/serverkit-k8s/backend/kubectl_service.py b/builtin-extensions/serverkit-k8s/backend/kubectl_service.py
new file mode 100644
index 00000000..5824a40e
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/backend/kubectl_service.py
@@ -0,0 +1,127 @@
+"""Low-level ``kubectl`` engine for the serverkit-k8s extension.
+
+Every cluster operation runs the real ``kubectl`` binary against a per-cluster
+kubeconfig that we materialize to a private temp file for the duration of one
+call and delete immediately after (never left on disk between calls). This keeps
+the panel host free of any standing cluster credentials.
+
+Nothing here is Linux-specific -- ``kubectl`` runs on any OS -- so the extension
+is not platform-gated. The temp-file ``chmod 0600`` is guarded with
+``os.name != 'nt'`` per the repo's platform rule.
+"""
+import json
+import logging
+import os
+import subprocess
+import tempfile
+
+logger = logging.getLogger(__name__)
+
+KUBECTL_BIN = 'kubectl'
+DEFAULT_TIMEOUT = 30
+
+
+class KubectlError(RuntimeError):
+ """Raised when a kubectl invocation fails (non-zero exit)."""
+
+ def __init__(self, message, returncode=None, stderr=None):
+ super().__init__(message)
+ self.returncode = returncode
+ self.stderr = stderr
+
+
+def is_available():
+ """Return True if the ``kubectl`` binary is on the host."""
+ try:
+ from app.utils.system import is_command_available
+ return is_command_available(KUBECTL_BIN)
+ except Exception: # pragma: no cover - fall back to a direct probe
+ from shutil import which
+ return which(KUBECTL_BIN) is not None
+
+
+def _write_kubeconfig(kubeconfig_text):
+ """Write *kubeconfig_text* to a private temp file and return its path."""
+ fd, path = tempfile.mkstemp(prefix='sk8s-', suffix='.yaml')
+ try:
+ with os.fdopen(fd, 'w', encoding='utf-8') as fh:
+ fh.write(kubeconfig_text or '')
+ if os.name != 'nt':
+ os.chmod(path, 0o600)
+ except Exception:
+ _safe_unlink(path)
+ raise
+ return path
+
+
+def _safe_unlink(path):
+ try:
+ if path and os.path.exists(path):
+ os.unlink(path)
+ except OSError as e: # pragma: no cover - best effort cleanup
+ logger.warning('serverkit-k8s: could not remove temp kubeconfig %s: %s', path, e)
+
+
+def build_argv(cluster, args):
+ """Return the full ``kubectl`` argv for *args* against *cluster*.
+
+ Separated out so tests can assert on argv construction without running the
+ binary. The ``--kubeconfig`` path is appended by :func:`run` since it is only
+ known once the temp file is written.
+ """
+ argv = [KUBECTL_BIN]
+ if getattr(cluster, 'context', None):
+ argv += ['--context', cluster.context]
+ return argv + list(args)
+
+
+def run(cluster, args, timeout=DEFAULT_TIMEOUT, input_text=None):
+ """Run ``kubectl <args>`` against *cluster* and return stdout as a string.
+
+ Raises :class:`KubectlError` on a non-zero exit or missing binary.
+ """
+ if not is_available():
+ raise KubectlError('kubectl is not installed on the panel host.')
+
+ kubeconfig_text = cluster.get_kubeconfig() if hasattr(cluster, 'get_kubeconfig') else cluster
+ path = _write_kubeconfig(kubeconfig_text)
+ try:
+ argv = build_argv(cluster, args)
+ argv += ['--kubeconfig', path]
+ try:
+ result = subprocess.run(
+ argv,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ input=input_text,
+ )
+ except subprocess.TimeoutExpired as e:
+ raise KubectlError(f'kubectl timed out after {timeout}s') from e
+ except (OSError, subprocess.SubprocessError) as e:
+ raise KubectlError(f'kubectl could not be executed: {e}') from e
+
+ if result.returncode != 0:
+ stderr = (result.stderr or '').strip()
+ raise KubectlError(
+ stderr or f'kubectl exited with code {result.returncode}',
+ returncode=result.returncode,
+ stderr=stderr,
+ )
+ return result.stdout or ''
+ finally:
+ _safe_unlink(path)
+
+
+def run_json(cluster, args, timeout=DEFAULT_TIMEOUT):
+ """Run a kubectl command that emits JSON and return the parsed object.
+
+ The caller is expected to include ``-o json`` (or a get with it) in *args*.
+ """
+ out = run(cluster, args, timeout=timeout)
+ if not out.strip():
+ return {}
+ try:
+ return json.loads(out)
+ except ValueError as e:
+ raise KubectlError(f'kubectl returned unparseable JSON: {e}') from e
diff --git a/builtin-extensions/serverkit-k8s/backend/lifecycle.py b/builtin-extensions/serverkit-k8s/backend/lifecycle.py
new file mode 100644
index 00000000..c999df1d
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/backend/lifecycle.py
@@ -0,0 +1,32 @@
+"""Install / uninstall lifecycle hooks (serverkit-k8s extension).
+
+Contract (per the plugin SDK): a single positional arg -- the InstalledPlugin
+row. ``on_uninstall`` also accepts a ``purge`` flag. Everything here is wrapped
+so a hook failure never blocks install/uninstall.
+
+There is no engine to provision: the extension only talks to *remote* clusters
+through kubectl, so install just registers a notification event and uninstall is
+a no-op (the ``ext_serverkit_k8s_*`` table is dropped by the platform on
+``--purge``).
+"""
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def on_install(plugin):
+ """Register the extension's notification events. Best-effort."""
+ try:
+ from app.plugins_sdk import notify
+ notify.register_event(
+ 'k8s.cluster_unreachable',
+ 'A Kubernetes cluster became unreachable',
+ template='generic', severity='warning', category='system')
+ logger.info('serverkit-k8s installed: notification events registered')
+ except Exception as e: # noqa: BLE001
+ logger.warning('serverkit-k8s on_install hook error: %s', e)
+
+
+def on_uninstall(plugin, purge=False):
+ """Nothing to tear down -- clusters are remote and hold no local resources."""
+ logger.info('serverkit-k8s on_uninstall (purge=%s): no local resources to remove', purge)
diff --git a/builtin-extensions/serverkit-k8s/backend/models.py b/builtin-extensions/serverkit-k8s/backend/models.py
new file mode 100644
index 00000000..80a7741a
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/backend/models.py
@@ -0,0 +1,101 @@
+"""Data models for the serverkit-k8s extension.
+
+A :class:`K8sCluster` row is a saved *connection* to an external Kubernetes
+cluster: a friendly name, the cluster's **kubeconfig** (stored encrypted with the
+panel key), an optional context to select within that kubeconfig, a default flag,
+and a small cache of the last reachability probe so the Overview can render
+without blocking on a live ``kubectl`` call.
+
+The panel host is never assumed to be a cluster member. All cluster access goes
+through ``kubectl --kubeconfig <the decrypted blob>`` (see ``kubectl_service``),
+so the only secret we hold is the kubeconfig, and it is **never** returned by
+:meth:`K8sCluster.to_dict`.
+
+Tables are namespaced ``ext_serverkit_k8s_*`` (dash -> underscore) per the
+extension convention, so ``--purge`` on uninstall drops exactly these.
+
+Registration: importing this module defines the table on the shared metadata as
+a side effect; the manifest's ``models: "models:register"`` then calls
+:func:`register` (a no-op passthrough) and the platform runs ``db.create_all()``.
+"""
+import json
+from datetime import datetime
+
+from app import db
+
+try:
+ from app.utils.crypto import encrypt_secret, decrypt_secret_safe
+except Exception: # pragma: no cover - crypto util should always be present
+ encrypt_secret = None
+ decrypt_secret_safe = None
+
+
+class K8sCluster(db.Model):
+ __tablename__ = 'ext_serverkit_k8s_clusters'
+
+ id = db.Column(db.Integer, primary_key=True)
+ name = db.Column(db.String(255), unique=True, nullable=False, index=True)
+
+ # Encrypted kubeconfig YAML. Read/written only through the helpers below so
+ # the plaintext never lands in a column or a log line.
+ kubeconfig_encrypted = db.Column(db.Text, nullable=False)
+
+ # Optional context to select inside the kubeconfig (kubectl --context).
+ context = db.Column(db.String(255), nullable=True)
+
+ is_default = db.Column(db.Boolean, default=False, nullable=False)
+
+ # Cached result of the last reachability probe (test_connection).
+ last_reachable = db.Column(db.Boolean, nullable=True)
+ last_status = db.Column(db.Text, nullable=True) # JSON: {server_version, error}
+ last_checked_at = db.Column(db.DateTime, nullable=True)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # --- secret helpers -------------------------------------------------
+ def set_kubeconfig(self, plaintext):
+ """Encrypt and store a kubeconfig YAML string."""
+ if encrypt_secret is None:
+ # No key configured: store as-is so dev boxes still work. Encryption
+ # is expected in any real deployment.
+ self.kubeconfig_encrypted = plaintext or ''
+ else:
+ self.kubeconfig_encrypted = encrypt_secret(plaintext or '')
+
+ def get_kubeconfig(self):
+ """Return the decrypted kubeconfig YAML string."""
+ if not self.kubeconfig_encrypted:
+ return ''
+ if decrypt_secret_safe is None:
+ return self.kubeconfig_encrypted
+ return decrypt_secret_safe(self.kubeconfig_encrypted)
+
+ # --- serialization --------------------------------------------------
+ def to_dict(self):
+ status = None
+ if self.last_status:
+ try:
+ status = json.loads(self.last_status)
+ except (ValueError, TypeError):
+ status = None
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'context': self.context,
+ 'is_default': self.is_default,
+ 'last_reachable': self.last_reachable,
+ 'status': status,
+ 'last_checked_at': self.last_checked_at.isoformat() if self.last_checked_at else None,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
+ }
+
+
+def register(db): # noqa: A002 - signature dictated by the platform (fn(db))
+ """No-op passthrough required by the manifest ``models: "models:register"``.
+
+ Importing this module already defined the table on ``db.metadata``; the
+ platform creates it. Nothing else to do here.
+ """
+ return [K8sCluster]
diff --git a/builtin-extensions/serverkit-k8s/frontend/components/K8sPage.jsx b/builtin-extensions/serverkit-k8s/frontend/components/K8sPage.jsx
new file mode 100644
index 00000000..1c4857a4
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/frontend/components/K8sPage.jsx
@@ -0,0 +1,689 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import {
+ ShipWheel, RefreshCw, Plus, Trash2, Server, Boxes, Network,
+ Layers, RotateCw, ScrollText, Star, Cable, FileCode, X,
+} from 'lucide-react';
+import api from '@/services/api';
+import { PageTopbar, Pill } from '@/components/ds';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import Modal from '@/components/Modal';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import EmptyState from '@/components/EmptyState';
+import { useToast } from '@/contexts/ToastContext';
+
+import '../styles/k8s.scss';
+
+// Route-driven tabs (manifest maps /k8s and /k8s/:tab to this component).
+const TABS = [
+ { slug: 'overview', to: '/k8s', label: 'Overview', end: true },
+ { slug: 'workloads', to: '/k8s/workloads', label: 'Workloads' },
+ { slug: 'pods', to: '/k8s/pods', label: 'Pods' },
+ { slug: 'services', to: '/k8s/services', label: 'Services' },
+ { slug: 'nodes', to: '/k8s/nodes', label: 'Nodes' },
+ { slug: 'apply', to: '/k8s/apply', label: 'Apply' },
+ { slug: 'clusters', to: '/k8s/clusters', label: 'Clusters' },
+];
+const VALID_TABS = TABS.map((t) => t.slug);
+
+const phasePill = (phase) => {
+ const kind = phase === 'Running' || phase === 'Succeeded' || phase === 'Active'
+ ? 'green'
+ : phase === 'Pending' ? 'amber' : phase === 'Failed' ? 'red' : 'gray';
+ return <Pill kind={kind}>{phase || 'Unknown'}</Pill>;
+};
+
+const K8sPage = () => {
+ const toast = useToast();
+ const navigate = useNavigate();
+ const { tab } = useParams();
+ const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';
+
+ const [kubectlAvailable, setKubectlAvailable] = useState(true);
+ const [clusters, setClusters] = useState([]);
+ const [selectedId, setSelectedId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+ const [confirmDialog, setConfirmDialog] = useState(null);
+
+ // Per-tab data
+ const [overview, setOverview] = useState(null);
+ const [namespace, setNamespace] = useState('all');
+ const [namespaces, setNamespaces] = useState([]);
+ const [workloadKind, setWorkloadKind] = useState('deployment');
+ const [rows, setRows] = useState([]);
+ const [dataLoading, setDataLoading] = useState(false);
+
+ // Modals
+ const [addClusterOpen, setAddClusterOpen] = useState(false);
+ const [addForm, setAddForm] = useState({ name: '', context: '', kubeconfig: '', make_default: false });
+ const [logsModal, setLogsModal] = useState(null); // {pod, namespace, container, text, loading}
+ const [manifest, setManifest] = useState('');
+ const [applyOutput, setApplyOutput] = useState(null);
+
+ const selected = useMemo(
+ () => clusters.find((c) => String(c.id) === String(selectedId)) || null,
+ [clusters, selectedId],
+ );
+
+ // ── Cluster list ──
+ const loadStatus = useCallback(async () => {
+ setLoading(true);
+ try {
+ const data = await api.request('/k8s/status');
+ setKubectlAvailable(data.kubectl_available);
+ setClusters(data.clusters || []);
+ setSelectedId((prev) => {
+ if (prev && (data.clusters || []).some((c) => String(c.id) === String(prev))) return prev;
+ return data.default_cluster_id || (data.clusters?.[0]?.id ?? null);
+ });
+ } catch (error) {
+ toast.error(`Could not load Kubernetes status: ${error.message}`);
+ } finally {
+ setLoading(false);
+ }
+ }, [toast]);
+
+ useEffect(() => { loadStatus(); }, [loadStatus]);
+
+ // ── Namespaces (for the namespace filter) ──
+ const loadNamespaces = useCallback(async () => {
+ if (!selected || !kubectlAvailable) return;
+ try {
+ const data = await api.request(`/k8s/clusters/${selected.id}/namespaces`);
+ setNamespaces((data.items || []).map((n) => n.name).filter(Boolean));
+ } catch { /* namespace filter is optional */ }
+ }, [selected, kubectlAvailable]);
+
+ useEffect(() => { loadNamespaces(); }, [loadNamespaces]);
+
+ // ── Tab data ──
+ const loadTab = useCallback(async () => {
+ if (!selected || !kubectlAvailable) { setRows([]); setOverview(null); return; }
+ setDataLoading(true);
+ try {
+ if (activeTab === 'overview') {
+ setOverview(await api.request(`/k8s/clusters/${selected.id}/overview`));
+ } else if (activeTab === 'workloads') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/workloads?namespace=${namespace}&kind=${workloadKind}`);
+ setRows(data.items || []);
+ } else if (activeTab === 'pods') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/pods?namespace=${namespace}`);
+ setRows(data.items || []);
+ } else if (activeTab === 'services') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/services?namespace=${namespace}`);
+ setRows(data.items || []);
+ } else if (activeTab === 'nodes') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/nodes`);
+ setRows(data.items || []);
+ }
+ } catch (error) {
+ toast.error(error.message);
+ setRows([]);
+ } finally {
+ setDataLoading(false);
+ }
+ }, [selected, kubectlAvailable, activeTab, namespace, workloadKind, toast]);
+
+ useEffect(() => { loadTab(); }, [loadTab]);
+
+ // ── Cluster actions ──
+ const handleAddCluster = async () => {
+ if (!addForm.name.trim() || !addForm.kubeconfig.trim()) {
+ toast.error('Name and kubeconfig are required.');
+ return;
+ }
+ setBusy(true);
+ try {
+ await api.request('/k8s/clusters', { method: 'POST', body: addForm });
+ toast.success(`Cluster "${addForm.name}" added`);
+ setAddClusterOpen(false);
+ setAddForm({ name: '', context: '', kubeconfig: '', make_default: false });
+ await loadStatus();
+ } catch (error) {
+ toast.error(`Could not add cluster: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleDeleteCluster = (cluster) => {
+ setConfirmDialog({
+ title: `Remove ${cluster.name}?`,
+ message: 'This deletes the stored connection and its kubeconfig from the panel. The cluster itself is not touched.',
+ confirmText: 'Remove',
+ variant: 'destructive',
+ onConfirm: async () => {
+ setConfirmDialog(null);
+ try {
+ await api.request(`/k8s/clusters/${cluster.id}`, { method: 'DELETE' });
+ toast.success('Cluster removed');
+ await loadStatus();
+ } catch (error) {
+ toast.error(error.message);
+ }
+ },
+ onCancel: () => setConfirmDialog(null),
+ });
+ };
+
+ const handleSetDefault = async (cluster) => {
+ try {
+ await api.request(`/k8s/clusters/${cluster.id}/default`, { method: 'POST' });
+ await loadStatus();
+ } catch (error) {
+ toast.error(error.message);
+ }
+ };
+
+ const handleTest = async (cluster) => {
+ setBusy(true);
+ try {
+ const res = await api.request(`/k8s/clusters/${cluster.id}/test`, { method: 'POST' });
+ if (res.ok) toast.success(`Reachable — ${res.server_version}`);
+ else toast.error(`Unreachable: ${res.error}`);
+ await loadStatus();
+ } catch (error) {
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // ── Workload actions ──
+ const handleScale = (w, delta) => {
+ const next = Math.max(0, (w.desired || 0) + delta);
+ return doScale(w, next);
+ };
+
+ const doScale = async (w, replicas) => {
+ setBusy(true);
+ try {
+ await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/scale`,
+ { method: 'POST', body: { replicas } });
+ toast.success(`Scaled ${w.name} to ${replicas}`);
+ await loadTab();
+ } catch (error) {
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleRestart = async (w) => {
+ setBusy(true);
+ try {
+ await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/restart`,
+ { method: 'POST' });
+ toast.success(`Restart triggered for ${w.name}`);
+ } catch (error) {
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleDeleteResource = (kind, row) => {
+ setConfirmDialog({
+ title: `Delete ${kind} ${row.name}?`,
+ message: `This removes ${row.name} from namespace ${row.namespace} on the live cluster.`,
+ confirmText: 'Delete',
+ variant: 'destructive',
+ onConfirm: async () => {
+ setConfirmDialog(null);
+ try {
+ await api.request(`/k8s/clusters/${selected.id}/delete-resource`,
+ { method: 'POST', body: { kind, name: row.name, namespace: row.namespace } });
+ toast.success(`${kind} ${row.name} deleted`);
+ await loadTab();
+ } catch (error) {
+ toast.error(error.message);
+ }
+ },
+ onCancel: () => setConfirmDialog(null),
+ });
+ };
+
+ // ── Pod logs ──
+ const openLogs = async (pod) => {
+ const container = pod.containers?.[0] || '';
+ setLogsModal({ pod: pod.name, namespace: pod.namespace, container, text: '', loading: true });
+ try {
+ const q = container ? `?container=${container}&tail=200` : '?tail=200';
+ const data = await api.request(`/k8s/clusters/${selected.id}/pods/${pod.namespace}/${pod.name}/logs${q}`);
+ setLogsModal((m) => m && ({ ...m, text: data.logs || '(no output)', loading: false }));
+ } catch (error) {
+ setLogsModal((m) => m && ({ ...m, text: `Error: ${error.message}`, loading: false }));
+ }
+ };
+
+ // ── Apply ──
+ const handleApply = async () => {
+ if (!manifest.trim()) { toast.error('Paste a manifest first.'); return; }
+ setBusy(true);
+ setApplyOutput(null);
+ try {
+ const res = await api.request(`/k8s/clusters/${selected.id}/apply`, { method: 'POST', body: { manifest } });
+ setApplyOutput(res.output || '(applied)');
+ toast.success('Manifest applied');
+ } catch (error) {
+ setApplyOutput(`Error: ${error.message}`);
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // ── Renderers ──
+ const NamespaceFilter = () => (
+ <div className="k8s-filter">
+ <Label>Namespace</Label>
+ <select className="k8s-select" value={namespace} onChange={(e) => setNamespace(e.target.value)}>
+ <option value="all">All namespaces</option>
+ {namespaces.map((n) => <option key={n} value={n}>{n}</option>)}
+ </select>
+ </div>
+ );
+
+ const renderOverview = () => {
+ if (dataLoading && !overview) return <EmptyState loading title="Querying cluster..." />;
+ if (!overview) return <EmptyState icon={ShipWheel} title="No data" description="Select a reachable cluster." />;
+ if (!overview.reachable) {
+ return (
+ <div className="card">
+ <div className="card-body">
+ <EmptyState icon={Cable} title="Cluster unreachable"
+ description={overview.error || 'kubectl could not reach the API server with the stored kubeconfig.'} />
+ <div className="k8s-center">
+ <Button variant="outline" size="sm" onClick={() => handleTest(selected)}>
+ <RefreshCw size={14} /> Retry
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ const c = overview.counts;
+ const cards = [
+ { label: 'Server', value: overview.server_version, icon: ShipWheel },
+ { label: 'Nodes ready', value: `${c.nodes_ready}/${c.nodes}`, icon: Server },
+ { label: 'Namespaces', value: c.namespaces, icon: Layers },
+ { label: 'Pods running', value: `${c.pods_running}/${c.pods}`, icon: Boxes },
+ { label: 'Deployments', value: c.deployments, icon: Network },
+ ];
+ return (
+ <div className="k8s-kpis">
+ {cards.map((k) => (
+ <div className="card k8s-kpi" key={k.label}>
+ <div className="card-body">
+ <div className="k8s-kpi__icon"><k.icon size={18} /></div>
+ <div className="k8s-kpi__val">{k.value ?? '—'}</div>
+ <div className="k8s-kpi__label">{k.label}</div>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+ };
+
+ const renderWorkloads = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Workloads</h3>
+ <div className="card-actions k8s-toolbar">
+ <select className="k8s-select" value={workloadKind} onChange={(e) => setWorkloadKind(e.target.value)}>
+ <option value="deployment">Deployments</option>
+ <option value="statefulset">StatefulSets</option>
+ <option value="daemonset">DaemonSets</option>
+ </select>
+ <NamespaceFilter />
+ </div>
+ </div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading workloads..." />
+ : rows.length === 0 ? <EmptyState icon={Network} title="No workloads" description="Nothing found in this namespace." />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Namespace</th><th>Replicas</th><th>Status</th><th>Image</th><th /></tr>
+ </thead>
+ <tbody>
+ {rows.map((w) => (
+ <tr key={`${w.namespace}/${w.name}`}>
+ <td className="sk-cell-mono">{w.name}</td>
+ <td>{w.namespace}</td>
+ <td>
+ {workloadKind === 'deployment' ? (
+ <span className="k8s-scale">
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, -1)}>−</Button>
+ <span className="k8s-scale__n">{w.ready}/{w.desired}</span>
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, +1)}>+</Button>
+ </span>
+ ) : <span className="sk-cell-mono">{w.ready}/{w.desired}</span>}
+ </td>
+ <td><Pill kind={w.healthy ? 'green' : 'amber'}>{w.healthy ? 'healthy' : 'degraded'}</Pill></td>
+ <td className="sk-cell-mono k8s-truncate" title={(w.images || []).join(', ')}>{(w.images || [])[0] || '—'}</td>
+ <td className="k8s-row-actions">
+ {workloadKind === 'deployment' && (
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRestart(w)} title="Rolling restart">
+ <RotateCw size={14} />
+ </Button>
+ )}
+ <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource(workloadKind, w)}>
+ <Trash2 size={14} />
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderPods = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Pods</h3>
+ <div className="card-actions"><NamespaceFilter /></div>
+ </div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading pods..." />
+ : rows.length === 0 ? <EmptyState icon={Boxes} title="No pods" description="Nothing running in this namespace." />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Namespace</th><th>Ready</th><th>Status</th><th>Restarts</th><th>Node</th><th /></tr>
+ </thead>
+ <tbody>
+ {rows.map((p) => (
+ <tr key={`${p.namespace}/${p.name}`}>
+ <td className="sk-cell-mono k8s-truncate" title={p.name}>{p.name}</td>
+ <td>{p.namespace}</td>
+ <td className="sk-cell-mono">{p.ready}</td>
+ <td>{phasePill(p.phase)}</td>
+ <td className="sk-cell-mono">{p.restarts > 0 ? <Pill kind="amber">{p.restarts}</Pill> : 0}</td>
+ <td className="sk-cell-mono k8s-truncate">{p.node || '—'}</td>
+ <td className="k8s-row-actions">
+ <Button variant="secondary" size="sm" onClick={() => openLogs(p)} title="Logs">
+ <ScrollText size={14} />
+ </Button>
+ <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource('pod', p)}>
+ <Trash2 size={14} />
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderServices = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Services</h3>
+ <div className="card-actions"><NamespaceFilter /></div>
+ </div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading services..." />
+ : rows.length === 0 ? <EmptyState icon={Cable} title="No services" />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Namespace</th><th>Type</th><th>Cluster IP</th><th>External</th><th>Ports</th></tr>
+ </thead>
+ <tbody>
+ {rows.map((s) => (
+ <tr key={`${s.namespace}/${s.name}`}>
+ <td className="sk-cell-mono">{s.name}</td>
+ <td>{s.namespace}</td>
+ <td><Pill kind={s.type === 'LoadBalancer' ? 'green' : 'gray'}>{s.type}</Pill></td>
+ <td className="sk-cell-mono">{s.cluster_ip || '—'}</td>
+ <td className="sk-cell-mono">{s.external_ip || '—'}</td>
+ <td className="sk-cell-mono">{(s.ports || []).join(', ') || '—'}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderNodes = () => (
+ <div className="card sec-flush">
+ <div className="card-header"><h3>Nodes</h3></div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading nodes..." />
+ : rows.length === 0 ? <EmptyState icon={Server} title="No nodes" />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Status</th><th>Roles</th><th>Version</th><th>OS</th><th>CPU</th><th>Memory</th></tr>
+ </thead>
+ <tbody>
+ {rows.map((n) => (
+ <tr key={n.name}>
+ <td className="sk-cell-mono">{n.name}</td>
+ <td><Pill kind={n.ready ? 'green' : 'red'}>{n.ready ? 'Ready' : 'NotReady'}</Pill></td>
+ <td>{(n.roles || []).join(', ')}</td>
+ <td className="sk-cell-mono">{n.kubelet_version || '—'}</td>
+ <td className="k8s-truncate" title={n.os_image}>{n.os_image || '—'}</td>
+ <td className="sk-cell-mono">{n.cpu || '—'}</td>
+ <td className="sk-cell-mono">{n.memory || '—'}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderApply = () => (
+ <div className="card">
+ <div className="card-header"><h3>Apply manifest</h3></div>
+ <div className="card-body k8s-apply">
+ <p className="text-muted">
+ Paste a Kubernetes YAML or JSON manifest. It is sent to the selected cluster with
+ <code> kubectl apply -f -</code>. Admin only.
+ </p>
+ <textarea
+ className="k8s-textarea"
+ rows={16}
+ spellCheck={false}
+ placeholder={'apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: demo'}
+ value={manifest}
+ onChange={(e) => setManifest(e.target.value)}
+ />
+ <div className="k8s-apply__actions">
+ <Button variant="default" size="sm" disabled={busy || !selected} onClick={handleApply}>
+ <FileCode size={14} /> Apply
+ </Button>
+ <Button variant="outline" size="sm" onClick={() => { setManifest(''); setApplyOutput(null); }}>Clear</Button>
+ </div>
+ {applyOutput != null && <pre className="k8s-output">{applyOutput}</pre>}
+ </div>
+ </div>
+ );
+
+ const renderClusters = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Clusters</h3>
+ <div className="card-actions">
+ <Button variant="default" size="sm" onClick={() => setAddClusterOpen(true)}>
+ <Plus size={14} /> Add cluster
+ </Button>
+ </div>
+ </div>
+ <div className="card-body">
+ {clusters.length === 0 ? (
+ <EmptyState icon={ShipWheel} title="No clusters yet"
+ description="Add a cluster by pasting its kubeconfig to start managing workloads." />
+ ) : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Context</th><th>Reachable</th><th>Server</th><th>Last checked</th><th /></tr>
+ </thead>
+ <tbody>
+ {clusters.map((c) => (
+ <tr key={c.id}>
+ <td className="sk-cell-mono">
+ {c.is_default && <Star size={12} className="k8s-default-star" title="Default" />} {c.name}
+ </td>
+ <td className="sk-cell-mono">{c.context || '—'}</td>
+ <td>
+ {c.last_reachable == null
+ ? <Pill kind="gray">unknown</Pill>
+ : <Pill kind={c.last_reachable ? 'green' : 'red'}>{c.last_reachable ? 'yes' : 'no'}</Pill>}
+ </td>
+ <td className="sk-cell-mono">{c.status?.server_version || '—'}</td>
+ <td className="sk-cell-mono">{c.last_checked_at ? new Date(c.last_checked_at).toLocaleString() : '—'}</td>
+ <td className="k8s-row-actions">
+ <Button variant="secondary" size="sm" disabled={busy || !kubectlAvailable} onClick={() => handleTest(c)}>Test</Button>
+ {!c.is_default && <Button variant="secondary" size="sm" onClick={() => handleSetDefault(c)}>Set default</Button>}
+ <Button variant="destructive" size="sm" onClick={() => handleDeleteCluster(c)}><Trash2 size={14} /></Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ // ── Page shell ──
+ if (loading) {
+ return (
+ <div className="page-container k8s-page">
+ <PageTopbar icon={<ShipWheel size={18} />} title="Kubernetes" />
+ <EmptyState loading title="Loading Kubernetes..." />
+ </div>
+ );
+ }
+
+ const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));
+ const needsCluster = activeTab !== 'clusters' && clusters.length === 0;
+
+ return (
+ <div className="page-container k8s-page">
+ <PageTopbar
+ icon={<ShipWheel size={18} />}
+ title="Kubernetes"
+ meta={<>kubectl · clusters · workloads</>}
+ tabs={topbarTabs}
+ actions={
+ <div className="k8s-topbar-actions">
+ {clusters.length > 0 && activeTab !== 'clusters' && (
+ <select className="k8s-select" value={selectedId ?? ''} onChange={(e) => setSelectedId(e.target.value)}>
+ {clusters.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
+ </select>
+ )}
+ <Button variant="outline" size="sm" onClick={() => { loadStatus(); loadTab(); }}>
+ <RefreshCw size={14} /> Refresh
+ </Button>
+ </div>
+ }
+ />
+
+ {!kubectlAvailable && (
+ <div className="card k8s-warn">
+ <div className="card-body">
+ <strong>kubectl is not installed on the panel host.</strong> You can still add and
+ store cluster connections, but live cluster data and actions are unavailable until
+ <code> kubectl</code> is on the panel host PATH.
+ </div>
+ </div>
+ )}
+
+ {needsCluster ? (
+ <div className="card">
+ <div className="card-body">
+ <EmptyState icon={ShipWheel} title="No clusters connected"
+ description="Add a cluster on the Clusters tab by pasting its kubeconfig." />
+ <div className="k8s-center">
+ <Button variant="default" size="sm" onClick={() => navigate('/k8s/clusters')}>
+ <Plus size={14} /> Go to Clusters
+ </Button>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <>
+ {activeTab === 'overview' && renderOverview()}
+ {activeTab === 'workloads' && renderWorkloads()}
+ {activeTab === 'pods' && renderPods()}
+ {activeTab === 'services' && renderServices()}
+ {activeTab === 'nodes' && renderNodes()}
+ {activeTab === 'apply' && renderApply()}
+ {activeTab === 'clusters' && renderClusters()}
+ </>
+ )}
+
+ {/* Add cluster modal */}
+ <Modal open={addClusterOpen} onClose={() => setAddClusterOpen(false)} title="Add Kubernetes cluster">
+ <div className="k8s-form">
+ <div className="form-group">
+ <Label>Name</Label>
+ <Input type="text" value={addForm.name} placeholder="prod-eu"
+ onChange={(e) => setAddForm((f) => ({ ...f, name: e.target.value }))} />
+ </div>
+ <div className="form-group">
+ <Label>Context (optional)</Label>
+ <Input type="text" value={addForm.context} placeholder="Leave blank for the kubeconfig's current-context"
+ onChange={(e) => setAddForm((f) => ({ ...f, context: e.target.value }))} />
+ </div>
+ <div className="form-group">
+ <Label>Kubeconfig</Label>
+ <textarea className="k8s-textarea" rows={10} spellCheck={false}
+ placeholder="Paste the full kubeconfig YAML here"
+ value={addForm.kubeconfig}
+ onChange={(e) => setAddForm((f) => ({ ...f, kubeconfig: e.target.value }))} />
+ <p className="text-muted">Stored encrypted with the panel key. Never shown again after saving.</p>
+ </div>
+ <label className="k8s-checkbox">
+ <input type="checkbox" checked={addForm.make_default}
+ onChange={(e) => setAddForm((f) => ({ ...f, make_default: e.target.checked }))} />
+ Make this the default cluster
+ </label>
+ </div>
+ <div className="modal-footer">
+ <Button variant="outline" onClick={() => setAddClusterOpen(false)}>Cancel</Button>
+ <Button variant="default" onClick={handleAddCluster} disabled={busy}>Add cluster</Button>
+ </div>
+ </Modal>
+
+ {/* Logs modal */}
+ <Modal open={!!logsModal} onClose={() => setLogsModal(null)}
+ title={logsModal ? `Logs · ${logsModal.pod}` : 'Logs'}>
+ {logsModal?.loading
+ ? <EmptyState loading title="Fetching logs..." />
+ : <pre className="k8s-logs">{logsModal?.text}</pre>}
+ <div className="modal-footer">
+ <Button variant="outline" onClick={() => setLogsModal(null)}><X size={14} /> Close</Button>
+ </div>
+ </Modal>
+
+ {confirmDialog && (
+ <ConfirmDialog
+ title={confirmDialog.title}
+ message={confirmDialog.message}
+ confirmText={confirmDialog.confirmText}
+ variant={confirmDialog.variant}
+ onConfirm={confirmDialog.onConfirm}
+ onCancel={confirmDialog.onCancel}
+ />
+ )}
+ </div>
+ );
+};
+
+export default K8sPage;
diff --git a/builtin-extensions/serverkit-k8s/frontend/index.jsx b/builtin-extensions/serverkit-k8s/frontend/index.jsx
new file mode 100644
index 00000000..bb282478
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/frontend/index.jsx
@@ -0,0 +1,7 @@
+// Kubernetes cluster management UI, contributed through the extension system.
+// Fully self-contained in the extension. After sync this folder lives at
+// frontend/src/plugins/serverkit-k8s/, so '@/…' host aliases resolve.
+export { default as K8sPage } from './components/K8sPage.jsx';
+
+// No default export on purpose: PluginLoader legacy-auto-renders any plugin
+// default export globally. The route contribution resolves the NAMED export.
diff --git a/builtin-extensions/serverkit-k8s/frontend/styles/k8s.scss b/builtin-extensions/serverkit-k8s/frontend/styles/k8s.scss
new file mode 100644
index 00000000..7c732390
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/frontend/styles/k8s.scss
@@ -0,0 +1,177 @@
+/* Kubernetes extension — layout-only styles. Colors, typography, spacing and
+ controls all inherit from the host design system (card, sk-dtable, Pill,
+ empty-state, form controls). No hardcoded palette; surface tints lean on
+ currentColor / neutral rgba so they read in both themes. */
+
+.k8s-page {
+ .k8s-topbar-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .k8s-select {
+ height: 32px;
+ padding: 0 10px;
+ border-radius: 6px;
+ border: 1px solid rgba(128, 128, 128, 0.35);
+ background: transparent;
+ color: inherit;
+ font-size: 13px;
+ }
+
+ .k8s-filter {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ label {
+ margin: 0;
+ white-space: nowrap;
+ }
+ }
+
+ .k8s-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+ }
+
+ .k8s-warn {
+ margin-bottom: 16px;
+
+ code {
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: rgba(128, 128, 128, 0.15);
+ }
+ }
+
+ .k8s-center {
+ display: flex;
+ justify-content: center;
+ margin-top: 12px;
+ }
+
+ /* Overview KPI band */
+ .k8s-kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 12px;
+ }
+
+ .k8s-kpi {
+ .card-body {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ &__icon {
+ opacity: 0.6;
+ margin-bottom: 4px;
+ }
+
+ &__val {
+ font-size: 20px;
+ font-weight: 600;
+ word-break: break-word;
+ }
+
+ &__label {
+ font-size: 12px;
+ opacity: 0.7;
+ }
+ }
+
+ /* Tables */
+ .k8s-row-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ justify-content: flex-end;
+ }
+
+ .k8s-truncate {
+ max-width: 240px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .k8s-scale {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+
+ &__n {
+ min-width: 44px;
+ text-align: center;
+ font-variant-numeric: tabular-nums;
+ }
+ }
+
+ .k8s-default-star {
+ color: #eab308;
+ vertical-align: middle;
+ }
+
+ /* Forms */
+ .k8s-form {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+
+ .k8s-textarea,
+ .k8s-logs,
+ .k8s-output {
+ width: 100%;
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12.5px;
+ border-radius: 8px;
+ border: 1px solid rgba(128, 128, 128, 0.3);
+ background: rgba(128, 128, 128, 0.06);
+ color: inherit;
+ padding: 12px;
+ box-sizing: border-box;
+ }
+
+ .k8s-textarea {
+ resize: vertical;
+ }
+
+ .k8s-checkbox {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ cursor: pointer;
+ }
+
+ /* Apply */
+ .k8s-apply {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ &__actions {
+ display: flex;
+ gap: 8px;
+ }
+ }
+
+ .k8s-logs,
+ .k8s-output {
+ max-height: 55vh;
+ overflow: auto;
+ white-space: pre-wrap;
+ word-break: break-word;
+ margin: 0;
+ }
+
+ .k8s-output {
+ margin-top: 4px;
+ }
+}
diff --git a/builtin-extensions/serverkit-k8s/plugin.json b/builtin-extensions/serverkit-k8s/plugin.json
new file mode 100644
index 00000000..3359002d
--- /dev/null
+++ b/builtin-extensions/serverkit-k8s/plugin.json
@@ -0,0 +1,46 @@
+{
+ "name": "serverkit-k8s",
+ "display_name": "Kubernetes",
+ "version": "1.0.0",
+ "description": "Manage remote Kubernetes clusters from the panel. Add a cluster by pasting its kubeconfig (stored encrypted, one row per cluster) and the extension shells out to kubectl to show cluster health, nodes, namespaces, workloads, pods with live logs, services, and ingresses, plus scale, restart, delete, and apply-manifest actions. Most panels never touch Kubernetes, so it ships as an opt-in extension and needs no cluster on the panel host itself.",
+ "author": "ServerKit",
+ "license": "MIT",
+ "category": "deployment",
+ "homepage": "https://github.com/jhd3197/ServerKit",
+ "permissions": ["shell", "filesystem", "network"],
+ "min_panel_version": "1.7.0",
+ "entry_point": "k8s:k8s_bp",
+ "url_prefix": "/api/v1/k8s",
+ "models": "models:register",
+ "lifecycle": {
+ "install": "lifecycle:on_install",
+ "uninstall": "lifecycle:on_uninstall"
+ },
+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>",
+ "contributions": {
+ "nav": [
+ {
+ "id": "k8s",
+ "label": "Kubernetes",
+ "route": "/k8s",
+ "category": "infrastructure",
+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>"
+ }
+ ],
+ "routes": [
+ { "path": "k8s", "component": "K8sPage" },
+ { "path": "k8s/:tab", "component": "K8sPage" }
+ ],
+ "page_titles": {
+ "/k8s": "Kubernetes"
+ },
+ "command_palette": [
+ {
+ "label": "Kubernetes",
+ "path": "/k8s",
+ "category": "Pages",
+ "keywords": "k8s kubernetes kubectl cluster node namespace pod deployment workload statefulset daemonset service ingress scale restart apply kubeconfig"
+ }
+ ]
+ }
+}
diff --git a/frontend/src/plugins/serverkit-k8s/components/K8sPage.jsx b/frontend/src/plugins/serverkit-k8s/components/K8sPage.jsx
new file mode 100644
index 00000000..1c4857a4
--- /dev/null
+++ b/frontend/src/plugins/serverkit-k8s/components/K8sPage.jsx
@@ -0,0 +1,689 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import {
+ ShipWheel, RefreshCw, Plus, Trash2, Server, Boxes, Network,
+ Layers, RotateCw, ScrollText, Star, Cable, FileCode, X,
+} from 'lucide-react';
+import api from '@/services/api';
+import { PageTopbar, Pill } from '@/components/ds';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import Modal from '@/components/Modal';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import EmptyState from '@/components/EmptyState';
+import { useToast } from '@/contexts/ToastContext';
+
+import '../styles/k8s.scss';
+
+// Route-driven tabs (manifest maps /k8s and /k8s/:tab to this component).
+const TABS = [
+ { slug: 'overview', to: '/k8s', label: 'Overview', end: true },
+ { slug: 'workloads', to: '/k8s/workloads', label: 'Workloads' },
+ { slug: 'pods', to: '/k8s/pods', label: 'Pods' },
+ { slug: 'services', to: '/k8s/services', label: 'Services' },
+ { slug: 'nodes', to: '/k8s/nodes', label: 'Nodes' },
+ { slug: 'apply', to: '/k8s/apply', label: 'Apply' },
+ { slug: 'clusters', to: '/k8s/clusters', label: 'Clusters' },
+];
+const VALID_TABS = TABS.map((t) => t.slug);
+
+const phasePill = (phase) => {
+ const kind = phase === 'Running' || phase === 'Succeeded' || phase === 'Active'
+ ? 'green'
+ : phase === 'Pending' ? 'amber' : phase === 'Failed' ? 'red' : 'gray';
+ return <Pill kind={kind}>{phase || 'Unknown'}</Pill>;
+};
+
+const K8sPage = () => {
+ const toast = useToast();
+ const navigate = useNavigate();
+ const { tab } = useParams();
+ const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';
+
+ const [kubectlAvailable, setKubectlAvailable] = useState(true);
+ const [clusters, setClusters] = useState([]);
+ const [selectedId, setSelectedId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+ const [confirmDialog, setConfirmDialog] = useState(null);
+
+ // Per-tab data
+ const [overview, setOverview] = useState(null);
+ const [namespace, setNamespace] = useState('all');
+ const [namespaces, setNamespaces] = useState([]);
+ const [workloadKind, setWorkloadKind] = useState('deployment');
+ const [rows, setRows] = useState([]);
+ const [dataLoading, setDataLoading] = useState(false);
+
+ // Modals
+ const [addClusterOpen, setAddClusterOpen] = useState(false);
+ const [addForm, setAddForm] = useState({ name: '', context: '', kubeconfig: '', make_default: false });
+ const [logsModal, setLogsModal] = useState(null); // {pod, namespace, container, text, loading}
+ const [manifest, setManifest] = useState('');
+ const [applyOutput, setApplyOutput] = useState(null);
+
+ const selected = useMemo(
+ () => clusters.find((c) => String(c.id) === String(selectedId)) || null,
+ [clusters, selectedId],
+ );
+
+ // ── Cluster list ──
+ const loadStatus = useCallback(async () => {
+ setLoading(true);
+ try {
+ const data = await api.request('/k8s/status');
+ setKubectlAvailable(data.kubectl_available);
+ setClusters(data.clusters || []);
+ setSelectedId((prev) => {
+ if (prev && (data.clusters || []).some((c) => String(c.id) === String(prev))) return prev;
+ return data.default_cluster_id || (data.clusters?.[0]?.id ?? null);
+ });
+ } catch (error) {
+ toast.error(`Could not load Kubernetes status: ${error.message}`);
+ } finally {
+ setLoading(false);
+ }
+ }, [toast]);
+
+ useEffect(() => { loadStatus(); }, [loadStatus]);
+
+ // ── Namespaces (for the namespace filter) ──
+ const loadNamespaces = useCallback(async () => {
+ if (!selected || !kubectlAvailable) return;
+ try {
+ const data = await api.request(`/k8s/clusters/${selected.id}/namespaces`);
+ setNamespaces((data.items || []).map((n) => n.name).filter(Boolean));
+ } catch { /* namespace filter is optional */ }
+ }, [selected, kubectlAvailable]);
+
+ useEffect(() => { loadNamespaces(); }, [loadNamespaces]);
+
+ // ── Tab data ──
+ const loadTab = useCallback(async () => {
+ if (!selected || !kubectlAvailable) { setRows([]); setOverview(null); return; }
+ setDataLoading(true);
+ try {
+ if (activeTab === 'overview') {
+ setOverview(await api.request(`/k8s/clusters/${selected.id}/overview`));
+ } else if (activeTab === 'workloads') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/workloads?namespace=${namespace}&kind=${workloadKind}`);
+ setRows(data.items || []);
+ } else if (activeTab === 'pods') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/pods?namespace=${namespace}`);
+ setRows(data.items || []);
+ } else if (activeTab === 'services') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/services?namespace=${namespace}`);
+ setRows(data.items || []);
+ } else if (activeTab === 'nodes') {
+ const data = await api.request(`/k8s/clusters/${selected.id}/nodes`);
+ setRows(data.items || []);
+ }
+ } catch (error) {
+ toast.error(error.message);
+ setRows([]);
+ } finally {
+ setDataLoading(false);
+ }
+ }, [selected, kubectlAvailable, activeTab, namespace, workloadKind, toast]);
+
+ useEffect(() => { loadTab(); }, [loadTab]);
+
+ // ── Cluster actions ──
+ const handleAddCluster = async () => {
+ if (!addForm.name.trim() || !addForm.kubeconfig.trim()) {
+ toast.error('Name and kubeconfig are required.');
+ return;
+ }
+ setBusy(true);
+ try {
+ await api.request('/k8s/clusters', { method: 'POST', body: addForm });
+ toast.success(`Cluster "${addForm.name}" added`);
+ setAddClusterOpen(false);
+ setAddForm({ name: '', context: '', kubeconfig: '', make_default: false });
+ await loadStatus();
+ } catch (error) {
+ toast.error(`Could not add cluster: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleDeleteCluster = (cluster) => {
+ setConfirmDialog({
+ title: `Remove ${cluster.name}?`,
+ message: 'This deletes the stored connection and its kubeconfig from the panel. The cluster itself is not touched.',
+ confirmText: 'Remove',
+ variant: 'destructive',
+ onConfirm: async () => {
+ setConfirmDialog(null);
+ try {
+ await api.request(`/k8s/clusters/${cluster.id}`, { method: 'DELETE' });
+ toast.success('Cluster removed');
+ await loadStatus();
+ } catch (error) {
+ toast.error(error.message);
+ }
+ },
+ onCancel: () => setConfirmDialog(null),
+ });
+ };
+
+ const handleSetDefault = async (cluster) => {
+ try {
+ await api.request(`/k8s/clusters/${cluster.id}/default`, { method: 'POST' });
+ await loadStatus();
+ } catch (error) {
+ toast.error(error.message);
+ }
+ };
+
+ const handleTest = async (cluster) => {
+ setBusy(true);
+ try {
+ const res = await api.request(`/k8s/clusters/${cluster.id}/test`, { method: 'POST' });
+ if (res.ok) toast.success(`Reachable — ${res.server_version}`);
+ else toast.error(`Unreachable: ${res.error}`);
+ await loadStatus();
+ } catch (error) {
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // ── Workload actions ──
+ const handleScale = (w, delta) => {
+ const next = Math.max(0, (w.desired || 0) + delta);
+ return doScale(w, next);
+ };
+
+ const doScale = async (w, replicas) => {
+ setBusy(true);
+ try {
+ await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/scale`,
+ { method: 'POST', body: { replicas } });
+ toast.success(`Scaled ${w.name} to ${replicas}`);
+ await loadTab();
+ } catch (error) {
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleRestart = async (w) => {
+ setBusy(true);
+ try {
+ await api.request(`/k8s/clusters/${selected.id}/deployments/${w.namespace}/${w.name}/restart`,
+ { method: 'POST' });
+ toast.success(`Restart triggered for ${w.name}`);
+ } catch (error) {
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleDeleteResource = (kind, row) => {
+ setConfirmDialog({
+ title: `Delete ${kind} ${row.name}?`,
+ message: `This removes ${row.name} from namespace ${row.namespace} on the live cluster.`,
+ confirmText: 'Delete',
+ variant: 'destructive',
+ onConfirm: async () => {
+ setConfirmDialog(null);
+ try {
+ await api.request(`/k8s/clusters/${selected.id}/delete-resource`,
+ { method: 'POST', body: { kind, name: row.name, namespace: row.namespace } });
+ toast.success(`${kind} ${row.name} deleted`);
+ await loadTab();
+ } catch (error) {
+ toast.error(error.message);
+ }
+ },
+ onCancel: () => setConfirmDialog(null),
+ });
+ };
+
+ // ── Pod logs ──
+ const openLogs = async (pod) => {
+ const container = pod.containers?.[0] || '';
+ setLogsModal({ pod: pod.name, namespace: pod.namespace, container, text: '', loading: true });
+ try {
+ const q = container ? `?container=${container}&tail=200` : '?tail=200';
+ const data = await api.request(`/k8s/clusters/${selected.id}/pods/${pod.namespace}/${pod.name}/logs${q}`);
+ setLogsModal((m) => m && ({ ...m, text: data.logs || '(no output)', loading: false }));
+ } catch (error) {
+ setLogsModal((m) => m && ({ ...m, text: `Error: ${error.message}`, loading: false }));
+ }
+ };
+
+ // ── Apply ──
+ const handleApply = async () => {
+ if (!manifest.trim()) { toast.error('Paste a manifest first.'); return; }
+ setBusy(true);
+ setApplyOutput(null);
+ try {
+ const res = await api.request(`/k8s/clusters/${selected.id}/apply`, { method: 'POST', body: { manifest } });
+ setApplyOutput(res.output || '(applied)');
+ toast.success('Manifest applied');
+ } catch (error) {
+ setApplyOutput(`Error: ${error.message}`);
+ toast.error(error.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // ── Renderers ──
+ const NamespaceFilter = () => (
+ <div className="k8s-filter">
+ <Label>Namespace</Label>
+ <select className="k8s-select" value={namespace} onChange={(e) => setNamespace(e.target.value)}>
+ <option value="all">All namespaces</option>
+ {namespaces.map((n) => <option key={n} value={n}>{n}</option>)}
+ </select>
+ </div>
+ );
+
+ const renderOverview = () => {
+ if (dataLoading && !overview) return <EmptyState loading title="Querying cluster..." />;
+ if (!overview) return <EmptyState icon={ShipWheel} title="No data" description="Select a reachable cluster." />;
+ if (!overview.reachable) {
+ return (
+ <div className="card">
+ <div className="card-body">
+ <EmptyState icon={Cable} title="Cluster unreachable"
+ description={overview.error || 'kubectl could not reach the API server with the stored kubeconfig.'} />
+ <div className="k8s-center">
+ <Button variant="outline" size="sm" onClick={() => handleTest(selected)}>
+ <RefreshCw size={14} /> Retry
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ const c = overview.counts;
+ const cards = [
+ { label: 'Server', value: overview.server_version, icon: ShipWheel },
+ { label: 'Nodes ready', value: `${c.nodes_ready}/${c.nodes}`, icon: Server },
+ { label: 'Namespaces', value: c.namespaces, icon: Layers },
+ { label: 'Pods running', value: `${c.pods_running}/${c.pods}`, icon: Boxes },
+ { label: 'Deployments', value: c.deployments, icon: Network },
+ ];
+ return (
+ <div className="k8s-kpis">
+ {cards.map((k) => (
+ <div className="card k8s-kpi" key={k.label}>
+ <div className="card-body">
+ <div className="k8s-kpi__icon"><k.icon size={18} /></div>
+ <div className="k8s-kpi__val">{k.value ?? '—'}</div>
+ <div className="k8s-kpi__label">{k.label}</div>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+ };
+
+ const renderWorkloads = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Workloads</h3>
+ <div className="card-actions k8s-toolbar">
+ <select className="k8s-select" value={workloadKind} onChange={(e) => setWorkloadKind(e.target.value)}>
+ <option value="deployment">Deployments</option>
+ <option value="statefulset">StatefulSets</option>
+ <option value="daemonset">DaemonSets</option>
+ </select>
+ <NamespaceFilter />
+ </div>
+ </div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading workloads..." />
+ : rows.length === 0 ? <EmptyState icon={Network} title="No workloads" description="Nothing found in this namespace." />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Namespace</th><th>Replicas</th><th>Status</th><th>Image</th><th /></tr>
+ </thead>
+ <tbody>
+ {rows.map((w) => (
+ <tr key={`${w.namespace}/${w.name}`}>
+ <td className="sk-cell-mono">{w.name}</td>
+ <td>{w.namespace}</td>
+ <td>
+ {workloadKind === 'deployment' ? (
+ <span className="k8s-scale">
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, -1)}>−</Button>
+ <span className="k8s-scale__n">{w.ready}/{w.desired}</span>
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleScale(w, +1)}>+</Button>
+ </span>
+ ) : <span className="sk-cell-mono">{w.ready}/{w.desired}</span>}
+ </td>
+ <td><Pill kind={w.healthy ? 'green' : 'amber'}>{w.healthy ? 'healthy' : 'degraded'}</Pill></td>
+ <td className="sk-cell-mono k8s-truncate" title={(w.images || []).join(', ')}>{(w.images || [])[0] || '—'}</td>
+ <td className="k8s-row-actions">
+ {workloadKind === 'deployment' && (
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRestart(w)} title="Rolling restart">
+ <RotateCw size={14} />
+ </Button>
+ )}
+ <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource(workloadKind, w)}>
+ <Trash2 size={14} />
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderPods = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Pods</h3>
+ <div className="card-actions"><NamespaceFilter /></div>
+ </div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading pods..." />
+ : rows.length === 0 ? <EmptyState icon={Boxes} title="No pods" description="Nothing running in this namespace." />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Namespace</th><th>Ready</th><th>Status</th><th>Restarts</th><th>Node</th><th /></tr>
+ </thead>
+ <tbody>
+ {rows.map((p) => (
+ <tr key={`${p.namespace}/${p.name}`}>
+ <td className="sk-cell-mono k8s-truncate" title={p.name}>{p.name}</td>
+ <td>{p.namespace}</td>
+ <td className="sk-cell-mono">{p.ready}</td>
+ <td>{phasePill(p.phase)}</td>
+ <td className="sk-cell-mono">{p.restarts > 0 ? <Pill kind="amber">{p.restarts}</Pill> : 0}</td>
+ <td className="sk-cell-mono k8s-truncate">{p.node || '—'}</td>
+ <td className="k8s-row-actions">
+ <Button variant="secondary" size="sm" onClick={() => openLogs(p)} title="Logs">
+ <ScrollText size={14} />
+ </Button>
+ <Button variant="destructive" size="sm" disabled={busy} onClick={() => handleDeleteResource('pod', p)}>
+ <Trash2 size={14} />
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderServices = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Services</h3>
+ <div className="card-actions"><NamespaceFilter /></div>
+ </div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading services..." />
+ : rows.length === 0 ? <EmptyState icon={Cable} title="No services" />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Namespace</th><th>Type</th><th>Cluster IP</th><th>External</th><th>Ports</th></tr>
+ </thead>
+ <tbody>
+ {rows.map((s) => (
+ <tr key={`${s.namespace}/${s.name}`}>
+ <td className="sk-cell-mono">{s.name}</td>
+ <td>{s.namespace}</td>
+ <td><Pill kind={s.type === 'LoadBalancer' ? 'green' : 'gray'}>{s.type}</Pill></td>
+ <td className="sk-cell-mono">{s.cluster_ip || '—'}</td>
+ <td className="sk-cell-mono">{s.external_ip || '—'}</td>
+ <td className="sk-cell-mono">{(s.ports || []).join(', ') || '—'}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderNodes = () => (
+ <div className="card sec-flush">
+ <div className="card-header"><h3>Nodes</h3></div>
+ <div className="card-body">
+ {dataLoading ? <EmptyState loading title="Loading nodes..." />
+ : rows.length === 0 ? <EmptyState icon={Server} title="No nodes" />
+ : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Status</th><th>Roles</th><th>Version</th><th>OS</th><th>CPU</th><th>Memory</th></tr>
+ </thead>
+ <tbody>
+ {rows.map((n) => (
+ <tr key={n.name}>
+ <td className="sk-cell-mono">{n.name}</td>
+ <td><Pill kind={n.ready ? 'green' : 'red'}>{n.ready ? 'Ready' : 'NotReady'}</Pill></td>
+ <td>{(n.roles || []).join(', ')}</td>
+ <td className="sk-cell-mono">{n.kubelet_version || '—'}</td>
+ <td className="k8s-truncate" title={n.os_image}>{n.os_image || '—'}</td>
+ <td className="sk-cell-mono">{n.cpu || '—'}</td>
+ <td className="sk-cell-mono">{n.memory || '—'}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderApply = () => (
+ <div className="card">
+ <div className="card-header"><h3>Apply manifest</h3></div>
+ <div className="card-body k8s-apply">
+ <p className="text-muted">
+ Paste a Kubernetes YAML or JSON manifest. It is sent to the selected cluster with
+ <code> kubectl apply -f -</code>. Admin only.
+ </p>
+ <textarea
+ className="k8s-textarea"
+ rows={16}
+ spellCheck={false}
+ placeholder={'apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: demo'}
+ value={manifest}
+ onChange={(e) => setManifest(e.target.value)}
+ />
+ <div className="k8s-apply__actions">
+ <Button variant="default" size="sm" disabled={busy || !selected} onClick={handleApply}>
+ <FileCode size={14} /> Apply
+ </Button>
+ <Button variant="outline" size="sm" onClick={() => { setManifest(''); setApplyOutput(null); }}>Clear</Button>
+ </div>
+ {applyOutput != null && <pre className="k8s-output">{applyOutput}</pre>}
+ </div>
+ </div>
+ );
+
+ const renderClusters = () => (
+ <div className="card sec-flush">
+ <div className="card-header">
+ <h3>Clusters</h3>
+ <div className="card-actions">
+ <Button variant="default" size="sm" onClick={() => setAddClusterOpen(true)}>
+ <Plus size={14} /> Add cluster
+ </Button>
+ </div>
+ </div>
+ <div className="card-body">
+ {clusters.length === 0 ? (
+ <EmptyState icon={ShipWheel} title="No clusters yet"
+ description="Add a cluster by pasting its kubeconfig to start managing workloads." />
+ ) : (
+ <table className="sk-dtable">
+ <thead>
+ <tr><th>Name</th><th>Context</th><th>Reachable</th><th>Server</th><th>Last checked</th><th /></tr>
+ </thead>
+ <tbody>
+ {clusters.map((c) => (
+ <tr key={c.id}>
+ <td className="sk-cell-mono">
+ {c.is_default && <Star size={12} className="k8s-default-star" title="Default" />} {c.name}
+ </td>
+ <td className="sk-cell-mono">{c.context || '—'}</td>
+ <td>
+ {c.last_reachable == null
+ ? <Pill kind="gray">unknown</Pill>
+ : <Pill kind={c.last_reachable ? 'green' : 'red'}>{c.last_reachable ? 'yes' : 'no'}</Pill>}
+ </td>
+ <td className="sk-cell-mono">{c.status?.server_version || '—'}</td>
+ <td className="sk-cell-mono">{c.last_checked_at ? new Date(c.last_checked_at).toLocaleString() : '—'}</td>
+ <td className="k8s-row-actions">
+ <Button variant="secondary" size="sm" disabled={busy || !kubectlAvailable} onClick={() => handleTest(c)}>Test</Button>
+ {!c.is_default && <Button variant="secondary" size="sm" onClick={() => handleSetDefault(c)}>Set default</Button>}
+ <Button variant="destructive" size="sm" onClick={() => handleDeleteCluster(c)}><Trash2 size={14} /></Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+
+ // ── Page shell ──
+ if (loading) {
+ return (
+ <div className="page-container k8s-page">
+ <PageTopbar icon={<ShipWheel size={18} />} title="Kubernetes" />
+ <EmptyState loading title="Loading Kubernetes..." />
+ </div>
+ );
+ }
+
+ const topbarTabs = TABS.map(({ to, label, end }) => ({ to, label, end }));
+ const needsCluster = activeTab !== 'clusters' && clusters.length === 0;
+
+ return (
+ <div className="page-container k8s-page">
+ <PageTopbar
+ icon={<ShipWheel size={18} />}
+ title="Kubernetes"
+ meta={<>kubectl · clusters · workloads</>}
+ tabs={topbarTabs}
+ actions={
+ <div className="k8s-topbar-actions">
+ {clusters.length > 0 && activeTab !== 'clusters' && (
+ <select className="k8s-select" value={selectedId ?? ''} onChange={(e) => setSelectedId(e.target.value)}>
+ {clusters.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
+ </select>
+ )}
+ <Button variant="outline" size="sm" onClick={() => { loadStatus(); loadTab(); }}>
+ <RefreshCw size={14} /> Refresh
+ </Button>
+ </div>
+ }
+ />
+
+ {!kubectlAvailable && (
+ <div className="card k8s-warn">
+ <div className="card-body">
+ <strong>kubectl is not installed on the panel host.</strong> You can still add and
+ store cluster connections, but live cluster data and actions are unavailable until
+ <code> kubectl</code> is on the panel host PATH.
+ </div>
+ </div>
+ )}
+
+ {needsCluster ? (
+ <div className="card">
+ <div className="card-body">
+ <EmptyState icon={ShipWheel} title="No clusters connected"
+ description="Add a cluster on the Clusters tab by pasting its kubeconfig." />
+ <div className="k8s-center">
+ <Button variant="default" size="sm" onClick={() => navigate('/k8s/clusters')}>
+ <Plus size={14} /> Go to Clusters
+ </Button>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <>
+ {activeTab === 'overview' && renderOverview()}
+ {activeTab === 'workloads' && renderWorkloads()}
+ {activeTab === 'pods' && renderPods()}
+ {activeTab === 'services' && renderServices()}
+ {activeTab === 'nodes' && renderNodes()}
+ {activeTab === 'apply' && renderApply()}
+ {activeTab === 'clusters' && renderClusters()}
+ </>
+ )}
+
+ {/* Add cluster modal */}
+ <Modal open={addClusterOpen} onClose={() => setAddClusterOpen(false)} title="Add Kubernetes cluster">
+ <div className="k8s-form">
+ <div className="form-group">
+ <Label>Name</Label>
+ <Input type="text" value={addForm.name} placeholder="prod-eu"
+ onChange={(e) => setAddForm((f) => ({ ...f, name: e.target.value }))} />
+ </div>
+ <div className="form-group">
+ <Label>Context (optional)</Label>
+ <Input type="text" value={addForm.context} placeholder="Leave blank for the kubeconfig's current-context"
+ onChange={(e) => setAddForm((f) => ({ ...f, context: e.target.value }))} />
+ </div>
+ <div className="form-group">
+ <Label>Kubeconfig</Label>
+ <textarea className="k8s-textarea" rows={10} spellCheck={false}
+ placeholder="Paste the full kubeconfig YAML here"
+ value={addForm.kubeconfig}
+ onChange={(e) => setAddForm((f) => ({ ...f, kubeconfig: e.target.value }))} />
+ <p className="text-muted">Stored encrypted with the panel key. Never shown again after saving.</p>
+ </div>
+ <label className="k8s-checkbox">
+ <input type="checkbox" checked={addForm.make_default}
+ onChange={(e) => setAddForm((f) => ({ ...f, make_default: e.target.checked }))} />
+ Make this the default cluster
+ </label>
+ </div>
+ <div className="modal-footer">
+ <Button variant="outline" onClick={() => setAddClusterOpen(false)}>Cancel</Button>
+ <Button variant="default" onClick={handleAddCluster} disabled={busy}>Add cluster</Button>
+ </div>
+ </Modal>
+
+ {/* Logs modal */}
+ <Modal open={!!logsModal} onClose={() => setLogsModal(null)}
+ title={logsModal ? `Logs · ${logsModal.pod}` : 'Logs'}>
+ {logsModal?.loading
+ ? <EmptyState loading title="Fetching logs..." />
+ : <pre className="k8s-logs">{logsModal?.text}</pre>}
+ <div className="modal-footer">
+ <Button variant="outline" onClick={() => setLogsModal(null)}><X size={14} /> Close</Button>
+ </div>
+ </Modal>
+
+ {confirmDialog && (
+ <ConfirmDialog
+ title={confirmDialog.title}
+ message={confirmDialog.message}
+ confirmText={confirmDialog.confirmText}
+ variant={confirmDialog.variant}
+ onConfirm={confirmDialog.onConfirm}
+ onCancel={confirmDialog.onCancel}
+ />
+ )}
+ </div>
+ );
+};
+
+export default K8sPage;
diff --git a/frontend/src/plugins/serverkit-k8s/index.jsx b/frontend/src/plugins/serverkit-k8s/index.jsx
new file mode 100644
index 00000000..bb282478
--- /dev/null
+++ b/frontend/src/plugins/serverkit-k8s/index.jsx
@@ -0,0 +1,7 @@
+// Kubernetes cluster management UI, contributed through the extension system.
+// Fully self-contained in the extension. After sync this folder lives at
+// frontend/src/plugins/serverkit-k8s/, so '@/…' host aliases resolve.
+export { default as K8sPage } from './components/K8sPage.jsx';
+
+// No default export on purpose: PluginLoader legacy-auto-renders any plugin
+// default export globally. The route contribution resolves the NAMED export.
diff --git a/frontend/src/plugins/serverkit-k8s/plugin.json b/frontend/src/plugins/serverkit-k8s/plugin.json
new file mode 100644
index 00000000..5e8791e6
--- /dev/null
+++ b/frontend/src/plugins/serverkit-k8s/plugin.json
@@ -0,0 +1,56 @@
+{
+ "name": "serverkit-k8s",
+ "display_name": "Kubernetes",
+ "version": "1.0.0",
+ "description": "Manage remote Kubernetes clusters from the panel. Add a cluster by pasting its kubeconfig (stored encrypted, one row per cluster) and the extension shells out to kubectl to show cluster health, nodes, namespaces, workloads, pods with live logs, services, and ingresses, plus scale, restart, delete, and apply-manifest actions. Most panels never touch Kubernetes, so it ships as an opt-in extension and needs no cluster on the panel host itself.",
+ "author": "ServerKit",
+ "license": "MIT",
+ "category": "deployment",
+ "homepage": "https://github.com/jhd3197/ServerKit",
+ "permissions": [
+ "shell",
+ "filesystem",
+ "network"
+ ],
+ "min_panel_version": "1.7.0",
+ "entry_point": "k8s:k8s_bp",
+ "url_prefix": "/api/v1/k8s",
+ "models": "models:register",
+ "lifecycle": {
+ "install": "lifecycle:on_install",
+ "uninstall": "lifecycle:on_uninstall"
+ },
+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>",
+ "contributions": {
+ "nav": [
+ {
+ "id": "k8s",
+ "label": "Kubernetes",
+ "route": "/k8s",
+ "category": "infrastructure",
+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"8\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 2v7.5\"/><path d=\"m19 5-5.23 5.23\"/><path d=\"M22 12h-7.5\"/><path d=\"m19 19-5.23-5.23\"/><path d=\"M12 14.5V22\"/><path d=\"M10.23 13.77 5 19\"/><path d=\"M9.5 12H2\"/><path d=\"M10.23 10.23 5 5\"/>"
+ }
+ ],
+ "routes": [
+ {
+ "path": "k8s",
+ "component": "K8sPage"
+ },
+ {
+ "path": "k8s/:tab",
+ "component": "K8sPage"
+ }
+ ],
+ "page_titles": {
+ "/k8s": "Kubernetes"
+ },
+ "command_palette": [
+ {
+ "label": "Kubernetes",
+ "path": "/k8s",
+ "category": "Pages",
+ "keywords": "k8s kubernetes kubectl cluster node namespace pod deployment workload statefulset daemonset service ingress scale restart apply kubeconfig"
+ }
+ ]
+ }
+}
diff --git a/frontend/src/plugins/serverkit-k8s/styles/k8s.scss b/frontend/src/plugins/serverkit-k8s/styles/k8s.scss
new file mode 100644
index 00000000..7c732390
--- /dev/null
+++ b/frontend/src/plugins/serverkit-k8s/styles/k8s.scss
@@ -0,0 +1,177 @@
+/* Kubernetes extension — layout-only styles. Colors, typography, spacing and
+ controls all inherit from the host design system (card, sk-dtable, Pill,
+ empty-state, form controls). No hardcoded palette; surface tints lean on
+ currentColor / neutral rgba so they read in both themes. */
+
+.k8s-page {
+ .k8s-topbar-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .k8s-select {
+ height: 32px;
+ padding: 0 10px;
+ border-radius: 6px;
+ border: 1px solid rgba(128, 128, 128, 0.35);
+ background: transparent;
+ color: inherit;
+ font-size: 13px;
+ }
+
+ .k8s-filter {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ label {
+ margin: 0;
+ white-space: nowrap;
+ }
+ }
+
+ .k8s-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+ }
+
+ .k8s-warn {
+ margin-bottom: 16px;
+
+ code {
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: rgba(128, 128, 128, 0.15);
+ }
+ }
+
+ .k8s-center {
+ display: flex;
+ justify-content: center;
+ margin-top: 12px;
+ }
+
+ /* Overview KPI band */
+ .k8s-kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 12px;
+ }
+
+ .k8s-kpi {
+ .card-body {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ &__icon {
+ opacity: 0.6;
+ margin-bottom: 4px;
+ }
+
+ &__val {
+ font-size: 20px;
+ font-weight: 600;
+ word-break: break-word;
+ }
+
+ &__label {
+ font-size: 12px;
+ opacity: 0.7;
+ }
+ }
+
+ /* Tables */
+ .k8s-row-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ justify-content: flex-end;
+ }
+
+ .k8s-truncate {
+ max-width: 240px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .k8s-scale {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+
+ &__n {
+ min-width: 44px;
+ text-align: center;
+ font-variant-numeric: tabular-nums;
+ }
+ }
+
+ .k8s-default-star {
+ color: #eab308;
+ vertical-align: middle;
+ }
+
+ /* Forms */
+ .k8s-form {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+
+ .k8s-textarea,
+ .k8s-logs,
+ .k8s-output {
+ width: 100%;
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12.5px;
+ border-radius: 8px;
+ border: 1px solid rgba(128, 128, 128, 0.3);
+ background: rgba(128, 128, 128, 0.06);
+ color: inherit;
+ padding: 12px;
+ box-sizing: border-box;
+ }
+
+ .k8s-textarea {
+ resize: vertical;
+ }
+
+ .k8s-checkbox {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ cursor: pointer;
+ }
+
+ /* Apply */
+ .k8s-apply {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ &__actions {
+ display: flex;
+ gap: 8px;
+ }
+ }
+
+ .k8s-logs,
+ .k8s-output {
+ max-height: 55vh;
+ overflow: auto;
+ white-space: pre-wrap;
+ word-break: break-word;
+ margin: 0;
+ }
+
+ .k8s-output {
+ margin-top: 4px;
+ }
+}