Files

138 lines
5.1 KiB
Python

"""Kubernetes service - kubectl operations via SSH"""
import logging
import shlex
logger = logging.getLogger(__name__)
class K8sService:
def __init__(self, ssh_service, namespace):
self.ssh = ssh_service
self.namespace = namespace
def run(self, kubectl_command, timeout=30, quiet=False):
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}'
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
result = self.ssh.run(full_cmd, timeout=timeout, quiet=quiet)
out, err, rc = result
if rc != 0:
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
else:
logger.debug(f"K8s command OK, output lines: {len(out.split(chr(10))) if out else 0}")
return result
def get_pods(self):
out, err, rc = self.run('get pods -o name')
if rc != 0:
logger.error(f"Failed to get pods: {err}")
return []
pods = [line.replace('pod/', '').strip() for line in (out or '').strip().split('\n') if line.strip()]
logger.debug(f"Found {len(pods)} pods in namespace {self.namespace}")
return pods
def get_running_game_pods(self):
"""List game server pods (sg-*-pod-*) currently in Running phase.
Used as the "server is online" signal, e.g. to block battlegroup
updates while players could be connected.
Returns:
List of running game pod names, [] when none running,
or None when pod status could not be determined.
"""
out, err, rc = self.run(
'get pods --no-headers -o custom-columns=NAME:.metadata.name,STATUS:.status.phase')
if rc != 0:
logger.warning(f"Could not get pod statuses: {err[:100] if err else 'no error'}")
return None
running = []
for line in (out or '').strip().split('\n'):
parts = line.strip().split()
if len(parts) < 2:
continue
name, phase = parts[0], parts[1]
if phase == 'Running' and '-sg-' in name and '-pod-' in name:
running.append(name)
logger.debug(f"Found {len(running)} running game pods in namespace {self.namespace}")
return running
def find_pod_by_pattern(self, pattern):
pods = self.get_pods()
for pod in pods:
if pattern.lower() in pod.lower():
return pod
return None
def get_text_router_pod(self):
pod = self.find_pod_by_pattern('tr-deploy')
if pod:
return pod
pod = self.find_pod_by_pattern('text')
if pod:
return pod
pod = self.find_pod_by_pattern('router')
return pod
def get_rabbitmq_pod(self):
pod = self.find_pod_by_pattern('mq-admin')
if pod:
return pod
pod = self.find_pod_by_pattern('mq-game')
return pod
def get_deployments(self):
out, err, rc = self.run('get deployments -o name')
if rc != 0:
return []
return [d.strip() for d in (out or '').strip().split('\n') if d.strip()]
def _parse_memory_gib(self, raw):
raw = raw.strip().upper()
if raw.endswith('KI'):
return round(int(raw[:-2]) / (1024 ** 3), 1)
if raw.endswith('MI'):
return round(int(raw[:-2]) / 1024, 1)
if raw.endswith('GI'):
return round(int(raw[:-2]), 1)
if raw.endswith('TI'):
return round(int(raw[:-2]) * 1024, 1)
if raw.endswith('PI'):
return round(int(raw[:-2]) * 1024 ** 2, 1)
try:
return round(int(raw) / (1024 ** 3), 1)
except ValueError:
return 0.0
def get_node_metrics(self):
out, err, rc = self.run('top nodes')
if rc == 0 and out.strip():
lines = out.strip().split('\n')
if len(lines) >= 2:
parts = lines[1].split()
if len(parts) >= 4:
cpu_pct_str = parts[2]
mem_str = parts[3]
mem_pct_str = parts[4] if len(parts) >= 5 else ''
return {
'cpu': cpu_pct_str,
'memory': mem_str,
'cpu_pct': parts[1],
'cpu_num': float(cpu_pct_str.rstrip('%')),
'memory_gib': self._parse_memory_gib(mem_str),
'memory_pct': mem_pct_str,
'memory_pct_num': float(mem_pct_str.rstrip('%')) if mem_pct_str else 0.0,
}
return {}
def auto_detect_namespace(self):
out, err, rc = self.ssh.run('sudo kubectl get namespaces -o name', timeout=10)
if rc == 0:
for line in (out or '').strip().split('\n'):
ns = line.replace('namespace/', '').strip()
if ns.startswith('funcom-seabass-'):
logger.info(f"Auto-detected K8s namespace: {ns}")
self.namespace = ns
return ns
return None