|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import contextlib |
| 8 | +import dataclasses |
| 9 | +import importlib |
| 10 | +import importlib.abc |
| 11 | +import importlib.util |
| 12 | +import itertools |
| 13 | +import sys |
| 14 | +import threading |
| 15 | +from pathlib import Path |
| 16 | +from types import ModuleType |
| 17 | +from typing import Dict, List, Optional, Tuple |
| 18 | + |
| 19 | +from monarch.actor_mesh import Actor, endpoint |
| 20 | +from monarch.code_sync import WorkspaceLocation |
| 21 | + |
| 22 | + |
| 23 | +class SysAuditHookGuard(contextlib.AbstractContextManager): |
| 24 | + """ |
| 25 | + A guard (and context manager), which will unregister an import hook when |
| 26 | + closed or deleted. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__(self, hooks, idx): |
| 30 | + self._hooks = hooks |
| 31 | + self._idx = idx |
| 32 | + |
| 33 | + def close(self): |
| 34 | + self._hooks.pop(self._idx, None) |
| 35 | + |
| 36 | + def __enter__(self): |
| 37 | + return self |
| 38 | + |
| 39 | + def __exit__(self, *args): |
| 40 | + self.close() |
| 41 | + |
| 42 | + def __del__(self): |
| 43 | + self.close() |
| 44 | + |
| 45 | + |
| 46 | +class SysAuditHookMultiplexer: |
| 47 | + """ |
| 48 | + Multiplexes import hooks to multiple hooks. |
| 49 | +
|
| 50 | + `sys.addaudithook`s can only be added and not removed, so this class provides |
| 51 | + a global singleton that can be used to multiplex multiple hooks which support |
| 52 | + removal. |
| 53 | + """ |
| 54 | + |
| 55 | + def __init__(self): |
| 56 | + self._idx = itertools.count() |
| 57 | + self._hooks = {} |
| 58 | + |
| 59 | + def _callback(self, event, args): |
| 60 | + for hook in self._hooks.values(): |
| 61 | + hook(event, args) |
| 62 | + |
| 63 | + def add(self, hook) -> SysAuditHookGuard: |
| 64 | + idx = next(self._idx) |
| 65 | + self._hooks[idx] = hook |
| 66 | + return SysAuditHookGuard(self._hooks, idx) |
| 67 | + |
| 68 | + _instance_lock = threading.Lock() |
| 69 | + _instance = None |
| 70 | + |
| 71 | + @classmethod |
| 72 | + def singleton(cls): |
| 73 | + if cls._instance is None: |
| 74 | + with cls._instance_lock: |
| 75 | + if cls._instance is None: |
| 76 | + cls._instance = SysAuditHookMultiplexer() |
| 77 | + sys.addaudithook(cls._instance._callback) |
| 78 | + return cls._instance |
| 79 | + |
| 80 | + |
| 81 | +@dataclasses.dataclass |
| 82 | +class ThreadLocalState(threading.local): |
| 83 | + last_import: Optional[str] = None |
| 84 | + |
| 85 | + |
| 86 | +class SysAuditImportHook: |
| 87 | + """ |
| 88 | + An audit hook that processes and coalesces import/exec events and calls a |
| 89 | + user-defined callback with the module name and module object which was |
| 90 | + imported. |
| 91 | + """ |
| 92 | + |
| 93 | + def __init__(self, callback): |
| 94 | + self._callback = callback |
| 95 | + self._state = ThreadLocalState() |
| 96 | + |
| 97 | + @classmethod |
| 98 | + def install(cls, callback) -> SysAuditHookGuard: |
| 99 | + return SysAuditHookMultiplexer.singleton().add(SysAuditImportHook(callback)) |
| 100 | + |
| 101 | + def _py_filename(self, filename: Path) -> Path: |
| 102 | + if filename.suffix in (".pyc", ".pyo"): |
| 103 | + return filename.with_suffix(".py") |
| 104 | + return filename |
| 105 | + |
| 106 | + def __call__(self, event, args): |
| 107 | + if event == "import": |
| 108 | + # While `filename` is specific as an argument to the import event, it's |
| 109 | + # almost always `None`, so we need to wait for a subsequent exec event |
| 110 | + # to get the filename. |
| 111 | + module, _, _, _, _ = args |
| 112 | + self._state.last_import = module |
| 113 | + elif event == "exec": |
| 114 | + module_name = self._state.last_import |
| 115 | + if module_name is None: |
| 116 | + return |
| 117 | + # We always expect an exec right after an import, so we can clear the |
| 118 | + # last import module name we store. |
| 119 | + self._state.last_import = None |
| 120 | + module = sys.modules.get(module_name) |
| 121 | + if module is None: |
| 122 | + return |
| 123 | + if module.__file__ is None: |
| 124 | + return |
| 125 | + (code_obj,) = args |
| 126 | + if code_obj.co_filename is None: |
| 127 | + return |
| 128 | + # code objects store the original source name, not the pyc |
| 129 | + if self._py_filename(Path(module.__file__)) != Path(code_obj.co_filename): |
| 130 | + return |
| 131 | + self._callback(module_name, module) |
| 132 | + |
| 133 | + |
| 134 | +@dataclasses.dataclass(frozen=True, kw_only=True) |
| 135 | +class Fingerprint: |
| 136 | + mtime: float |
| 137 | + size: int |
| 138 | + |
| 139 | + @classmethod |
| 140 | + def for_path(cls, path: Path) -> "Fingerprint": |
| 141 | + stat = path.stat() |
| 142 | + return Fingerprint(mtime=stat.st_mtime, size=stat.st_size) |
| 143 | + |
| 144 | + |
| 145 | +class AutoReloader: |
| 146 | + """ |
| 147 | + Track changes to modules in a workspace and reload them when they change. |
| 148 | + """ |
| 149 | + |
| 150 | + def __init__(self, workspace: Path, reload=importlib.reload): |
| 151 | + self._workspace = workspace |
| 152 | + self._reload = reload |
| 153 | + self._tracked_modules: Dict[str, Tuple[Path, Fingerprint]] = {} |
| 154 | + self._track_all_imported() |
| 155 | + |
| 156 | + def _maybe_track_module(self, name: str, module: ModuleType): |
| 157 | + filename = getattr(module, "__file__", None) |
| 158 | + if filename is None: |
| 159 | + return |
| 160 | + filename = Path(filename) |
| 161 | + |
| 162 | + # Ignore modules that are not in the workspace. |
| 163 | + if not filename.is_relative_to(self._workspace): |
| 164 | + return |
| 165 | + |
| 166 | + self._tracked_modules[name] = ( |
| 167 | + filename, |
| 168 | + Fingerprint.for_path(filename), |
| 169 | + ) |
| 170 | + |
| 171 | + def _track_all_imported(self): |
| 172 | + for name, module in sys.modules.items(): |
| 173 | + if module is None: |
| 174 | + continue |
| 175 | + self._maybe_track_module(name, module) |
| 176 | + |
| 177 | + def import_callback(self, name: str, module: ModuleType): |
| 178 | + """ |
| 179 | + Callback for when a module has been imported. |
| 180 | + """ |
| 181 | + |
| 182 | + self._maybe_track_module(name, module) |
| 183 | + |
| 184 | + def reload_changes(self) -> List[str]: |
| 185 | + """ |
| 186 | + Reload all modules that have changed since they were last imported. |
| 187 | + """ |
| 188 | + |
| 189 | + reloaded = [] |
| 190 | + |
| 191 | + for module_name, (filename, stored_fingerprint) in list( |
| 192 | + self._tracked_modules.items() |
| 193 | + ): |
| 194 | + fingerprint = Fingerprint.for_path(filename) |
| 195 | + if fingerprint == stored_fingerprint: |
| 196 | + continue |
| 197 | + reloaded.append(module_name) |
| 198 | + self._reload(sys.modules[module_name]) |
| 199 | + self._tracked_modules[module_name] = (filename, fingerprint) |
| 200 | + |
| 201 | + return reloaded |
| 202 | + |
| 203 | + |
| 204 | +class AutoReloadActor(Actor): |
| 205 | + def __init__(self, workspace: WorkspaceLocation): |
| 206 | + self._reloader = AutoReloader(workspace.resolve()) |
| 207 | + self._hook_guard = SysAuditImportHook.install(self._reloader.import_callback) |
| 208 | + |
| 209 | + @endpoint |
| 210 | + async def reload(self) -> None: |
| 211 | + changed = self._reloader.reload_changes() |
| 212 | + print(f"reloaded modules: {changed}") |
0 commit comments