|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import openshift_client as oc |
| 4 | +import logging |
| 5 | +import json |
| 6 | +from datetime import datetime, timezone |
| 7 | +from helpers import ( |
| 8 | + parse_rfc3339, |
| 9 | + as_bool, |
| 10 | + build_user_cutoff_map, |
| 11 | + get_running_notebooks, |
| 12 | + get_notebook_username_map, |
| 13 | +) |
| 14 | + |
| 15 | +LOG = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +def get_class_ns(culler: dict) -> tuple[dict, dict]: |
| 19 | + """ |
| 20 | + build multi ns and single ns dicts |
| 21 | + """ |
| 22 | + multi_ns: dict[str, dict] = {} |
| 23 | + single_ns: dict[str, dict] = {} |
| 24 | + |
| 25 | + for class_name, config in culler.items(): |
| 26 | + cutoff = int(config["cutoff"]) |
| 27 | + ns = config["ns"] |
| 28 | + mult_ns = as_bool(config.get("multiple-ns", False)) |
| 29 | + |
| 30 | + if mult_ns: |
| 31 | + multi_ns[class_name] = { |
| 32 | + "cutoff": cutoff, |
| 33 | + "prefix": ns, |
| 34 | + } |
| 35 | + else: |
| 36 | + single_ns[class_name] = { |
| 37 | + "cutoff": cutoff, |
| 38 | + "namespace": ns, |
| 39 | + } |
| 40 | + |
| 41 | + return multi_ns, single_ns |
| 42 | + |
| 43 | + |
| 44 | +def stop_notebook(nb_name: str, started_at: str, namespace: str, cutoff_seconds: int) -> bool: |
| 45 | + """ Patch notebook if past cutoff. Returns True if stopped. """ |
| 46 | + start_dt = parse_rfc3339(started_at) |
| 47 | + age_seconds = int((datetime.now(timezone.utc) - start_dt).total_seconds()) |
| 48 | + |
| 49 | + if age_seconds <= cutoff_seconds: |
| 50 | + LOG.info( |
| 51 | + "Notebook %s/%s within cutoff (age=%ss < cutoff=%ss)", |
| 52 | + namespace, nb_name, age_seconds, cutoff_seconds |
| 53 | + ) |
| 54 | + return False |
| 55 | + |
| 56 | + now_utc = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 57 | + patch_obj = { |
| 58 | + "metadata": { |
| 59 | + "annotations": {"kubeflow-resource-stopped": now_utc} |
| 60 | + } |
| 61 | + } |
| 62 | + oc.invoke("patch", ["notebook", nb_name, "-n", namespace, "--type=merge", "-p", json.dumps(patch_obj)]) |
| 63 | + LOG.info("Patched notebook %s/%s (age=%ss > cutoff=%ss)", namespace, nb_name, age_seconds, cutoff_seconds) |
| 64 | + return True |
| 65 | + |
| 66 | + |
| 67 | +def process_single(single_ns: dict[str, dict]) -> None: |
| 68 | + if not single_ns: |
| 69 | + LOG.info("No single namespace classes configured") |
| 70 | + return |
| 71 | + |
| 72 | + namespace = next(iter(single_ns.values()))["namespace"] |
| 73 | + |
| 74 | + LOG.info("Processing shared single namespace %s for %d class(es)", namespace, len(single_ns)) |
| 75 | + |
| 76 | + try: |
| 77 | + user_to_info = build_user_cutoff_map(single_ns) |
| 78 | + |
| 79 | + with oc.project(namespace): |
| 80 | + running = get_running_notebooks(namespace) |
| 81 | + username_map = get_notebook_username_map(namespace) |
| 82 | + |
| 83 | + for nb in running: |
| 84 | + nb_name = nb["name"] |
| 85 | + |
| 86 | + username = username_map.get(nb_name) |
| 87 | + if not username: |
| 88 | + LOG.warning("Notebook %s missing username annotation, skipping", nb_name) |
| 89 | + continue |
| 90 | + |
| 91 | + info = user_to_info.get(username) |
| 92 | + if not info: |
| 93 | + try: |
| 94 | + pvc = f"jupyterhub-nb-{nb_name.removeprefix('jupyter-nb-')}-pvc" |
| 95 | + oc.invoke("delete", ["notebook", nb_name, "-n", namespace]) |
| 96 | + oc.invoke("delete", ["pvc", pvc, "-n", namespace]) |
| 97 | + |
| 98 | + LOG.info("Deleted notebook %s and pvc %s in namespace %s", nb_name, pvc, namespace) |
| 99 | + except Exception as e: |
| 100 | + LOG.error("Failed deleting notebook %s or pvc in namespace %s: %s", nb_name,namespace, e) |
| 101 | + continue |
| 102 | + |
| 103 | + stop_notebook(nb_name, nb["startedAt"], namespace, info["cutoff"]) |
| 104 | + |
| 105 | + except Exception as e: |
| 106 | + LOG.error("Error processing shared single namespace %s: %s", namespace, e) |
| 107 | + |
| 108 | + |
| 109 | +def process_multi(multi_ns: dict[str, dict]) -> None: |
| 110 | + matchers: list[tuple[str, int]] = [] |
| 111 | + for class_name, cfg in multi_ns.items(): |
| 112 | + prefix = str(cfg["prefix"]).strip() |
| 113 | + cutoff = int(cfg["cutoff"]) |
| 114 | + if prefix: |
| 115 | + matchers.append((prefix, cutoff)) |
| 116 | + |
| 117 | + if not matchers: |
| 118 | + LOG.info("No multi-namespace classes configured") |
| 119 | + return |
| 120 | + |
| 121 | + matchers.sort(key=lambda x: len(x[0]), reverse=True) |
| 122 | + |
| 123 | + try: |
| 124 | + running_all = get_running_notebooks() |
| 125 | + except Exception as e: |
| 126 | + LOG.error("Failed to list running notebooks across all namespaces: %s", e) |
| 127 | + return |
| 128 | + |
| 129 | + matched = 0 |
| 130 | + for nb in running_all: |
| 131 | + ns = nb["namespace"] |
| 132 | + |
| 133 | + cutoff = None |
| 134 | + for prefix, c in matchers: |
| 135 | + if ns == prefix or ns.startswith(prefix + "-"): |
| 136 | + cutoff = c if cutoff is None else max(cutoff, c) |
| 137 | + |
| 138 | + if cutoff is None: |
| 139 | + continue |
| 140 | + |
| 141 | + matched += 1 |
| 142 | + stop_notebook(nb["name"], nb["startedAt"], ns, cutoff) |
| 143 | + |
| 144 | + LOG.info("Matched %d running notebooks in multi namespaces", matched) |
| 145 | + |
| 146 | + |
| 147 | +if __name__ == '__main__': |
| 148 | + logging.basicConfig(level='INFO') |
| 149 | + |
| 150 | + culler_dict = json.loads(os.environ["CULLER_DICT"]) |
| 151 | + |
| 152 | + if not culler_dict: |
| 153 | + LOG.error('CULLER_DICT environment variables is required.') |
| 154 | + sys.exit(1) |
| 155 | + |
| 156 | + class_info = get_class_ns(culler_dict) |
| 157 | + multi_ns, single_ns = class_info |
| 158 | + |
| 159 | + process_single(single_ns) |
| 160 | + process_multi(multi_ns) |
0 commit comments