meerschaum.plugins
Expose plugin management APIs from the meerschaum.plugins module.
1#! /usr/bin/env python 2# -*- coding: utf-8 -*- 3# vim:fenc=utf-8 4 5""" 6Expose plugin management APIs from the `meerschaum.plugins` module. 7""" 8 9from __future__ import annotations 10 11import contextlib 12import pathlib 13import functools 14from collections import defaultdict 15 16import meerschaum as mrsm 17from meerschaum.utils.typing import Callable, Any, Union, Optional, Dict, List, Tuple 18from meerschaum.utils.threading import RLock 19from meerschaum.core.Plugin import Plugin 20from meerschaum.plugins._page import figure, figure_json 21 22_api_plugins: Dict[str, List[Callable[['fastapi.App'], Any]]] = {} 23_plugins_import_errors: Dict[str, Exception] = {} 24_pre_sync_hooks: Dict[Union[str, None], List[Callable[[Any], Any]]] = {} 25_post_sync_hooks: Dict[Union[str, None], List[Callable[[Any], Any]]] = {} 26_actions_daemon_enabled: Dict[str, bool] = {} 27### The words of each plugin action (`{'weather_wait': ['weather', 'wait']}`): 28### `@make_action(name=...)` sets them, an underscore name (`def weather_wait`) splits on `_`. 29### The plugin manifest carries them so the CLI lists `wait` under `mrsm weather` in help and 30### completion. 31_action_words: Dict[str, List[str]] = {} 32### Tags added to the head of every console page with `add_head()`, by plugin. 33_console_head: Dict[Union[str, None], List[str]] = {} 34_locks = { 35 '_api_plugins': RLock(), 36 '_dash_plugins': RLock(), 37 '_pre_sync_hooks': RLock(), 38 '_post_sync_hooks': RLock(), 39 '_actions_daemon_enabled': RLock(), 40 '_console_head': RLock(), 41 '__path__': RLock(), 42 'sys.path': RLock(), 43 'internal_plugins': RLock(), 44 '_synced_symlinks': RLock(), 45 'PLUGINS_INTERNAL_LOCK_PATH': RLock(), 46} 47__all__ = ( 48 "Plugin", 49 "make_action", 50 "api_plugin", 51 "dash_plugin", 52 "web_page", 53 "web_callback", 54 "add_head", 55 "import_plugins", 56 "from_plugin_import", 57 "invalidate_plugins_cache", 58 "reload_plugins", 59 "get_plugins", 60 "get_data_plugins", 61 "add_plugin_argument", 62 "pre_sync_hook", 63 "post_sync_hook", 64 "figure", 65 "figure_json", 66) 67__pdoc__ = { 68 'venvs': False, 69 'data': False, 70 'stack': False, 71 'plugins': False, 72} 73 74_FIRST_PARTY_PLUGIN_MODULES = { 75 'compose': 'meerschaum.compose', 76} 77 78 79def _import_first_party_plugin(plugin_import_name: str): 80 """Import a compatibility alias for a plugin which moved into Meerschaum core.""" 81 import importlib 82 83 plugin_import_parts = plugin_import_name.split('.') 84 module_root = _FIRST_PARTY_PLUGIN_MODULES.get(plugin_import_parts[0], None) 85 if module_root is None: 86 return None 87 return importlib.import_module('.'.join([module_root] + plugin_import_parts[1:])) 88 89 90def _get_plugins_package_name() -> str: 91 """ 92 Return the import name of the plugins package (`plugins`) 93 without resolving (and creating) the plugins resources directory. 94 """ 95 from meerschaum.config._paths import paths 96 path_parts = paths['PLUGINS_RESOURCES_PATH'] 97 last_part = path_parts[-1] if isinstance(path_parts, (list, tuple)) else path_parts 98 return pathlib.Path(last_part).stem 99 100 101### Set by the worker program (`crates/meerschaum-worker/python/host.py`). 102_IN_WORKER: bool = False 103 104 105@contextlib.contextmanager 106def plugin_import_guard(): 107 """ 108 Hold while plugin modules are imported. In a worker's interpreter no worker is started 109 meanwhile (`_core.plugin_import_begin()`): a plugin whose import syncs a `plugin:` pipe or 110 calls `mrsm.entry()` would otherwise start workers without end, each importing it again. 111 Anywhere else this does nothing. 112 """ 113 if not _IN_WORKER: 114 yield 115 return 116 from meerschaum import _core 117 _core.plugin_import_begin() 118 try: 119 yield 120 finally: 121 _core.plugin_import_end() 122 123 124def _get_loaded_module(module_name: str) -> Union['ModuleType', None]: 125 """ 126 Return a fully-initialized module from `sys.modules`, else `None`. 127 A module still being imported (e.g. by another thread) is not returned. 128 """ 129 import sys 130 module = sys.modules.get(module_name, None) 131 if module is None: 132 return None 133 if getattr(getattr(module, '__spec__', None), '_initializing', False): 134 return None 135 return module 136 137 138def _action_name_words(name: Any) -> List[str]: 139 """ 140 Return the words of an explicit action name (`'weather wait'` -> `['weather', 'wait']`), 141 or raise a `ValueError` for a name that cannot be typed as an action. 142 """ 143 if not isinstance(name, str) or not name.strip(): 144 raise ValueError(f"An action name must be a non-empty string, not {name!r}.") 145 words = name.split() 146 for word in words: 147 if word.startswith('-'): 148 raise ValueError( 149 f"Invalid action name {name!r}: the word '{word}' would be read as a flag." 150 ) 151 ### The action is registered as the words joined by `_`, which is how the dispatcher 152 ### finds and strips them: a `_` inside a word would split it there. 153 if '_' in word: 154 raise ValueError( 155 f"Invalid action name {name!r}: write '{word}' as separate words " 156 f"('{word.replace('_', ' ')}') or with a hyphen ('{word.replace('_', '-')}')." 157 ) 158 return words 159 160 161def _named_action(func: Callable[[Any], Any], action_key: str) -> Callable[[Any], Any]: 162 """ 163 Return `func` registered under `action_key` (its `__name__`), as an underscore action is: 164 the dispatcher strips the action's words from `action` by the function's name. 165 The signature and docstring are `func`'s (`functools.wraps`). 166 """ 167 @functools.wraps(func) 168 def _action(*args, **kwargs): 169 return func(*args, **kwargs) 170 171 _action.__name__ = action_key 172 _action.__qualname__ = action_key 173 return _action 174 175 176def make_action( 177 function: Union[Callable[[Any], Any], str, None] = None, 178 shell: bool = False, 179 activate: bool = True, 180 deactivate: bool = True, 181 debug: bool = False, 182 daemon: bool = True, 183 skip_if_loaded: bool = True, 184 name: Optional[str] = None, 185 _plugin_name: Optional[str] = None, 186) -> Callable[[Any], Any]: 187 """ 188 Make a function a Meerschaum action. Useful for plugins that are adding multiple actions. 189 190 Parameters 191 ---------- 192 function: Callable[[Any], Any] 193 The function to become a Meerschaum action. Must accept all keyword arguments. 194 195 shell: bool, default False 196 Not used. 197 198 daemon: bool, default True 199 If `False`, the action may not be detached with `-d`. 200 201 name: Optional[str], default None 202 The words that run the action, e.g. `'weather wait'` for `mrsm weather wait` (and 203 `mrsm weather wait other words`, which arrive as `action=['other', 'words']`). 204 Defaults to the function's name, where an underscore separates words: `def weather_wait` 205 also runs as `mrsm weather wait`. `@make_action('weather wait')` is the same as 206 `@make_action(name='weather wait')`. 207 208 Returns 209 ------- 210 Another function (this is a decorator function). 211 212 Examples 213 -------- 214 >>> from meerschaum.plugins import make_action 215 >>> 216 >>> @make_action 217 ... def my_action(**kw): 218 ... print('foo') 219 ... return True, "Success" 220 >>> 221 >>> @make_action(name='weather wait') 222 ... def wait_for_counts(action=None, **kw): 223 ... return True, f"Waited for {action}." 224 >>> 225 """ 226 if isinstance(function, str): 227 name, function = function, None 228 words = _action_name_words(name) if name is not None else None 229 230 def _decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: 231 from meerschaum.actions import actions, _custom_actions_plugins, _plugins_actions 232 action_key = '_'.join(words) if words else func.__name__ 233 plugin_name = _plugin_name or _get_parent_plugin(function=func) 234 235 if skip_if_loaded and action_key in actions: 236 existing = actions[action_key] 237 same_function = existing is func or getattr(existing, '__wrapped__', None) is func 238 if words and not same_function and _custom_actions_plugins.get(action_key) != plugin_name: 239 from meerschaum.utils.warnings import warn 240 warn( 241 f"The action '{' '.join(words)}' already exists; " 242 f"plugin '{plugin_name}' does not replace it.", 243 stack=False, 244 ) 245 return func 246 247 plugin = Plugin(plugin_name) if plugin_name else None 248 249 if debug: 250 from meerschaum.utils.debug import dprint 251 dprint( 252 f"Adding action '{action_key}' from plugin " 253 f"'{plugin}'..." 254 ) 255 256 registered = func if action_key == func.__name__ else _named_action(func, action_key) 257 actions[action_key] = registered 258 _custom_actions_plugins[action_key] = plugin_name 259 if plugin_name not in _plugins_actions: 260 _plugins_actions[plugin_name] = [] 261 _plugins_actions[plugin_name].append(action_key) 262 _action_words[action_key] = list(words) if words else [ 263 word for word in action_key.split('_') if word 264 ] or [action_key] 265 if not daemon: 266 _actions_daemon_enabled[action_key] = False 267 return func 268 269 if function is None: 270 return _decorator 271 return _decorator(function) 272 273 274def pre_sync_hook( 275 function: Callable[[Any], Any], 276) -> Callable[[Any], Any]: 277 """ 278 Register a function as a sync hook to be executed right before sync. 279 280 Parameters 281 ---------- 282 function: Callable[[Any], Any] 283 The function to execute right before a sync. 284 285 Returns 286 ------- 287 Another function (this is a decorator function). 288 289 Examples 290 -------- 291 >>> from meerschaum.plugins import pre_sync_hook 292 >>> 293 >>> @pre_sync_hook 294 ... def log_sync(pipe, **kwargs): 295 ... print(f"About to sync {pipe} with kwargs:\n{kwargs}.") 296 >>> 297 """ 298 with _locks['_pre_sync_hooks']: 299 plugin_name = _get_parent_plugin(function=function) 300 try: 301 if plugin_name not in _pre_sync_hooks: 302 _pre_sync_hooks[plugin_name] = [] 303 _pre_sync_hooks[plugin_name].append(function) 304 except Exception as e: 305 from meerschaum.utils.warnings import warn 306 warn(e) 307 return function 308 309 310def post_sync_hook( 311 function: Callable[[Any], Any], 312) -> Callable[[Any], Any]: 313 """ 314 Register a function as a sync hook to be executed upon completion of a sync. 315 316 Parameters 317 ---------- 318 function: Callable[[Any], Any] 319 The function to execute upon completion of a sync. 320 321 Returns 322 ------- 323 Another function (this is a decorator function). 324 325 Examples 326 -------- 327 >>> from meerschaum.plugins import post_sync_hook 328 >>> from meerschaum.utils.misc import interval_str 329 >>> from datetime import timedelta 330 >>> 331 >>> @post_sync_hook 332 ... def log_sync(pipe, success_tuple, duration=None, **kwargs): 333 ... duration_delta = timedelta(seconds=duration) 334 ... duration_text = interval_str(duration_delta) 335 ... print(f"It took {duration_text} to sync {pipe}.") 336 >>> 337 """ 338 with _locks['_post_sync_hooks']: 339 try: 340 plugin_name = _get_parent_plugin(function=function) 341 if plugin_name not in _post_sync_hooks: 342 _post_sync_hooks[plugin_name] = [] 343 _post_sync_hooks[plugin_name].append(function) 344 except Exception as e: 345 from meerschaum.utils.warnings import warn 346 warn(e) 347 return function 348 349 350### The Bootstrap themes the console ships: `@web_page(theme=...)` names them, or gives the URL of 351### another theme's stylesheet. 352_CONSOLE_THEMES: Dict[str, str] = { 353 'dark': 'dark', 354 'darkly': 'dark', 355 'light': 'light', 356 'flatly': 'light', 357} 358### What `@web_page(head=[...])` and `add_head(...)` may add as a dictionary or a Dash component. 359_HEAD_TAGS = ('meta', 'link', 'script', 'style', 'noscript') 360_VOID_HEAD_TAGS = ('meta', 'link') 361 362 363def _normalize_theme(theme: Optional[str]) -> Tuple[Optional[str], Optional[str]]: 364 """ 365 Return `(kind, url)` for a `@web_page(theme=...)` value: `('dark', None)`, `('light', None)`, 366 `('url', <stylesheet>)`, or `(None, None)` for the default (a warning names an unknown value). 367 """ 368 if theme is None: 369 return None, None 370 text = str(theme).strip() 371 if text.lower() in _CONSOLE_THEMES: 372 return _CONSOLE_THEMES[text.lower()], None 373 if text.startswith(('https://', 'http://', '//', '/')): 374 return 'url', text 375 from meerschaum.utils.warnings import warn 376 warn( 377 f"Unknown web page theme {theme!r}: use 'dark', 'light' or the URL of a Bootstrap " 378 "stylesheet (for example `dash_bootstrap_components.themes.LUX`). Using the default theme.", 379 stack=False, 380 ) 381 return None, None 382 383 384def _head_tag_html(tag: Any) -> Union[str, None]: 385 """ 386 Return the HTML of one head tag: a string is used as is (one or more tags), a dictionary is 387 `{'tag': 'meta', 'name': ..., 'content': ...}` (text of a `script` or `style` under 388 `children`), and a Dash component (`html.Link(...)`, `html.Meta(...)`, `html.Script(...)`) is 389 rendered from its properties. 390 """ 391 import html as html_lib 392 if tag is None: 393 return None 394 if isinstance(tag, str): 395 return tag.strip() or None 396 if not isinstance(tag, dict) and hasattr(tag, 'to_plotly_json'): 397 component = tag.to_plotly_json() 398 props = { 399 key: value 400 for key, value in (component.get('props', {}) or {}).items() 401 if value is not None 402 } 403 tag = {'tag': str(component.get('type', '')).lower(), **props} 404 if not isinstance(tag, dict): 405 raise TypeError( 406 f"A head tag must be an HTML string, a dictionary or a Dash component, not {tag!r}." 407 ) 408 attributes = dict(tag) 409 name = str(attributes.pop('tag', '') or '').lower() 410 if name not in _HEAD_TAGS: 411 raise ValueError( 412 f"Unsupported head tag {name!r}: use one of {', '.join(_HEAD_TAGS)}." 413 ) 414 text = None 415 for key in ('children', 'content_text', 'text'): 416 if key in attributes: 417 text = attributes.pop(key) 418 renamed = {'className': 'class', 'htmlFor': 'for', 'httpEquiv': 'http-equiv'} 419 parts = [name] 420 for key, value in attributes.items(): 421 key = renamed.get(key, key) 422 if value is None or value is False: 423 continue 424 if value is True: 425 parts.append(html_lib.escape(str(key), quote=True)) 426 continue 427 parts.append( 428 f'{html_lib.escape(str(key), quote=True)}="{html_lib.escape(str(value), quote=True)}"' 429 ) 430 opening = '<' + ' '.join(parts) + '>' 431 if name in _VOID_HEAD_TAGS: 432 return opening 433 body = '' if text is None else str(text) 434 if name in ('script', 'style'): 435 body = body.replace('</', '<\\/') 436 else: 437 body = html_lib.escape(body) 438 return f'{opening}{body}</{name}>' 439 440 441def _head_tags_html(tags: Any) -> List[str]: 442 """ 443 Return the HTML of each of `tags` (one tag or a list of them), see `_head_tag_html()`. 444 """ 445 if tags is None: 446 return [] 447 if isinstance(tags, (str, dict)) or hasattr(tags, 'to_plotly_json'): 448 tags = [tags] 449 out = [] 450 for tag in tags: 451 rendered = _head_tag_html(tag) 452 if rendered: 453 out.append(rendered) 454 return out 455 456 457def add_head(*tags: Any) -> None: 458 """ 459 Add tags to the `<head>` of every page of the web console (and of the documents of 460 page-contract pages): meta tags, stylesheets, scripts, fonts, a web app manifest... 461 462 Each tag is an HTML string, a dictionary (`{'tag': 'meta', 'name': 'theme-color', 463 'content': '#222'}`; the text of a `script` or `style` goes under `children`) or a Dash 464 component (`html.Link(rel='stylesheet', href='...')`). Call it at the top level of your plugin 465 (it applies when the console starts); `@web_page(head=[...])` adds tags to one page only. 466 467 Examples 468 -------- 469 >>> from meerschaum.plugins import add_head 470 >>> add_head( 471 ... '<meta name="theme-color" content="#222222">', 472 ... {'tag': 'link', 'rel': 'preconnect', 'href': 'https://fonts.gstatic.com'}, 473 ... ) 474 """ 475 rendered = _head_tags_html(list(tags)) 476 if not rendered: 477 return 478 plugin_name = _get_parent_plugin() 479 with _locks['_console_head']: 480 existing = _console_head.setdefault(plugin_name, []) 481 for tag in rendered: 482 if tag not in existing: 483 existing.append(tag) 484 485 486def get_console_head() -> List[str]: 487 """ 488 Return the HTML of every tag added with `add_head()`, in the order the plugins added them. 489 """ 490 with _locks['_console_head']: 491 return [tag for tags in _console_head.values() for tag in tags] 492 493 494_plugin_endpoints_to_pages = {} 495_plugins_web_pages = {} 496def web_page( 497 page: Union[str, None, Callable[[Any], Any]] = None, 498 login_required: bool = True, 499 skip_navbar: bool = False, 500 page_group: Optional[str] = None, 501 dark_theme: Optional[bool] = None, 502 theme: Optional[str] = None, 503 head: Optional[List[Any]] = None, 504 **kwargs 505) -> Any: 506 """ 507 Quickly add pages to the dash application. 508 509 Parameters 510 ---------- 511 page: Union[str, None, Callable[[Any], Any]], default None 512 The page's path in the console (`'foo/bar'` is served at `/dash/foo/bar`; sub-paths 513 such as `/dash/foo/bar/1` route to it too). Defaults to the function's name. 514 515 login_required: bool, default True 516 If `True`, visitors without a console session see the login page instead. 517 A public page (`login_required=False`) runs its callbacks for anonymous visitors only if 518 they are public too: register them with `@web_callback(..., public=True)` or inside a 519 `@dash_plugin(public=True)` function. 520 521 skip_navbar: bool, default False 522 If `True`, the console's navigation bar is not added above the page. 523 524 navbar: bool, default False 525 If `True`, the page gets the console's top navigation (its pages, the instance selector 526 and the user menu). By default a plugin's page keeps its own layout under a plain bar 527 (the logo, a link to the Overview, and Sign out). 528 529 page_group: Optional[str], default None 530 The group the page is listed under (defaults to the plugin's name). 531 532 dark_theme: Optional[bool], default None 533 Whether the `dbc_dark` component overrides apply to this page. By default they do for the 534 console's dark theme and do not for `theme='light'` or a custom stylesheet. 535 `dark_theme=False` without a `theme` gives the light theme, as before. 536 537 theme: Optional[str], default None 538 The Bootstrap theme of this page: `'dark'` (the console's theme, the default), `'light'`, 539 or the URL of a Bootstrap stylesheet (for example `dash_bootstrap_components.themes.LUX`, 540 or a file you serve with `meerschaum.api.mount_static`). Exactly one theme stylesheet 541 applies while the page is open, and the console's theme returns on other pages. 542 543 head: Optional[List[Any]], default None 544 Tags to add to the page's `<head>` while it is open: HTML strings, dictionaries 545 (`{'tag': 'link', 'rel': 'stylesheet', 'href': '...'}`) or Dash components 546 (`html.Script(src='...')`). Stylesheets and meta tags apply only while the page is open; 547 a script runs once, the first time the page opens. `add_head()` adds tags to every page. 548 549 Examples 550 -------- 551 >>> import meerschaum as mrsm 552 >>> from meerschaum.plugins import web_page 553 >>> html = mrsm.attempt_import('dash.html') 554 >>> 555 >>> @web_page('foo/bar', login_required=False) 556 >>> def foo_bar(): 557 ... return html.Div([html.H1("Hello, World!")]) 558 >>> 559 >>> @web_page('reports', theme='light', head=['<meta name="robots" content="noindex">']) 560 >>> def reports(): 561 ... return html.Div([html.H1("Reports")]) 562 >>> 563 """ 564 page_str = None 565 theme_kind, theme_url = _normalize_theme(theme) 566 if theme_kind in ('dark', 'light'): 567 if dark_theme is not None and dark_theme != (theme_kind == 'dark'): 568 from meerschaum.utils.warnings import warn 569 warn( 570 f"`@web_page(theme={theme!r}, dark_theme={dark_theme})`: " 571 f"the {theme_kind} theme applies.", 572 stack=False, 573 ) 574 resolved_dark = theme_kind == 'dark' 575 elif theme_kind == 'url': 576 resolved_dark = bool(dark_theme) if dark_theme is not None else False 577 else: 578 resolved_dark = True if dark_theme is None else bool(dark_theme) 579 resolved_theme = theme_url if theme_kind == 'url' else ('dark' if resolved_dark else 'light') 580 head_tags = _head_tags_html(head) 581 582 def _decorator(_func: Callable[[Any], Any]) -> Callable[[Any], Any]: 583 nonlocal page_str, page_group 584 585 @functools.wraps(_func) 586 def wrapper(*_args, **_kwargs): 587 return _func(*_args, **_kwargs) 588 589 if page_str is None: 590 page_str = _func.__name__ 591 592 page_str = page_str.lstrip('/').rstrip('/').strip() 593 if not page_str.startswith('dash'): 594 page_str = f'/dash/{page_str}' 595 page_key = ( 596 ' '.join( 597 [ 598 word.capitalize() 599 for word in ( 600 page_str.replace('/dash', '').lstrip('/').rstrip('/').strip() 601 .replace('-', ' ').replace('_', ' ').split(' ') 602 ) 603 ] 604 ) 605 ) 606 607 plugin_name = _get_parent_plugin(function=_func) 608 page_group = page_group or plugin_name 609 if page_group not in _plugin_endpoints_to_pages: 610 _plugin_endpoints_to_pages[page_group] = {} 611 _plugin_endpoints_to_pages[page_group][page_str] = { 612 'function': _func, 613 'login_required': login_required, 614 'skip_navbar': skip_navbar, 615 ### The console's top navigation instead of the plain bar (`build_plugin_navbar`). 616 'navbar': bool(kwargs.get('navbar', False)), 617 'page_key': page_key, 618 'dark_theme': resolved_dark, 619 'theme': resolved_theme, 620 'head': list(head_tags), 621 } 622 if plugin_name not in _plugins_web_pages: 623 _plugins_web_pages[plugin_name] = [] 624 _plugins_web_pages[plugin_name].append(_func) 625 return wrapper 626 627 if callable(page): 628 decorator_to_return = _decorator(page) 629 page_str = page.__name__ 630 else: 631 decorator_to_return = _decorator 632 page_str = page 633 634 return decorator_to_return 635 636 637### Dash callbacks are public (served without a console session) when their function carries this 638### attribute: `@web_callback(..., public=True)`, the callbacks a `@dash_plugin(public=True)` function 639### registers, and the console's login and registration callbacks. The API host's guard 640### (`meerschaum.api.host._callbacks`) follows `__wrapped__` from the function Dash calls. 641_PUBLIC_CALLBACK_ATTR: str = '_mrsm_public_callback' 642 643 644def _mark_public_callback(func: Callable[[Any], Any]) -> Callable[[Any], Any]: 645 """ 646 Mark a Dash callback function as public and return it. 647 """ 648 for target in (func, getattr(func, '__func__', None)): 649 if target is None: 650 continue 651 try: 652 setattr(target, _PUBLIC_CALLBACK_ATTR, True) 653 return func 654 except (AttributeError, TypeError): 655 continue 656 from meerschaum.utils.warnings import warn 657 warn(f"Could not mark the callback {func!r} as public.", stack=False) 658 return func 659 660 661def _is_public_callback(func: Any) -> bool: 662 """ 663 Return whether the function Dash calls for a callback (or one it wraps) is marked public. 664 """ 665 for _ in range(32): 666 if func is None: 667 return False 668 if getattr(func, _PUBLIC_CALLBACK_ATTR, False) is True: 669 return True 670 func = getattr(func, '__wrapped__', None) or getattr(func, '__func__', None) 671 return False 672 673 674def _built_dash_app() -> Any: 675 """ 676 Return the console's Dash app if this process built it (never builds it). 677 """ 678 import sys 679 module = sys.modules.get('meerschaum.api.dash', None) 680 if module is None: 681 return None 682 return module.__dict__.get('dash_app', None) 683 684 685def _callback_registrations(dash_app: Any) -> Dict[str, Any]: 686 """ 687 Snapshot the places a Dash callback can be registered in: the app's callback map, the 688 `dash_extensions` blueprint of a `DashProxy` app, and the global `dash.callback` and 689 `dash_extensions.enrich.callback` registries. 690 """ 691 import sys 692 dash_callback = sys.modules.get('dash._callback', None) 693 enrich = sys.modules.get('dash_extensions.enrich', None) 694 blueprint = getattr(dash_app, 'blueprint', None) 695 global_blueprint = getattr(enrich, 'GLOBAL_BLUEPRINT', None) 696 return { 697 'map': dict(getattr(dash_app, 'callback_map', None) or {}), 698 'global_map': dict(getattr(dash_callback, 'GLOBAL_CALLBACK_MAP', None) or {}), 699 'blueprint': list(getattr(blueprint, 'callbacks', None) or []), 700 'global_blueprint': list(getattr(global_blueprint, 'callbacks', None) or []), 701 } 702 703 704@contextlib.contextmanager 705def _registering_public_callbacks(dash_app: Any): 706 """ 707 Mark every Dash callback registered inside this block public (whichever way it was 708 registered: `dash_app.callback`, `dash.callback` or `dash_extensions.enrich.callback`). 709 """ 710 before = _callback_registrations(dash_app) 711 try: 712 yield 713 finally: 714 for func in _new_callback_functions(before, _callback_registrations(dash_app)): 715 _mark_public_callback(func) 716 717 718def _new_callback_functions(before: Dict[str, Any], after: Dict[str, Any]) -> List[Any]: 719 """ 720 Return the callback functions registered between two `_callback_registrations()` snapshots. 721 """ 722 functions = [] 723 for key in ('blueprint', 'global_blueprint'): 724 known = {id(item) for item in before[key]} 725 functions.extend( 726 getattr(item, 'f', None) for item in after[key] if id(item) not in known 727 ) 728 for key in ('map', 'global_map'): 729 functions.extend( 730 (spec or {}).get('callback', None) 731 for callback_id, spec in after[key].items() 732 if callback_id not in before[key] 733 ) 734 return [func for func in functions if callable(func)] 735 736 737_dash_plugins = {} 738def dash_plugin( 739 function: Optional[Callable[[Any], Any]] = None, 740 *, 741 public: bool = False, 742) -> Callable[[Any], Any]: 743 """ 744 Execute the function when starting the Dash application (the web console), with the console's 745 `dash_app` as its argument: register your callbacks in it with `@dash_app.callback(...)`. 746 747 Parameters 748 ---------- 749 public: bool, default False 750 Every callback the function registers runs without a console session. By default a 751 callback answers only signed-in visitors (`api:dash:callbacks_require_session`); make 752 callbacks public only for pages anyone may use (`@web_page(login_required=False)`), and 753 use `@web_callback(..., public=True)` to choose callbacks one at a time. 754 755 Examples 756 -------- 757 >>> from meerschaum.plugins import dash_plugin 758 >>> 759 >>> @dash_plugin(public=True) 760 ... def init_dash(dash_app): 761 ... from dash import Input, Output 762 ... @dash_app.callback(Output('greeting', 'children'), Input('name', 'value')) 763 ... def greet(name): 764 ... return f"Hello, {name}!" 765 """ 766 def _decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: 767 registered = func 768 if public: 769 @functools.wraps(func) 770 def _public_dash_plugin(dash_app, *args, **kwargs): 771 with _registering_public_callbacks(dash_app): 772 return func(dash_app, *args, **kwargs) 773 registered = _public_dash_plugin 774 775 with _locks['_dash_plugins']: 776 plugin_name = _get_parent_plugin(function=func) 777 try: 778 if plugin_name not in _dash_plugins: 779 _dash_plugins[plugin_name] = [] 780 _dash_plugins[plugin_name].append(registered) 781 except Exception as e: 782 from meerschaum.utils.warnings import warn 783 warn(e) 784 return func 785 786 if function is not None: 787 if not callable(function): 788 raise TypeError("`@dash_plugin` decorates a function.") 789 return _decorator(function) 790 return _decorator 791 792 793def _dash_dependencies(kind: str, specs: Any) -> List[Any]: 794 """ 795 Return Dash dependencies for `web_callback(output=..., inputs=..., state=...)`: each spec is an 796 `'id.property'` string, an `(id, property)` tuple or a Dash dependency (kept as is). 797 """ 798 from dash.dependencies import Input, Output, State 799 dependency_class = {'output': Output, 'inputs': Input, 'state': State}[kind] 800 if isinstance(specs, (str, tuple)): 801 specs = [specs] 802 out = [] 803 for spec in specs: 804 if isinstance(spec, str): 805 component_id, dot, prop = spec.strip().rpartition('.') 806 if not dot or not component_id or not prop: 807 raise ValueError( 808 f"`@web_callback({kind}=...)` takes 'component-id.property' strings, not {spec!r}." 809 ) 810 out.append(dependency_class(component_id, prop)) 811 elif isinstance(spec, tuple) and len(spec) == 2: 812 out.append(dependency_class(*spec)) 813 else: 814 out.append(spec) 815 return out 816 817 818def web_callback( 819 *args: Any, 820 public: bool = False, 821 output: Any = None, 822 inputs: Any = None, 823 state: Any = None, 824 **kwargs: Any 825) -> Callable[[Any], Any]: 826 """ 827 Register a Dash callback on the web console: `@web_callback(...)` takes what 828 `@dash_app.callback(...)` takes (outputs, inputs, states, `prevent_initial_call`, ...), 829 at the top level of your plugin, without a `@dash_plugin` function. 830 831 Parameters 832 ---------- 833 public: bool, default False 834 If `True`, the callback runs for visitors without a console session (for a page with 835 `@web_page(login_required=False)`). Otherwise the console answers it only for signed-in 836 visitors and sends the others to the login page. 837 838 output: Union[str, List[str], None], default None 839 The outputs as `'component-id.property'` strings (instead of `Output(...)` arguments), so 840 your plugin need not import Dash: it is imported when the console starts. 841 842 inputs: Union[str, List[str], None], default None 843 The inputs, likewise (`'my-button.n_clicks'`). 844 845 state: Union[str, List[str], None], default None 846 The states, likewise (`'session-store.data'`). 847 848 Examples 849 -------- 850 >>> from meerschaum.plugins import web_page, web_callback 851 >>> 852 >>> @web_callback(output='visits.children', inputs='visit-button.n_clicks', public=True) 853 ... def count_visits(n_clicks): 854 ... return f"{n_clicks or 0} visits" 855 >>> 856 >>> from dash import Input, Output 857 >>> @web_callback(Output('clock', 'children'), Input('tick', 'n_intervals')) 858 ... def clock(n_intervals): 859 ... return str(n_intervals) 860 """ 861 if ( 862 len(args) == 1 and not kwargs and output is None and inputs is None and state is None 863 and callable(args[0]) and not hasattr(args[0], 'component_id') 864 ): 865 raise TypeError( 866 "`@web_callback` takes the callback's outputs and inputs, e.g. " 867 "`@web_callback(output='out.children', inputs='button.n_clicks')`." 868 ) 869 870 def _arguments() -> Tuple[List[Any], Dict[str, Any]]: 871 """The positional and keyword arguments for `dash_app.callback` (Dash imported now).""" 872 dependencies = list(args) 873 flexible = dict(kwargs) 874 for kind, specs in (('output', output), ('inputs', inputs), ('state', state)): 875 if specs is None: 876 continue 877 if isinstance(specs, dict): 878 flexible[kind] = specs 879 continue 880 dependencies.extend(_dash_dependencies(kind, specs)) 881 return dependencies, flexible 882 883 def _decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: 884 if public: 885 _mark_public_callback(func) 886 dash_app = _built_dash_app() 887 if dash_app is not None: 888 dependencies, flexible = _arguments() 889 dash_app.callback(*dependencies, **flexible)(func) 890 return func 891 892 ### The console is built later (by the API host): register the callback then, as the 893 ### `@dash_plugin` functions are. 894 def _register(app): 895 dependencies, flexible = _arguments() 896 app.callback(*dependencies, **flexible)(func) 897 898 for attr in ('__module__', '__name__', '__qualname__', '__doc__'): 899 try: 900 setattr(_register, attr, getattr(func, attr)) 901 except (AttributeError, TypeError): 902 pass 903 with _locks['_dash_plugins']: 904 plugin_name = _get_parent_plugin(function=func) 905 if plugin_name not in _dash_plugins: 906 _dash_plugins[plugin_name] = [] 907 _dash_plugins[plugin_name].append(_register) 908 return func 909 910 return _decorator 911 912 913def api_plugin(function: Callable[[Any], Any]) -> Callable[[Any], Any]: 914 """ 915 Execute the function when initializing the Meerschaum API module. 916 Useful for lazy-loading heavy plugins only when the API is started, 917 such as when editing the `meerschaum.api.app` FastAPI app. 918 919 The FastAPI app will be passed as the only parameter. 920 921 Examples 922 -------- 923 >>> from meerschaum.plugins import api_plugin 924 >>> 925 >>> @api_plugin 926 >>> def initialize_plugin(app): 927 ... @app.get('/my/new/path') 928 ... def new_path(): 929 ... return {'message': 'It works!'} 930 >>> 931 """ 932 with _locks['_api_plugins']: 933 try: 934 plugin_name = _get_parent_plugin(function=function) 935 if plugin_name not in _api_plugins: 936 _api_plugins[plugin_name] = [] 937 _api_plugins[plugin_name].append(function) 938 except Exception as e: 939 from meerschaum.utils.warnings import warn 940 warn(e) 941 return function 942 943 944_synced_symlinks: int = 0 945_injected_plugin_symlinks = defaultdict(lambda: 0) 946def sync_plugins_symlinks(debug: bool = False, warn: bool = True) -> None: 947 """ 948 Update the plugins' internal symlinks. 949 """ 950 from meerschaum.utils.warnings import error, warn as _warn, dprint 951 global _synced_symlinks 952 with _locks['_synced_symlinks']: 953 if _synced_symlinks > 1: 954 if debug: 955 dprint("Skip syncing symlinks...") 956 return 957 958 import os 959 import pathlib 960 from collections import defaultdict 961 from meerschaum.utils.misc import flatten_list, make_symlink, is_symlink 962 import meerschaum.config.paths as paths 963 from meerschaum.utils.locks import InterProcessLock 964 965 ### 5.1: an isolated team's sandboxed process may only read the plugins' symlinks (the server 966 ### and every other process keep them); it never rewrites the directory other teams share. 967 import meerschaum.config._paths as native_paths 968 if os.environ.get('MRSM_TEAM_SANDBOX') or native_paths._TEAM_SOURCE_NAMESPACE is not None: 969 with _locks['__path__']: 970 if str(paths.PLUGINS_RESOURCES_PATH.parent) not in __path__: 971 __path__.append(str(paths.PLUGINS_RESOURCES_PATH.parent)) 972 with _locks['_synced_symlinks']: 973 _synced_symlinks += 1 974 return 975 976 with InterProcessLock(paths.PLUGINS_INTERNAL_LOCK_PATH), _locks['internal_plugins']: 977 978 try: 979 from importlib.metadata import entry_points 980 except ImportError: 981 importlib_metadata = mrsm.attempt_import('importlib_metadata', lazy=False) 982 entry_points = importlib_metadata.entry_points 983 984 ### NOTE: Allow plugins to be installed via `pip`. 985 packaged_plugin_paths = [] 986 try: 987 discovered_packaged_plugins_eps = entry_points(group='meerschaum.plugins') 988 except TypeError: 989 discovered_packaged_plugins_eps = [] 990 991 for ep in discovered_packaged_plugins_eps: 992 module_name = ep.name 993 for package_file_path in ep.dist.files: 994 if package_file_path.suffix != '.py': 995 continue 996 if str(package_file_path) == f'{module_name}.py': 997 packaged_plugin_paths.append(package_file_path.locate()) 998 elif str(package_file_path) == f'{module_name}/__init__.py': 999 packaged_plugin_paths.append(package_file_path.locate().parent) 1000 1001 if is_symlink(paths.PLUGINS_RESOURCES_PATH) or not paths.PLUGINS_RESOURCES_PATH.exists(): 1002 try: 1003 paths.PLUGINS_RESOURCES_PATH.unlink() 1004 except Exception: 1005 pass 1006 1007 paths.PLUGINS_RESOURCES_PATH.mkdir(exist_ok=True) 1008 1009 existing_symlinked_paths = { 1010 _existing_symlink: pathlib.Path(os.path.realpath(_existing_symlink)) 1011 for item in os.listdir(paths.PLUGINS_RESOURCES_PATH) 1012 if is_symlink(_existing_symlink := (paths.PLUGINS_RESOURCES_PATH / item)) 1013 } 1014 injected_symlinked_paths = { 1015 _injected_symlink: pathlib.Path(os.path.realpath(_injected_symlink)) 1016 for item in os.listdir(paths.PLUGINS_INJECTED_RESOURCES_PATH) 1017 if is_symlink(_injected_symlink := (paths.PLUGINS_INJECTED_RESOURCES_PATH / item)) 1018 } 1019 plugins_to_be_symlinked = list(flatten_list( 1020 [ 1021 [ 1022 pathlib.Path(os.path.realpath(plugins_path / item)) 1023 for item in os.listdir(plugins_path) 1024 if ( 1025 not item.startswith('.') 1026 ) and (item not in ('__pycache__', '__init__.py')) 1027 ] 1028 for plugins_path in paths.PLUGINS_DIR_PATHS 1029 if plugins_path.exists() 1030 ] 1031 )) 1032 plugins_to_be_symlinked.extend(packaged_plugin_paths) 1033 1034 ### Check for duplicates. 1035 seen_plugins = defaultdict(lambda: 0) 1036 for plugin_path in plugins_to_be_symlinked: 1037 plugin_name = plugin_path.stem 1038 seen_plugins[plugin_name] += 1 1039 for plugin_name, plugin_count in seen_plugins.items(): 1040 if plugin_count > 1: 1041 if warn: 1042 _warn(f"Found duplicate plugins named '{plugin_name}'.") 1043 1044 for plugin_symlink_path, real_path in existing_symlinked_paths.items(): 1045 1046 ### Remove invalid symlinks. 1047 if real_path not in plugins_to_be_symlinked: 1048 if _injected_plugin_symlinks[plugin_symlink_path] > 1: 1049 continue 1050 if plugin_symlink_path in injected_symlinked_paths: 1051 continue 1052 if real_path in injected_symlinked_paths.values(): 1053 continue 1054 ### Only reap a symlink whose target NO LONGER EXISTS (a genuinely stale 1055 ### plugin). A symlink whose target still exists is a valid plugin from 1056 ### another configured plugins directory and must not be removed here: 1057 ### `PLUGINS_DIR_PATHS` is process-global and can transiently fall back to 1058 ### the host default when `MRSM_PLUGINS_DIR` is momentarily absent from the 1059 ### environment (e.g. a daemon thread or a `replace_env` context). Removing 1060 ### valid cross-dir symlinks in that window deletes a project's plugin 1061 ### links from the shared per-root `.internal/plugins`, so a 1062 ### `plugin:<name>`-backed background job then fails to import its plugin. 1063 try: 1064 if real_path.exists(): 1065 continue 1066 except Exception: 1067 pass 1068 try: 1069 plugin_symlink_path.unlink() 1070 except Exception: 1071 pass 1072 1073 ### Remove valid plugins from the to-be-symlinked list. 1074 else: 1075 plugins_to_be_symlinked.remove(real_path) 1076 1077 for plugin_path in plugins_to_be_symlinked: 1078 plugin_symlink_path = paths.PLUGINS_RESOURCES_PATH / plugin_path.name 1079 try: 1080 ### There might be duplicate folders (e.g. __pycache__). 1081 if ( 1082 plugin_symlink_path.exists() 1083 and 1084 plugin_symlink_path.is_dir() 1085 and 1086 not is_symlink(plugin_symlink_path) 1087 ): 1088 continue 1089 success, msg = make_symlink(plugin_path, plugin_symlink_path) 1090 except Exception as e: 1091 success, msg = False, str(e) 1092 if not success: 1093 if warn: 1094 _warn( 1095 f"Failed to create symlink {plugin_symlink_path} " 1096 + f"to {plugin_path}:\n {msg}" 1097 ) 1098 1099 with _locks['PLUGINS_INTERNAL_LOCK_PATH']: 1100 try: 1101 if not paths.PLUGINS_INIT_PATH.exists(): 1102 paths.PLUGINS_INIT_PATH.touch() 1103 except Exception as e: 1104 error(f"Failed to create the file '{paths.PLUGINS_INIT_PATH}':\n{e}") 1105 1106 with _locks['__path__']: 1107 if str(paths.PLUGINS_RESOURCES_PATH.parent) not in __path__: 1108 __path__.append(str(paths.PLUGINS_RESOURCES_PATH.parent)) 1109 1110 with _locks['_synced_symlinks']: 1111 _synced_symlinks += 1 1112 1113 1114def import_plugins( 1115 *plugins_to_import: Union[str, List[str], None], 1116 warn: bool = True, 1117) -> Union[ 1118 'ModuleType', Tuple['ModuleType', None] 1119]: 1120 """ 1121 Import the Meerschaum plugins directory. 1122 1123 Parameters 1124 ---------- 1125 plugins_to_import: Union[str, List[str], None] 1126 If provided, only import the specified plugins. 1127 Otherwise import the entire plugins module. May be a string, list, or `None`. 1128 Defaults to `None`. 1129 1130 warn: bool, default True 1131 Print import errors. A named plugin's error is also available on `Plugin.import_error`. 1132 1133 Returns 1134 ------- 1135 A module of list of modules, depening on the number of plugins provided. 1136 1137 """ 1138 import sys 1139 import importlib 1140 import meerschaum.config._paths as native_paths 1141 import meerschaum.config.paths as paths 1142 from meerschaum.utils.misc import flatten_list 1143 from meerschaum.utils.venv import ( 1144 is_venv_active, activate_venv, deactivate_venv, Venv, ensure_default_venvs, 1145 ) 1146 from meerschaum.utils.warnings import warn as _warn 1147 plugins_to_import = list(plugins_to_import) 1148 ### PARITY: v4 had already activated the shared 'mrsm' venv (`attempt_import`) before the first 1149 ### plugin was imported, so plugin code with its own `required` venv still saw it. 1150 ensure_default_venvs() 1151 prepended_sys_path = False 1152 with _locks['sys.path']: 1153 1154 ### Since plugins may depend on other plugins, 1155 ### we need to activate the virtual environments for library plugins. 1156 ### This logic exists in `Plugin.activate_venv()`, 1157 ### but that code requires the plugin's module to already be imported. 1158 ### It's not a guarantee of correct activation order, 1159 ### e.g. if a library plugin pins a specific package and another 1160 plugins_names = get_plugins_names() 1161 already_active_venvs = { 1162 plugin_name 1163 for plugin_name in plugins_names 1164 if is_venv_active(plugin_name) 1165 } 1166 1167 if not sys.path or sys.path[0] != str(paths.PLUGINS_RESOURCES_PATH.parent): 1168 prepended_sys_path = True 1169 sys.path.insert(0, str(paths.PLUGINS_RESOURCES_PATH.parent)) 1170 1171 if not plugins_to_import: 1172 # The launcher creates an empty package for these sources. Its individual 1173 # plugins activate their own dependencies when they are imported. 1174 package_venvs = plugins_names if native_paths._TEAM_SOURCE_NAMESPACE is None else () 1175 for plugin_name in package_venvs: 1176 activate_venv(plugin_name) 1177 try: 1178 with plugin_import_guard(): 1179 imported_plugins = importlib.import_module(paths.PLUGINS_RESOURCES_PATH.stem) 1180 except ImportError as e: 1181 if warn: 1182 _warn(f"Failed to import the plugins module:\n {e}") 1183 import traceback 1184 traceback.print_exc() 1185 imported_plugins = None 1186 for plugin_name in package_venvs: 1187 if plugin_name in already_active_venvs: 1188 continue 1189 deactivate_venv(plugin_name) 1190 1191 else: 1192 imported_plugins = [] 1193 for plugin_name in flatten_list(plugins_to_import): 1194 plugin = Plugin(plugin_name) 1195 try: 1196 with Venv(plugin, init_if_not_exists=False), plugin_import_guard(): 1197 imported_plugins.append( 1198 importlib.import_module( 1199 f'{paths.PLUGINS_RESOURCES_PATH.stem}.{plugin_name}' 1200 ) 1201 ) 1202 _ = _plugins_import_errors.pop(plugin_name, None) 1203 except Exception as e: 1204 _plugins_import_errors[plugin_name] = e 1205 imported_plugins.append(None) 1206 if not warn: 1207 continue 1208 native_team_source = native_paths._TEAM_SOURCE_NAMESPACE is not None 1209 _warn( 1210 f"Failed to import plugin '{plugin_name}':\n " 1211 + f"{e}\n\nHere's a stacktrace:", 1212 stack = False, 1213 color = not native_team_source, 1214 ) 1215 if native_team_source: 1216 # Reporting a failed import does not need any additional packages. 1217 import traceback 1218 traceback.print_exc() 1219 else: 1220 from meerschaum.utils.formatting import print_exception 1221 print_exception( 1222 suppress = [ 1223 'meerschaum/plugins/__init__.py', 1224 importlib, 1225 importlib._bootstrap, 1226 ] 1227 ) 1228 1229 if imported_plugins is None and warn: 1230 _warn("Failed to import plugins.", stacklevel=3) 1231 1232 if prepended_sys_path and str(paths.PLUGINS_RESOURCES_PATH.parent) in sys.path: 1233 sys.path.remove(str(paths.PLUGINS_RESOURCES_PATH.parent)) 1234 1235 if isinstance(imported_plugins, list): 1236 return (imported_plugins[0] if len(imported_plugins) == 1 else tuple(imported_plugins)) 1237 return imported_plugins 1238 1239 1240def from_plugin_import(plugin_import_name: str, *attrs: str) -> Any: 1241 """ 1242 Emulate the `from module import x` behavior. 1243 1244 Parameters 1245 ---------- 1246 plugin_import_name: str 1247 The import name of the plugin's module. 1248 Separate submodules with '.' (e.g. 'compose.utils.pipes') 1249 1250 attrs: str 1251 Names of the attributes to return. 1252 1253 Returns 1254 ------- 1255 Objects from a plugin's submodule. 1256 If multiple objects are provided, return a tuple. 1257 1258 Examples 1259 -------- 1260 >>> init = from_plugin_import('compose.utils', 'init') 1261 >>> with mrsm.Venv('compose'): 1262 ... cf = init() 1263 >>> build_parent_pipe, get_defined_pipes = from_plugin_import( 1264 ... 'compose.utils.pipes', 1265 ... 'build_parent_pipe', 1266 ... 'get_defined_pipes', 1267 ... ) 1268 >>> parent_pipe = build_parent_pipe(cf) 1269 >>> defined_pipes = get_defined_pipes(cf) 1270 """ 1271 import importlib 1272 from meerschaum.utils.warnings import warn as _warn 1273 if plugin_import_name.startswith('plugins.'): 1274 plugin_import_name = plugin_import_name[len('plugins.'):] 1275 plugin_import_parts = plugin_import_name.split('.') 1276 plugin_root_name = plugin_import_parts[0] 1277 1278 plugins_package_name = _get_plugins_package_name() 1279 submodule_import_name = '.'.join([plugins_package_name] + plugin_import_parts) 1280 if len(attrs) == 0: 1281 raise ValueError(f"Provide which attributes to return from '{submodule_import_name}'.") 1282 1283 def _get_attrs(module) -> Any: 1284 attrs_to_return = [] 1285 for attr in attrs: 1286 try: 1287 attrs_to_return.append(getattr(module, attr)) 1288 except Exception: 1289 _warn(f"Failed to access '{attr}' from '{submodule_import_name}'.") 1290 attrs_to_return.append(None) 1291 return attrs_to_return[0] if len(attrs_to_return) == 1 else tuple(attrs_to_return) 1292 1293 first_party_submodule = _import_first_party_plugin(plugin_import_name) 1294 if first_party_submodule is not None: 1295 attrs_to_return = [getattr(first_party_submodule, attr) for attr in attrs] 1296 return attrs_to_return[0] if len(attrs_to_return) == 1 else tuple(attrs_to_return) 1297 1298 ### Skip building the plugin and activating its venv when the submodule is already imported. 1299 loaded_submodule = _get_loaded_module(submodule_import_name) 1300 if ( 1301 loaded_submodule is not None 1302 and _get_loaded_module(f'{plugins_package_name}.{plugin_root_name}') is not None 1303 ): 1304 return _get_attrs(loaded_submodule) 1305 1306 plugin = mrsm.Plugin(plugin_root_name) 1307 with mrsm.Venv(plugin): 1308 if plugin.module is None: 1309 raise ImportError(f"Unable to import plugin '{plugin}'.") 1310 1311 try: 1312 with plugin_import_guard(): 1313 submodule = importlib.import_module(submodule_import_name) 1314 except ImportError as e: 1315 _warn( 1316 f"Failed to import plugin '{submodule_import_name}':\n " 1317 + f"{e}\n\nHere's a stacktrace:", 1318 stack=False, 1319 ) 1320 from meerschaum.utils.formatting import print_exception 1321 print_exception( 1322 suppress=[ 1323 'meerschaum/plugins/__init__.py', 1324 importlib, 1325 importlib._bootstrap, 1326 ] 1327 ) 1328 ### Return one `None` per attribute so tuple unpacking still works. 1329 return None if len(attrs) == 1 else (None,) * len(attrs) 1330 1331 return _get_attrs(submodule) 1332 1333 1334_loaded_plugins: bool = False 1335def load_plugins( 1336 skip_if_loaded: bool = True, 1337 shell: bool = False, 1338 debug: bool = False, 1339) -> None: 1340 """ 1341 Import Meerschaum plugins and update the actions dictionary. 1342 """ 1343 global _loaded_plugins 1344 from meerschaum.utils.warnings import dprint 1345 1346 if skip_if_loaded and _loaded_plugins: 1347 if debug: 1348 dprint("Skip loading plugins...") 1349 return 1350 1351 from inspect import isfunction, getmembers 1352 from meerschaum.config._paths import _TEAM_SOURCE_NAMESPACE 1353 import meerschaum.config.paths as paths 1354 from meerschaum.actions import __all__ as _all, modules 1355 from meerschaum.utils.packages import get_modules_from_package 1356 1357 with plugin_import_guard(): 1358 if _TEAM_SOURCE_NAMESPACE is not None: 1359 # Load each granted source with the same environment checks as a named import. 1360 plugins_modules = [ 1361 module for name in _TEAM_SOURCE_NAMESPACE['names'] 1362 if (module := import_plugins(name)) is not None 1363 ] 1364 else: 1365 _plugins_names, plugins_modules = get_modules_from_package( 1366 import_plugins(), 1367 names = True, 1368 recursive = True, 1369 modules_venvs = True 1370 ) 1371 1372 ### I'm appending here to keep from redefining the modules list. 1373 new_modules = ( 1374 [ 1375 mod 1376 for mod in modules 1377 if not mod.__name__.startswith(paths.PLUGINS_RESOURCES_PATH.stem + '.') 1378 ] 1379 + plugins_modules 1380 ) 1381 n_mods = len(modules) 1382 for mod in new_modules: 1383 modules.append(mod) 1384 for i in range(n_mods): 1385 modules.pop(0) 1386 1387 for module in plugins_modules: 1388 for name, func in list(vars(module).items()): 1389 if not isfunction(func): 1390 continue 1391 if name == module.__name__.split('.')[-1]: 1392 make_action( 1393 func, 1394 **{'shell': shell, 'debug': debug}, 1395 _plugin_name=_get_parent_plugin(function=func), 1396 skip_if_loaded=True, 1397 ) 1398 1399 _loaded_plugins = True 1400 1401 1402def unload_custom_actions(plugins: Optional[List[str]] = None, debug: bool = False) -> None: 1403 """ 1404 Unload the custom actions added by plugins. 1405 """ 1406 from meerschaum.actions import ( 1407 actions, 1408 _custom_actions_plugins, 1409 _plugins_actions, 1410 ) 1411 1412 plugins = plugins if plugins is not None else list(_plugins_actions) 1413 1414 for plugin in plugins: 1415 action_names = _plugins_actions.get(plugin, []) 1416 for action_name in action_names: 1417 _ = actions.pop(action_name, None) 1418 _ = _custom_actions_plugins.pop(action_name, None) 1419 _ = _actions_daemon_enabled.pop(action_name, None) 1420 _ = _action_words.pop(action_name, None) 1421 1422 _ = _plugins_actions.pop(plugin, None) 1423 1424 1425def unload_plugins( 1426 plugins: Optional[List[str]] = None, 1427 remove_symlinks: bool = True, 1428 debug: bool = False, 1429) -> None: 1430 """ 1431 Unload the specified plugins from memory. 1432 """ 1433 global _loaded_plugins, _synced_symlinks 1434 import os 1435 import sys 1436 import pathlib 1437 import meerschaum.config.paths as paths 1438 from meerschaum.connectors import unload_plugin_connectors 1439 if debug: 1440 from meerschaum.utils.warnings import dprint 1441 1442 _loaded_plugins = False 1443 _synced_symlinks = 0 1444 1445 all_plugins = get_plugins_names() 1446 plugins = plugins if plugins is not None else all_plugins 1447 if debug: 1448 dprint(f"Unloading plugins: {plugins}") 1449 1450 unload_custom_actions(plugins, debug=debug) 1451 unload_plugin_connectors(plugins, debug=debug) 1452 1453 module_prefix = f"{paths.PLUGINS_RESOURCES_PATH.stem}." 1454 loaded_modules = [mod_name for mod_name in sys.modules if mod_name.startswith(module_prefix)] 1455 1456 root_plugins_mod = ( 1457 sys.modules.get(paths.PLUGINS_RESOURCES_PATH.stem, None) 1458 if sorted(plugins) != sorted(all_plugins) 1459 else sys.modules.pop(paths.PLUGINS_RESOURCES_PATH.stem, None) 1460 ) 1461 1462 for plugin_name in plugins: 1463 for mod_name in loaded_modules: 1464 if ( 1465 mod_name[len(module_prefix):].startswith(plugin_name + '.') 1466 or mod_name[len(module_prefix):] == plugin_name 1467 ): 1468 _ = sys.modules.pop(mod_name, None) 1469 1470 if root_plugins_mod is not None and plugin_name in root_plugins_mod.__dict__: 1471 try: 1472 delattr(root_plugins_mod, plugin_name) 1473 except Exception: 1474 pass 1475 1476 ### Unload sync hooks. 1477 _ = _pre_sync_hooks.pop(plugin_name, None) 1478 _ = _post_sync_hooks.pop(plugin_name, None) 1479 _ = _plugins_import_errors.pop(plugin_name, None) 1480 1481 ### Unload API endpoints and pages. 1482 _ = _dash_plugins.pop(plugin_name, None) 1483 _ = _api_plugins.pop(plugin_name, None) 1484 with _locks['_console_head']: 1485 _ = _console_head.pop(plugin_name, None) 1486 web_page_funcs = _plugins_web_pages.pop(plugin_name, None) or [] 1487 page_groups_to_pop = [] 1488 for page_group, page_functions in _plugin_endpoints_to_pages.items(): 1489 page_functions_to_pop = [ 1490 page_str 1491 for page_str, page_payload in page_functions.items() 1492 if page_payload.get('function', None) in web_page_funcs 1493 ] 1494 for page_str in page_functions_to_pop: 1495 page_functions.pop(page_str, None) 1496 if not page_functions: 1497 page_groups_to_pop.append(page_group) 1498 1499 for page_group in page_groups_to_pop: 1500 _plugin_endpoints_to_pages.pop(page_group, None) 1501 1502 ### Remove all but injected symlinks. 1503 if remove_symlinks: 1504 dir_symlink_path = paths.PLUGINS_RESOURCES_PATH / plugin_name 1505 dir_symlink_injected_path = paths.PLUGINS_INJECTED_RESOURCES_PATH / plugin_name 1506 file_symlink_path = paths.PLUGINS_RESOURCES_PATH / f"{plugin_name}.py" 1507 file_symlink_injected_path = paths.PLUGINS_INJECTED_RESOURCES_PATH / f"{plugin_name}.py" 1508 1509 ### Only remove a symlink whose target NO LONGER EXISTS (a genuinely stale 1510 ### plugin). The per-root `.internal/plugins` directory is SHARED by every 1511 ### process operating on that root — including a `plugin:<name>`-backed 1512 ### background job that may have been started moments earlier (e.g. by 1513 ### `mrsm compose start jobs`, which loads project plugins, starts the job 1514 ### daemon, then unloads). Removing a still-valid plugin symlink here deletes 1515 ### it out from under that daemon, so its plugin import fails with 1516 ### "Plugin '<name>' cannot be found". In-memory unloading (popping 1517 ### `sys.modules` above) is process-local and is all that unloading needs; 1518 ### the symlink lifecycle is owned by `sync_plugins_symlinks`. 1519 def _target_exists(symlink_path): 1520 try: 1521 return pathlib.Path(os.path.realpath(symlink_path)).exists() 1522 except Exception: 1523 return False 1524 1525 try: 1526 if ( 1527 dir_symlink_path.exists() 1528 and not dir_symlink_injected_path.exists() 1529 and not _target_exists(dir_symlink_path) 1530 ): 1531 dir_symlink_path.unlink() 1532 except Exception: 1533 pass 1534 1535 try: 1536 if ( 1537 file_symlink_path.exists() 1538 and not file_symlink_injected_path.exists() 1539 and not _target_exists(file_symlink_path) 1540 ): 1541 file_symlink_path.unlink() 1542 except Exception: 1543 pass 1544 1545 1546def invalidate_plugins_cache() -> None: 1547 """ 1548 Pop the cached `plugins` package and its submodules from `sys.modules` 1549 and reset the loaded-plugins state. 1550 1551 The `plugins` package caches its `__path__` (the resolved 1552 `PLUGINS_RESOURCES_PATH`) at import time. When the active root or 1553 plugins-dir scope changes in-process (e.g. via 1554 `meerschaum.config.environment.replace_env`), that stale `__path__` 1555 makes subsequent plugin imports re-discover plugins under the previous 1556 scope's `.internal/plugins` directory. Call this whenever the plugins 1557 scope changes so the next import rebuilds against the current 1558 `PLUGINS_RESOURCES_PATH`. 1559 """ 1560 global _loaded_plugins, _synced_symlinks 1561 import sys 1562 import meerschaum.config.paths as paths 1563 1564 plugins_stem = paths.PLUGINS_RESOURCES_PATH.stem 1565 module_prefix = plugins_stem + '.' 1566 for mod_name in [ 1567 mod_name 1568 for mod_name in sys.modules 1569 if mod_name == plugins_stem or mod_name.startswith(module_prefix) 1570 ]: 1571 _ = sys.modules.pop(mod_name, None) 1572 1573 _loaded_plugins = False 1574 ### Also reset the symlinks counter — it's per-scope state, and leaving it 1575 ### >1 makes `sync_plugins_symlinks` skip creating the new scope's 1576 ### `.internal/plugins` (so `plugins` imports as an empty namespace package). 1577 _synced_symlinks = 0 1578 1579 1580def reload_plugins(plugins: Optional[List[str]] = None, debug: bool = False) -> None: 1581 """ 1582 Reload plugins back into memory. 1583 1584 Parameters 1585 ---------- 1586 plugins: Optional[List[str]], default None 1587 The plugins to reload. `None` will reload all plugins. 1588 1589 """ 1590 global _synced_symlinks 1591 unload_plugins(plugins, debug=debug) 1592 _synced_symlinks = 0 1593 sync_plugins_symlinks(debug=debug) 1594 load_plugins(skip_if_loaded=False, debug=debug) 1595 1596 1597def get_plugins(*to_load, try_import: bool = True) -> Union[Tuple[Plugin], Plugin]: 1598 """ 1599 Return a list of `Plugin` objects. 1600 1601 Parameters 1602 ---------- 1603 to_load: 1604 If specified, only load specific plugins. 1605 Otherwise return all plugins. 1606 1607 try_import: bool, default True 1608 If `True`, allow for plugins to be imported. 1609 """ 1610 import meerschaum.config.paths as paths 1611 import os 1612 sync_plugins_symlinks() 1613 sandboxed_names = sandboxed_plugins_names() 1614 if to_load: 1615 names = list(to_load) 1616 elif sandboxed_names is not None: 1617 names = sandboxed_names 1618 else: 1619 names = [ 1620 ( 1621 name if (paths.PLUGINS_RESOURCES_PATH / name).is_dir() 1622 else name[:-3] 1623 ) 1624 for name in os.listdir(paths.PLUGINS_RESOURCES_PATH) 1625 if name != '__init__.py' 1626 ] 1627 _plugins = [Plugin(name) for name in names] 1628 plugins = tuple(plugin for plugin in _plugins if plugin.is_installed(try_import=try_import)) 1629 if len(to_load) == 1: 1630 if len(plugins) == 0: 1631 raise ValueError(f"Plugin '{to_load[0]}' is not installed.") 1632 return plugins[0] 1633 return plugins 1634 1635 1636def sandboxed_plugins_names() -> Union[List[str], None]: 1637 """ 1638 In an isolated team's sandboxed process (5.1), the names of the team's own plugins (its 1639 `MRSM_PLUGINS_DIR` links them); the shared plugins package names every team's, which the 1640 process cannot read. `None` in any other process. 1641 """ 1642 import os 1643 import meerschaum.config._paths as native_paths 1644 namespace = native_paths._TEAM_SOURCE_NAMESPACE 1645 if namespace is not None: 1646 return sorted(namespace['names']) 1647 executor_grants = os.environ.get('MRSM_EXECUTOR_PLUGINS') 1648 if executor_grants is not None: 1649 import json 1650 names = json.loads(executor_grants) 1651 if not isinstance(names, list) or not all( 1652 isinstance(name, str) and name and len(name) <= 128 1653 and all(c.isascii() and (c.isalnum() or c in '_-') for c in name) 1654 for name in names 1655 ): 1656 raise ValueError('Invalid executor plugin grants.') 1657 return sorted(set(names)) 1658 if not os.environ.get('MRSM_TEAM_SANDBOX'): 1659 return None 1660 import meerschaum.config.paths as paths 1661 return [ 1662 (item[:-3] if item.endswith('.py') else item) 1663 for plugins_path in paths.PLUGINS_DIR_PATHS 1664 if plugins_path.exists() 1665 for item in sorted(os.listdir(plugins_path)) 1666 if not item.startswith('.') and item not in ('__pycache__', '__init__.py') 1667 ] 1668 1669 1670def get_plugins_names(*to_load, **kw) -> List[str]: 1671 """ 1672 Return a list of installed plugins. 1673 """ 1674 return [plugin.name for plugin in get_plugins(*to_load, **kw)] 1675 1676 1677def get_plugins_modules(*to_load, **kw) -> List['ModuleType']: 1678 """ 1679 Return a list of modules for the installed plugins, or `None` if things break. 1680 """ 1681 return [plugin.module for plugin in get_plugins(*to_load, **kw)] 1682 1683 1684_data_plugins_cache: Dict[Tuple[str, ...], List[Plugin]] = {} 1685def get_data_plugins() -> List[Plugin]: 1686 """ 1687 Only return the modules of plugins with either `fetch()` or `sync()` functions. 1688 """ 1689 import inspect 1690 plugins = get_plugins() 1691 1692 ### ponytail: cache on the installed plugins' names. 1693 ### Accessing `plugin.module` re-enters `import_plugins()` (venv activation + 1694 ### a nested `get_plugins()`) for every plugin, so an uncached call costs 1695 ### hundreds of milliseconds. The shell completer calls this on every keystroke 1696 ### (via `get_connector_labels()`), which is what made typing `-c` laggy. 1697 ### Installing or removing a plugin changes the key, so the cache self-invalidates; 1698 ### editing a plugin in place requires a restart to pick up a new `fetch()`/`sync()`. 1699 cache_key = tuple(plugin.name for plugin in plugins) 1700 if cache_key in _data_plugins_cache: 1701 return _data_plugins_cache[cache_key] 1702 1703 data_names = {'sync', 'fetch'} 1704 data_plugins = [] 1705 for plugin in plugins: 1706 if plugin.module is None: 1707 continue 1708 for name, ob in list(vars(plugin.module).items()): 1709 if not inspect.isfunction(ob): 1710 continue 1711 if name not in data_names: 1712 continue 1713 data_plugins.append(plugin) 1714 1715 _data_plugins_cache[cache_key] = data_plugins 1716 return data_plugins 1717 1718 1719def add_plugin_argument(*args, **kwargs) -> None: 1720 """ 1721 Add argparse arguments under the 'Plugins options' group. 1722 Takes the same parameters as the regular argparse `add_argument()` function. 1723 1724 Examples 1725 -------- 1726 >>> add_plugin_argument('--foo', type=int, help="This is my help text!") 1727 >>> 1728 """ 1729 from meerschaum._internal.arguments._parser import groups, _seen_plugin_args, parser 1730 from meerschaum.utils.warnings import warn 1731 _parent_plugin_name = _get_parent_plugin() 1732 title = f"Plugin '{_parent_plugin_name}' options" if _parent_plugin_name else 'Custom options' 1733 group_key = 'plugin_' + (_parent_plugin_name or '') 1734 if group_key not in groups: 1735 groups[group_key] = parser.add_argument_group( 1736 title = title, 1737 ) 1738 _seen_plugin_args[group_key] = set() 1739 try: 1740 if str(args) not in _seen_plugin_args[group_key]: 1741 groups[group_key].add_argument(*args, **kwargs) 1742 _seen_plugin_args[group_key].add(str(args)) 1743 except Exception as e: 1744 warn(e) 1745 1746 1747def inject_plugin_path( 1748 plugin_path: pathlib.Path, 1749 plugins_resources_path: Optional[pathlib.Path] = None) -> None: 1750 """ 1751 Inject a plugin as a symlink into the internal `plugins` directory. 1752 1753 Parameters 1754 ---------- 1755 plugin_path: pathlib.Path 1756 The path to the plugin's source module. 1757 """ 1758 import meerschaum.config.paths as paths 1759 from meerschaum.utils.misc import make_symlink 1760 if plugins_resources_path is None: 1761 plugins_resources_path = paths.PLUGINS_RESOURCES_PATH 1762 plugins_injected_resources_path = paths.PLUGINS_INJECTED_RESOURCES_PATH 1763 else: 1764 plugins_injected_resources_path = plugins_resources_path / '.injected' 1765 1766 if plugin_path.is_dir(): 1767 plugin_name = plugin_path.name 1768 dest_path = plugins_resources_path / plugin_name 1769 injected_path = plugins_injected_resources_path / plugin_name 1770 elif plugin_path.name == '__init__.py': 1771 plugin_name = plugin_path.parent.name 1772 dest_path = plugins_resources_path / plugin_name 1773 injected_path = plugins_injected_resources_path / plugin_name 1774 elif plugin_path.name.endswith('.py'): 1775 plugin_name = plugin_path.name[:(-1 * len('.py'))] 1776 dest_path = plugins_resources_path / plugin_path.name 1777 injected_path = plugins_injected_resources_path / plugin_path.name 1778 else: 1779 raise ValueError(f"Cannot deduce plugin name from path '{plugin_path}'.") 1780 1781 _injected_plugin_symlinks[dest_path] += 1 1782 make_symlink(plugin_path, dest_path) 1783 make_symlink(plugin_path, injected_path) 1784 1785 1786def _get_parent_plugin( 1787 stacklevel: Union[int, Tuple[int, ...]] = (1, 2, 3, 4), 1788 function: Optional[Callable[[Any], Any]] = None, 1789) -> Union[str, None]: 1790 """If this function is called from outside a Meerschaum plugin, it will return None.""" 1791 import inspect 1792 module_name = getattr(function, '__module__', '') 1793 if module_name.startswith('plugins.'): 1794 return module_name.split('.')[1] 1795 if not isinstance(stacklevel, tuple): 1796 stacklevel = (stacklevel,) 1797 1798 for _level in stacklevel: 1799 try: 1800 parent_globals = inspect.stack()[_level][0].f_globals 1801 global_name = parent_globals.get('__name__', '') 1802 if global_name.startswith('meerschaum.'): 1803 continue 1804 plugin_name = global_name.replace('plugins.', '').split('.')[0] 1805 if plugin_name.startswith('_') or plugin_name == 'importlib': 1806 continue 1807 return plugin_name 1808 except Exception: 1809 continue 1810 1811 return None
50class Plugin: 51 """Handle packaging of Meerschaum plugins.""" 52 53 def __init__( 54 self, 55 name: str, 56 version: Optional[str] = None, 57 user_id: Optional[int] = None, 58 required: Optional[List[str]] = None, 59 attributes: Optional[Dict[str, Any]] = None, 60 archive_path: Optional[pathlib.Path] = None, 61 venv_path: Optional[pathlib.Path] = None, 62 repo_connector: Optional['mrsm.connectors.api.APIConnector'] = None, 63 repo: Union['mrsm.connectors.api.APIConnector', str, None] = None, 64 ): 65 import meerschaum.config.paths as paths 66 from meerschaum._internal.static import STATIC_CONFIG 67 sep = STATIC_CONFIG['plugins']['repo_separator'] 68 _repo = None 69 if sep in name: 70 try: 71 name, _repo = name.split(sep) 72 except Exception as e: 73 error(f"Invalid plugin name: '{name}'") 74 self._repo_in_name = _repo 75 76 if attributes is None: 77 attributes = {} 78 self.name = name 79 self.attributes = attributes 80 self.user_id = user_id 81 self._version = version 82 if required: 83 self._required = required 84 self.archive_path = ( 85 archive_path if archive_path is not None 86 else paths.PLUGINS_ARCHIVES_RESOURCES_PATH / f"{self.name}.tar.gz" 87 ) 88 self.venv_path = ( 89 venv_path if venv_path is not None 90 else paths.VIRTENV_RESOURCES_PATH / self.name 91 ) 92 self._repo_connector = repo_connector 93 self._repo_keys = repo 94 95 96 @property 97 def repo_connector(self): 98 """ 99 Return the repository connector for this plugin. 100 NOTE: This imports the `connectors` module, which imports certain plugin modules. 101 """ 102 if self._repo_connector is None: 103 from meerschaum.connectors.parse import parse_repo_keys 104 105 repo_keys = self._repo_keys or self._repo_in_name 106 if self._repo_in_name and self._repo_keys and self._repo_keys != self._repo_in_name: 107 error( 108 f"Received inconsistent repos: '{self._repo_in_name}' and '{self._repo_keys}'." 109 ) 110 repo_connector = parse_repo_keys(repo_keys) 111 self._repo_connector = repo_connector 112 return self._repo_connector 113 114 115 @property 116 def version(self): 117 """ 118 Return the plugin's module version is defined (`__version__`) if it's defined. 119 """ 120 if self._version is None: 121 try: 122 self._version = self.module.__version__ 123 except Exception as e: 124 self._version = None 125 return self._version 126 127 128 @property 129 def module(self): 130 """ 131 Return the Python module of the underlying plugin, 132 or `None` if the plugin is not installed or its import failed 133 (check `Plugin.import_error` for the swallowed exception). 134 """ 135 if '_module' not in self.__dict__ or self.__dict__.get('_module', None) is None: 136 from meerschaum.plugins import _get_loaded_module, _get_plugins_package_name 137 loaded_module = _get_loaded_module(f'{_get_plugins_package_name()}.{self.name}') 138 if loaded_module is not None: 139 self._module = loaded_module 140 return self._module 141 142 if self.__file__ is None: 143 return None 144 145 from meerschaum.plugins import import_plugins 146 self._module = import_plugins(str(self), warn=False) 147 148 return self._module 149 150 @property 151 def import_error(self) -> Union[Exception, None]: 152 """ 153 Return the exception raised by this plugin's most recent failed import 154 (i.e. when `Plugin.module` is `None` even though the plugin is installed), 155 otherwise `None`. 156 """ 157 from meerschaum.plugins import _plugins_import_errors 158 return _plugins_import_errors.get(self.name, None) 159 160 161 @property 162 def __file__(self) -> Union[str, None]: 163 """ 164 Return the file path (str) of the plugin if it exists, otherwise `None`. 165 """ 166 if self.__dict__.get('_module', None) is not None: 167 return self.module.__file__ 168 169 import meerschaum.config.paths as paths 170 171 potential_dir = paths.PLUGINS_RESOURCES_PATH / self.name 172 if ( 173 potential_dir.exists() 174 and potential_dir.is_dir() 175 and (potential_dir / '__init__.py').exists() 176 ): 177 return str((potential_dir / '__init__.py').as_posix()) 178 179 potential_file = paths.PLUGINS_RESOURCES_PATH / (self.name + '.py') 180 if potential_file.exists() and not potential_file.is_dir(): 181 return str(potential_file.as_posix()) 182 183 return None 184 185 186 @property 187 def requirements_file_path(self) -> Union[pathlib.Path, None]: 188 """ 189 If a file named `requirements.txt` exists, return its path. 190 """ 191 if self.__file__ is None: 192 return None 193 path = pathlib.Path(self.__file__).parent / 'requirements.txt' 194 if not path.exists(): 195 return None 196 return path 197 198 199 def is_installed(self, **kw) -> bool: 200 """ 201 Check whether a plugin is correctly installed. 202 203 Returns 204 ------- 205 A `bool` indicating whether a plugin exists and is successfully imported. 206 """ 207 return self.__file__ is not None 208 209 210 def make_tar(self, debug: bool = False) -> pathlib.Path: 211 """ 212 Compress the plugin's source files into a `.tar.gz` archive and return the archive's path. 213 214 Parameters 215 ---------- 216 debug: bool, default False 217 Verbosity toggle. 218 219 Returns 220 ------- 221 A `pathlib.Path` to the archive file's path. 222 223 """ 224 import tarfile, pathlib, subprocess, fnmatch 225 from meerschaum.utils.debug import dprint 226 from meerschaum.utils.packages import attempt_import 227 pathspec = attempt_import('pathspec', debug=debug) 228 229 if not self.__file__: 230 from meerschaum.utils.warnings import error 231 error(f"Could not find file for plugin '{self}'.") 232 if '__init__.py' in self.__file__ or os.path.isdir(self.__file__): 233 path = self.__file__.replace('__init__.py', '') 234 is_dir = True 235 else: 236 path = self.__file__ 237 is_dir = False 238 239 old_cwd = os.getcwd() 240 real_parent_path = pathlib.Path(os.path.realpath(path)).parent 241 os.chdir(real_parent_path) 242 243 default_patterns_to_ignore = [ 244 '.pyc', 245 '__pycache__/', 246 'eggs/', 247 '__pypackages__/', 248 '.git', 249 ] 250 251 def parse_gitignore() -> 'Set[str]': 252 gitignore_path = pathlib.Path(path) / '.gitignore' 253 if not gitignore_path.exists(): 254 return set(default_patterns_to_ignore) 255 with open(gitignore_path, 'r', encoding='utf-8') as f: 256 gitignore_text = f.read() 257 return set(pathspec.PathSpec.from_lines( 258 pathspec.patterns.GitWildMatchPattern, 259 default_patterns_to_ignore + gitignore_text.splitlines() 260 ).match_tree(path)) 261 262 patterns_to_ignore = parse_gitignore() if is_dir else set() 263 264 if debug: 265 dprint(f"Patterns to ignore:\n{patterns_to_ignore}") 266 267 with tarfile.open(self.archive_path, 'w:gz') as tarf: 268 if not is_dir: 269 tarf.add(f"{self.name}.py") 270 else: 271 for root, dirs, files in os.walk(self.name): 272 for f in files: 273 good_file = True 274 fp = os.path.join(root, f) 275 for pattern in patterns_to_ignore: 276 if pattern in str(fp) or f.startswith('.'): 277 good_file = False 278 break 279 if good_file: 280 if debug: 281 dprint(f"Adding '{fp}'...") 282 tarf.add(fp) 283 284 ### clean up and change back to old directory 285 os.chdir(old_cwd) 286 287 ### change to 775 to avoid permissions issues with the API in a Docker container 288 self.archive_path.chmod(0o775) 289 290 if debug: 291 dprint(f"Created archive '{self.archive_path}'.") 292 return self.archive_path 293 294 295 def install( 296 self, 297 skip_deps: bool = False, 298 force: bool = False, 299 debug: bool = False, 300 ) -> SuccessTuple: 301 """ 302 Extract a plugin's tar archive to the plugins directory. 303 304 This function checks if the plugin is already installed and if the version is equal or 305 greater than the existing installation. 306 307 Parameters 308 ---------- 309 skip_deps: bool, default False 310 If `True`, do not install dependencies. 311 312 force: bool, default False 313 If `True`, continue with installation, even if required packages fail to install. 314 315 debug: bool, default False 316 Verbosity toggle. 317 318 Returns 319 ------- 320 A `SuccessTuple` of success (bool) and a message (str). 321 322 """ 323 installation_key = self.full_name 324 with _ongoing_installations_lock: 325 if installation_key in _ongoing_installations: 326 return True, f"Already installing plugin '{self}'." 327 _ongoing_installations.add(installation_key) 328 329 try: 330 from meerschaum.utils.packages import _pip_install_lock 331 with _pip_install_lock(self.name): 332 return self._install_with_rollback( 333 skip_deps=skip_deps, 334 force=force, 335 debug=debug, 336 ) 337 finally: 338 with _ongoing_installations_lock: 339 _ongoing_installations.discard(installation_key) 340 341 342 def _install_with_rollback( 343 self, 344 skip_deps: bool = False, 345 force: bool = False, 346 debug: bool = False, 347 ) -> SuccessTuple: 348 """Restore the previous plugin source and environment after a failed install.""" 349 import tempfile 350 import meerschaum.config.paths as paths 351 from meerschaum.plugins import sync_plugins_symlinks 352 from meerschaum.utils.packages import reload_meerschaum 353 354 if not self.archive_path.exists(): 355 return False, f"Missing archive file for plugin '{self}'." 356 357 paths.PLUGINS_TEMP_RESOURCES_PATH.mkdir(parents=True, exist_ok=True) 358 source_paths = [ 359 plugins_dir_path / filename 360 for plugins_dir_path in paths.PLUGINS_DIR_PATHS 361 for filename in (self.name, self.name + '.py') 362 ] 363 tracked_paths = source_paths + [paths.VIRTENV_RESOURCES_PATH / self.name] 364 365 with tempfile.TemporaryDirectory( 366 prefix=f'.{self.name}-rollback-', 367 dir=paths.PLUGINS_TEMP_RESOURCES_PATH, 368 ) as rollback_dir_str: 369 rollback_dir = pathlib.Path(rollback_dir_str) 370 backups = {} 371 rollback_prepared = False 372 373 def prepare_rollback() -> None: 374 nonlocal rollback_prepared 375 for index, path in enumerate(tracked_paths): 376 if not path.exists() and not path.is_symlink(): 377 continue 378 backup_path = rollback_dir / str(index) 379 _copy_path(path, backup_path) 380 backups[path] = backup_path 381 rollback_prepared = True 382 383 def rollback() -> None: 384 if not rollback_prepared: 385 return 386 for path in tracked_paths: 387 _remove_path(path) 388 for path, backup_path in backups.items(): 389 path.parent.mkdir(parents=True, exist_ok=True) 390 shutil.move(str(backup_path), str(path)) 391 self.__dict__.pop('_module', None) 392 self.__dict__.pop('_required', None) 393 sync_plugins_symlinks(debug=debug) 394 reload_meerschaum(debug=debug) 395 396 try: 397 result = self._install( 398 skip_deps=skip_deps, 399 force=force, 400 debug=debug, 401 _prepare_rollback=prepare_rollback, 402 ) 403 except BaseException: 404 rollback() 405 raise 406 if not result[0]: 407 try: 408 rollback() 409 except Exception as e: 410 return False, result[1] + f"\nFailed to roll back plugin '{self}': {e}" 411 return result 412 413 414 def _install( 415 self, 416 skip_deps: bool = False, 417 force: bool = False, 418 debug: bool = False, 419 _prepare_rollback: Optional[Any] = None, 420 ) -> SuccessTuple: 421 422 import meerschaum.config.paths as paths 423 from meerschaum.utils.warnings import warn, error 424 if debug: 425 from meerschaum.utils.debug import dprint 426 import tarfile 427 import re 428 import ast 429 from meerschaum.plugins import sync_plugins_symlinks 430 from meerschaum.utils.packages import attempt_import, reload_meerschaum 431 from meerschaum.utils.venv import init_venv 432 from meerschaum.utils.misc import safely_extract_tar 433 old_cwd = os.getcwd() 434 old_version = '' 435 new_version = '' 436 temp_dir = paths.PLUGINS_TEMP_RESOURCES_PATH / self.name 437 temp_dir.mkdir(exist_ok=True) 438 439 if not self.archive_path.exists(): 440 return False, f"Missing archive file for plugin '{self}'." 441 if self.version is not None: 442 old_version = self.version 443 if debug: 444 dprint(f"Found existing version '{old_version}' for plugin '{self}'.") 445 446 if debug: 447 dprint(f"Extracting '{self.archive_path}' to '{temp_dir}'...") 448 449 try: 450 with tarfile.open(self.archive_path, 'r:gz') as tarf: 451 safely_extract_tar(tarf, temp_dir) 452 except Exception as e: 453 warn(e) 454 return False, f"Failed to extract plugin '{self.name}'." 455 456 ### search for version information 457 files = os.listdir(temp_dir) 458 459 if str(files[0]) == self.name: 460 is_dir = True 461 elif str(files[0]) == self.name + '.py': 462 is_dir = False 463 else: 464 error(f"Unknown format encountered for plugin '{self}'.") 465 466 fpath = temp_dir / files[0] 467 if is_dir: 468 fpath = fpath / '__init__.py' 469 470 with open(fpath, 'r', encoding='utf-8') as f: 471 init_lines = f.readlines() 472 new_version = None 473 for line in init_lines: 474 if '__version__' not in line: 475 continue 476 version_match = re.search(r'__version__(\s?)=', line.lstrip().rstrip()) 477 if not version_match: 478 continue 479 new_version = ast.literal_eval(line.split('=')[1].lstrip().rstrip()) 480 break 481 if not new_version: 482 warn( 483 f"No `__version__` defined for plugin '{self}'. " 484 + "Assuming new version...", 485 stack = False, 486 ) 487 488 packaging_version = attempt_import('packaging.version') 489 try: 490 is_new_version = (not new_version and not old_version) or ( 491 packaging_version.parse(old_version) < packaging_version.parse(new_version) 492 ) 493 is_same_version = new_version and old_version and ( 494 packaging_version.parse(old_version) == packaging_version.parse(new_version) 495 ) 496 except Exception: 497 is_new_version, is_same_version = True, False 498 499 ### Determine where to permanently store the new plugin. 500 plugin_installation_dir_path = paths.PLUGINS_DIR_PATHS[0] 501 for path in paths.PLUGINS_DIR_PATHS: 502 if not path.exists(): 503 warn(f"Plugins path does not exist: {path}", stack=False) 504 continue 505 506 files_in_plugins_dir = os.listdir(path) 507 if ( 508 self.name in files_in_plugins_dir 509 or 510 (self.name + '.py') in files_in_plugins_dir 511 ): 512 plugin_installation_dir_path = path 513 break 514 515 success_msg = ( 516 f"Successfully installed plugin '{self}'" 517 + ("\n (skipped dependencies)" if skip_deps else "") 518 + "." 519 ) 520 success, abort = None, None 521 522 if is_same_version and not force: 523 success, msg = True, ( 524 f"Plugin '{self}' is up-to-date (version {old_version}).\n" + 525 " Install again with `-f` or `--force` to reinstall." 526 ) 527 abort = True 528 elif is_new_version or force: 529 if _prepare_rollback is not None: 530 _prepare_rollback() 531 source_path = temp_dir / files[0] 532 destination_path = plugin_installation_dir_path / files[0] 533 try: 534 plugin_installation_dir_path.mkdir(parents=True, exist_ok=True) 535 for existing_path in ( 536 plugin_installation_dir_path / self.name, 537 plugin_installation_dir_path / (self.name + '.py'), 538 ): 539 _remove_path(existing_path) 540 if debug: 541 dprint(f"Moving '{source_path}' to '{destination_path}'...") 542 shutil.move(str(source_path), str(destination_path)) 543 except Exception as e: 544 success, msg = False, f"Failed to install plugin '{self}': {e}" 545 else: 546 success, msg = True, success_msg 547 else: 548 success, msg = False, ( 549 f"Your installed version of plugin '{self}' ({old_version}) is higher than " 550 + f"attempted version {new_version}." 551 ) 552 553 shutil.rmtree(temp_dir) 554 os.chdir(old_cwd) 555 556 ### Reload the plugin's module. 557 sync_plugins_symlinks(debug=debug) 558 if '_module' in self.__dict__: 559 del self.__dict__['_module'] 560 init_venv(venv=self.name, force=True, debug=debug) 561 reload_meerschaum(debug=debug) 562 563 ### Record the origin only after a successful transaction. Locally-installed 564 ### plugins have no explicit repo and are intentionally skipped. 565 _origin_repo_keys = ( 566 str(self._repo_connector) 567 if self._repo_connector is not None 568 else self._repo_keys or self._repo_in_name 569 ) 570 571 def write_origin() -> None: 572 if not _origin_repo_keys: 573 return 574 try: 575 from meerschaum.plugins._origins import write_plugin_origin 576 write_plugin_origin( 577 self.name, 578 _origin_repo_keys, 579 plugin_installation_dir_path, 580 debug=debug, 581 ) 582 except Exception: 583 pass 584 585 if abort: 586 write_origin() 587 588 ### if we've already failed, return here 589 if not success or abort: 590 return success, msg 591 592 ### attempt to install dependencies 593 dependencies_installed = skip_deps or self.install_dependencies(force=force, debug=debug) 594 if not dependencies_installed: 595 return False, f"Failed to install dependencies for plugin '{self}'." 596 597 ### handling success tuple, bool, or other (typically None) 598 setup_tuple = self.setup(debug=debug) 599 if isinstance(setup_tuple, tuple): 600 if not setup_tuple[0]: 601 success, msg = setup_tuple 602 elif isinstance(setup_tuple, bool): 603 if not setup_tuple: 604 success, msg = False, ( 605 f"Failed to run post-install setup for plugin '{self}'." + '\n' + 606 f"Check `setup()` in '{self.__file__}' for more information " + 607 "(no error message provided)." 608 ) 609 else: 610 success, msg = True, success_msg 611 elif setup_tuple is None: 612 success = True 613 msg = ( 614 f"Post-install for plugin '{self}' returned None. " + 615 "Assuming plugin successfully installed." 616 ) 617 warn(msg) 618 else: 619 success = False 620 msg = ( 621 f"Post-install for plugin '{self}' returned unexpected value " + 622 f"of type '{type(setup_tuple)}': {setup_tuple}" 623 ) 624 625 _ = self.module 626 if success: 627 write_origin() 628 return success, msg 629 630 631 def remove_archive( 632 self, 633 debug: bool = False 634 ) -> SuccessTuple: 635 """Remove a plugin's archive file.""" 636 if not self.archive_path.exists(): 637 return True, f"Archive file for plugin '{self}' does not exist." 638 try: 639 self.archive_path.unlink() 640 except Exception as e: 641 return False, f"Failed to remove archive for plugin '{self}':\n{e}" 642 return True, "Success" 643 644 645 def remove_venv( 646 self, 647 debug: bool = False 648 ) -> SuccessTuple: 649 """Remove a plugin's virtual environment.""" 650 if not self.venv_path.exists(): 651 return True, f"Virtual environment for plugin '{self}' does not exist." 652 try: 653 shutil.rmtree(self.venv_path) 654 except Exception as e: 655 return False, f"Failed to remove virtual environment for plugin '{self}':\n{e}" 656 return True, "Success" 657 658 659 def uninstall(self, debug: bool = False) -> SuccessTuple: 660 """ 661 Remove a plugin, its virtual environment, and archive file. 662 """ 663 from meerschaum.utils.packages import reload_meerschaum 664 from meerschaum.plugins import sync_plugins_symlinks 665 from meerschaum.utils.warnings import warn, info 666 warnings_thrown_count: int = 0 667 max_warnings: int = 3 668 669 if not self.is_installed(): 670 info( 671 f"Plugin '{self.name}' doesn't seem to be installed.\n " 672 + "Checking for artifacts...", 673 stack = False, 674 ) 675 else: 676 real_path = pathlib.Path(os.path.realpath(self.__file__)) 677 try: 678 if real_path.name == '__init__.py': 679 shutil.rmtree(real_path.parent) 680 else: 681 real_path.unlink() 682 except Exception as e: 683 warn(f"Could not remove source files for plugin '{self.name}':\n{e}", stack=False) 684 warnings_thrown_count += 1 685 else: 686 info(f"Removed source files for plugin '{self.name}'.") 687 688 if self.venv_path.exists(): 689 success, msg = self.remove_venv(debug=debug) 690 if not success: 691 warn(msg, stack=False) 692 warnings_thrown_count += 1 693 else: 694 info(f"Removed virtual environment from plugin '{self.name}'.") 695 696 success = warnings_thrown_count < max_warnings 697 try: 698 from meerschaum.plugins._origins import remove_plugin_origin 699 remove_plugin_origin(self.name, debug=debug) 700 except Exception: 701 pass 702 sync_plugins_symlinks(debug=debug) 703 self.deactivate_venv(force=True, debug=debug) 704 reload_meerschaum(debug=debug) 705 return success, ( 706 f"Successfully uninstalled plugin '{self}'." if success 707 else f"Failed to uninstall plugin '{self}'." 708 ) 709 710 711 def setup(self, *args: str, debug: bool = False, **kw: Any) -> Union[SuccessTuple, bool]: 712 """ 713 If exists, run the plugin's `setup()` function. 714 715 Parameters 716 ---------- 717 *args: str 718 The positional arguments passed to the `setup()` function. 719 720 debug: bool, default False 721 Verbosity toggle. 722 723 **kw: Any 724 The keyword arguments passed to the `setup()` function. 725 726 Returns 727 ------- 728 A `SuccessTuple` or `bool` indicating success. 729 730 """ 731 from meerschaum.utils.debug import dprint 732 import inspect 733 _setup = None 734 for name, fp in inspect.getmembers(self.module): 735 if name == 'setup' and inspect.isfunction(fp): 736 _setup = fp 737 break 738 739 ### assume success if no setup() is found (not necessary) 740 if _setup is None: 741 return True 742 743 sig = inspect.signature(_setup) 744 has_debug, has_kw = ('debug' in sig.parameters), False 745 for k, v in sig.parameters.items(): 746 if '**' in str(v): 747 has_kw = True 748 break 749 750 _kw = {} 751 if has_kw: 752 _kw.update(kw) 753 if has_debug: 754 _kw['debug'] = debug 755 756 if debug: 757 dprint(f"Running setup for plugin '{self}'...") 758 from meerschaum.utils.venv import Venv 759 try: 760 with Venv(self, debug=debug): 761 return_tuple = _setup(*args, **_kw) 762 except Exception as e: 763 return False, str(e) 764 765 if isinstance(return_tuple, tuple): 766 return return_tuple 767 if isinstance(return_tuple, bool): 768 return return_tuple, f"Setup for Plugin '{self.name}' did not return a message." 769 if return_tuple is None: 770 return False, f"Setup for Plugin '{self.name}' returned None." 771 return False, f"Unknown return value from setup for Plugin '{self.name}': {return_tuple}" 772 773 774 def get_dependencies( 775 self, 776 debug: bool = False, 777 ) -> List[str]: 778 """ 779 If the Plugin has specified dependencies in a list called `required`, return the list. 780 781 **NOTE:** Dependecies which start with `'plugin:'` are Meerschaum plugins, not pip packages. 782 Meerschaum plugins may also specify connector keys for a repo after `'@'`. 783 784 Parameters 785 ---------- 786 debug: bool, default False 787 Verbosity toggle. 788 789 Returns 790 ------- 791 A list of required packages and plugins (str). 792 793 """ 794 if '_required' in self.__dict__: 795 return self._required 796 797 ### If the plugin has not yet been imported, 798 ### infer the dependencies from the source text. 799 ### This is not super robust, and it doesn't feel right 800 ### having multiple versions of the logic. 801 ### This is necessary when determining the activation order 802 ### without having import the module. 803 ### For consistency's sake, the module-less method does not cache the requirements. 804 if self.__dict__.get('_module', None) is None: 805 file_path = self.__file__ 806 if file_path is None: 807 return [] 808 with open(file_path, 'r', encoding='utf-8') as f: 809 text = f.read() 810 811 if 'required' not in text: 812 return [] 813 814 ### This has some limitations: 815 ### It relies on `required` being manually declared. 816 ### We lose the ability to dynamically alter the `required` list, 817 ### which is why we've kept the module-reliant method below. 818 import ast, re 819 ### NOTE: This technically would break 820 ### if `required` was the very first line of the file. 821 req_start_match = re.search(r'\nrequired(:\s*)?.*=', text) 822 if not req_start_match: 823 return [] 824 req_start = req_start_match.start() 825 equals_sign = req_start + text[req_start:].find('=') 826 827 ### Dependencies may have brackets within the strings, so push back the index. 828 first_opening_brace = equals_sign + 1 + text[equals_sign:].find('[') 829 if first_opening_brace == -1: 830 return [] 831 832 next_closing_brace = equals_sign + 1 + text[equals_sign:].find(']') 833 if next_closing_brace == -1: 834 return [] 835 836 start_ix = first_opening_brace + 1 837 end_ix = next_closing_brace 838 839 num_braces = 0 840 while True: 841 if '[' not in text[start_ix:end_ix]: 842 break 843 num_braces += 1 844 start_ix = end_ix 845 end_ix += text[end_ix + 1:].find(']') + 1 846 847 req_end = end_ix + 1 848 req_text = ( 849 text[(first_opening_brace-1):req_end] 850 .lstrip() 851 .replace('=', '', 1) 852 .lstrip() 853 .rstrip() 854 ) 855 try: 856 required = ast.literal_eval(req_text) 857 except Exception as e: 858 warn( 859 f"Unable to determine requirements for plugin '{self.name}' " 860 + "without importing the module.\n" 861 + " This may be due to dynamically setting the global `required` list.\n" 862 + f" {e}" 863 ) 864 return [] 865 return required 866 867 import inspect 868 self.activate_venv(dependencies=False, debug=debug) 869 required = [] 870 for name, val in inspect.getmembers(self.module): 871 if name == 'required': 872 required = val 873 break 874 self._required = required 875 self.deactivate_venv(dependencies=False, debug=debug) 876 return required 877 878 879 def get_required_plugins(self, debug: bool=False) -> List[mrsm.plugins.Plugin]: 880 """ 881 Return a list of required Plugin objects. 882 """ 883 from meerschaum.utils.warnings import warn 884 from meerschaum.config import get_config 885 from meerschaum._internal.static import STATIC_CONFIG 886 from meerschaum.connectors.parse import is_valid_connector_keys 887 plugins = [] 888 _deps = self.get_dependencies(debug=debug) 889 sep = STATIC_CONFIG['plugins']['repo_separator'] 890 plugin_names = [ 891 _d[len('plugin:'):] for _d in _deps 892 if _d.startswith('plugin:') and len(_d) > len('plugin:') 893 ] 894 default_repo_keys = get_config('meerschaum', 'repository') 895 skipped_repo_keys = set() 896 897 for _plugin_name in plugin_names: 898 if sep in _plugin_name: 899 try: 900 _plugin_name, _repo_keys = _plugin_name.split(sep) 901 except Exception: 902 _repo_keys = default_repo_keys 903 warn( 904 f"Invalid repo keys for required plugin '{_plugin_name}'.\n " 905 + f"Will try to use '{_repo_keys}' instead.", 906 stack = False, 907 ) 908 else: 909 _repo_keys = default_repo_keys 910 911 if _repo_keys in skipped_repo_keys: 912 continue 913 914 if not is_valid_connector_keys(_repo_keys): 915 warn( 916 f"Invalid connector '{_repo_keys}'.\n" 917 f" Skipping required plugins from repository '{_repo_keys}'", 918 stack=False, 919 ) 920 continue 921 922 plugins.append(Plugin(_plugin_name, repo=_repo_keys)) 923 924 return plugins 925 926 927 def get_required_packages(self, debug: bool=False) -> List[str]: 928 """ 929 Return the required package names (excluding plugins). 930 """ 931 _deps = self.get_dependencies(debug=debug) 932 return [_d for _d in _deps if not _d.startswith('plugin:')] 933 934 935 def activate_venv( 936 self, 937 dependencies: bool = True, 938 init_if_not_exists: bool = True, 939 debug: bool = False, 940 **kw 941 ) -> bool: 942 """ 943 Activate the virtual environments for the plugin and its dependencies. 944 945 Parameters 946 ---------- 947 dependencies: bool, default True 948 If `True`, activate the virtual environments for required plugins. 949 950 Returns 951 ------- 952 A bool indicating success. 953 """ 954 import meerschaum.config.paths as paths 955 from meerschaum.config._paths import _TEAM_SOURCE_NAMESPACE 956 from meerschaum.utils.venv import venv_target_path 957 from meerschaum.utils.packages import activate_venv 958 from meerschaum.utils.misc import make_symlink, is_symlink 959 960 if dependencies: 961 for plugin in self.get_required_plugins(debug=debug): 962 plugin.activate_venv(debug=debug, init_if_not_exists=init_if_not_exists, **kw) 963 964 if _TEAM_SOURCE_NAMESPACE is not None and self.name in _TEAM_SOURCE_NAMESPACE['names']: 965 # A freshly granted Team source can import from its sealed view before it has 966 # a private environment. Let normal activation handle any existing environment. 967 try: 968 (paths.VIRTENV_RESOURCES_PATH / self.name).lstat() 969 except FileNotFoundError: 970 return False 971 972 vtp = venv_target_path(self.name, debug=debug, allow_nonexistent=True) 973 venv_meerschaum_path = vtp / 'meerschaum' 974 975 try: 976 success, msg = True, "Success" 977 if is_symlink(venv_meerschaum_path): 978 if pathlib.Path(os.path.realpath(venv_meerschaum_path)) != paths.PACKAGE_ROOT_PATH: 979 venv_meerschaum_path.unlink() 980 success, msg = make_symlink(venv_meerschaum_path, paths.PACKAGE_ROOT_PATH) 981 except Exception as e: 982 success, msg = False, str(e) 983 if not success: 984 warn( 985 f"Unable to create symlink {venv_meerschaum_path} to {paths.PACKAGE_ROOT_PATH}:\n" 986 f"{msg}" 987 ) 988 989 return activate_venv(self.name, init_if_not_exists=init_if_not_exists, debug=debug, **kw) 990 991 992 def deactivate_venv(self, dependencies: bool=True, debug: bool = False, **kw) -> bool: 993 """ 994 Deactivate the virtual environments for the plugin and its dependencies. 995 996 Parameters 997 ---------- 998 dependencies: bool, default True 999 If `True`, deactivate the virtual environments for required plugins. 1000 1001 Returns 1002 ------- 1003 A bool indicating success. 1004 """ 1005 from meerschaum.utils.packages import deactivate_venv 1006 success = deactivate_venv(self.name, debug=debug, **kw) 1007 if dependencies: 1008 for plugin in self.get_required_plugins(debug=debug): 1009 plugin.deactivate_venv(debug=debug, **kw) 1010 return success 1011 1012 1013 def install_dependencies( 1014 self, 1015 force: bool = False, 1016 debug: bool = False, 1017 ) -> bool: 1018 """ 1019 If specified, install dependencies. 1020 1021 **NOTE:** Dependencies that start with `'plugin:'` will be installed as 1022 Meerschaum plugins from the same repository as this Plugin. 1023 To install from a different repository, add the repo keys after `'@'` 1024 (e.g. `'plugin:foo@api:bar'`). 1025 1026 Parameters 1027 ---------- 1028 force: bool, default False 1029 If `True`, continue with the installation, even if some 1030 required packages fail to install. 1031 1032 debug: bool, default False 1033 Verbosity toggle. 1034 1035 Returns 1036 ------- 1037 A bool indicating success. 1038 """ 1039 from meerschaum.utils.packages import pip_install, venv_contains_package 1040 from meerschaum.utils.warnings import warn, info 1041 _deps = self.get_dependencies(debug=debug) 1042 if not _deps and self.requirements_file_path is None: 1043 return True 1044 1045 plugins = self.get_required_plugins(debug=debug) 1046 for _plugin in plugins: 1047 if _plugin.name == self.name: 1048 warn(f"Plugin '{self.name}' cannot depend on itself! Skipping...", stack=False) 1049 continue 1050 _success, _msg = _plugin.repo_connector.install_plugin( 1051 _plugin.name, debug=debug, force=force 1052 ) 1053 if not _success: 1054 warn( 1055 f"Failed to install required plugin '{_plugin}' from '{_plugin.repo_connector}'" 1056 + f" for plugin '{self.name}':\n" + _msg, 1057 stack = False, 1058 ) 1059 if not force: 1060 warn( 1061 "Try installing with the `--force` flag to continue anyway.", 1062 stack = False, 1063 ) 1064 return False 1065 info( 1066 "Continuing with installation despite the failure " 1067 + "(careful, things might be broken!)...", 1068 icon = False 1069 ) 1070 1071 1072 ### First step: parse `requirements.txt` if it exists. 1073 if self.requirements_file_path is not None: 1074 if not pip_install( 1075 requirements_file_path=self.requirements_file_path, 1076 venv=self.name, debug=debug 1077 ): 1078 warn( 1079 f"Failed to resolve 'requirements.txt' for plugin '{self.name}'.", 1080 stack = False, 1081 ) 1082 if not force: 1083 warn( 1084 "Try installing with `--force` to continue anyway.", 1085 stack = False, 1086 ) 1087 return False 1088 info( 1089 "Continuing with installation despite the failure " 1090 + "(careful, things might be broken!)...", 1091 icon = False 1092 ) 1093 1094 1095 ### Don't reinstall packages that are already included in required plugins. 1096 packages = [] 1097 _packages = self.get_required_packages(debug=debug) 1098 accounted_for_packages = set() 1099 for package_name in _packages: 1100 for plugin in plugins: 1101 if venv_contains_package(package_name, plugin.name): 1102 accounted_for_packages.add(package_name) 1103 break 1104 packages = [pkg for pkg in _packages if pkg not in accounted_for_packages] 1105 1106 ### Attempt pip packages installation. 1107 if packages: 1108 for package in packages: 1109 if not pip_install(package, venv=self.name, debug=debug): 1110 warn( 1111 f"Failed to install required package '{package}'" 1112 + f" for plugin '{self.name}'.", 1113 stack = False, 1114 ) 1115 if not force: 1116 warn( 1117 "Try installing with `--force` to continue anyway.", 1118 stack = False, 1119 ) 1120 return False 1121 info( 1122 "Continuing with installation despite the failure " 1123 + "(careful, things might be broken!)...", 1124 icon = False 1125 ) 1126 return True 1127 1128 1129 @property 1130 def full_name(self) -> str: 1131 """ 1132 Include the repo keys with the plugin's name. 1133 """ 1134 from meerschaum._internal.static import STATIC_CONFIG 1135 sep = STATIC_CONFIG['plugins']['repo_separator'] 1136 return self.name + sep + str(self.repo_connector) 1137 1138 1139 def __str__(self): 1140 return self.name 1141 1142 1143 def __repr__(self): 1144 return f"Plugin('{self.name}', repo='{self.repo_connector}')" 1145 1146 1147 def __del__(self): 1148 pass
Handle packaging of Meerschaum plugins.
53 def __init__( 54 self, 55 name: str, 56 version: Optional[str] = None, 57 user_id: Optional[int] = None, 58 required: Optional[List[str]] = None, 59 attributes: Optional[Dict[str, Any]] = None, 60 archive_path: Optional[pathlib.Path] = None, 61 venv_path: Optional[pathlib.Path] = None, 62 repo_connector: Optional['mrsm.connectors.api.APIConnector'] = None, 63 repo: Union['mrsm.connectors.api.APIConnector', str, None] = None, 64 ): 65 import meerschaum.config.paths as paths 66 from meerschaum._internal.static import STATIC_CONFIG 67 sep = STATIC_CONFIG['plugins']['repo_separator'] 68 _repo = None 69 if sep in name: 70 try: 71 name, _repo = name.split(sep) 72 except Exception as e: 73 error(f"Invalid plugin name: '{name}'") 74 self._repo_in_name = _repo 75 76 if attributes is None: 77 attributes = {} 78 self.name = name 79 self.attributes = attributes 80 self.user_id = user_id 81 self._version = version 82 if required: 83 self._required = required 84 self.archive_path = ( 85 archive_path if archive_path is not None 86 else paths.PLUGINS_ARCHIVES_RESOURCES_PATH / f"{self.name}.tar.gz" 87 ) 88 self.venv_path = ( 89 venv_path if venv_path is not None 90 else paths.VIRTENV_RESOURCES_PATH / self.name 91 ) 92 self._repo_connector = repo_connector 93 self._repo_keys = repo
96 @property 97 def repo_connector(self): 98 """ 99 Return the repository connector for this plugin. 100 NOTE: This imports the `connectors` module, which imports certain plugin modules. 101 """ 102 if self._repo_connector is None: 103 from meerschaum.connectors.parse import parse_repo_keys 104 105 repo_keys = self._repo_keys or self._repo_in_name 106 if self._repo_in_name and self._repo_keys and self._repo_keys != self._repo_in_name: 107 error( 108 f"Received inconsistent repos: '{self._repo_in_name}' and '{self._repo_keys}'." 109 ) 110 repo_connector = parse_repo_keys(repo_keys) 111 self._repo_connector = repo_connector 112 return self._repo_connector
Return the repository connector for this plugin.
NOTE: This imports the connectors module, which imports certain plugin modules.
115 @property 116 def version(self): 117 """ 118 Return the plugin's module version is defined (`__version__`) if it's defined. 119 """ 120 if self._version is None: 121 try: 122 self._version = self.module.__version__ 123 except Exception as e: 124 self._version = None 125 return self._version
Return the plugin's module version is defined (__version__) if it's defined.
128 @property 129 def module(self): 130 """ 131 Return the Python module of the underlying plugin, 132 or `None` if the plugin is not installed or its import failed 133 (check `Plugin.import_error` for the swallowed exception). 134 """ 135 if '_module' not in self.__dict__ or self.__dict__.get('_module', None) is None: 136 from meerschaum.plugins import _get_loaded_module, _get_plugins_package_name 137 loaded_module = _get_loaded_module(f'{_get_plugins_package_name()}.{self.name}') 138 if loaded_module is not None: 139 self._module = loaded_module 140 return self._module 141 142 if self.__file__ is None: 143 return None 144 145 from meerschaum.plugins import import_plugins 146 self._module = import_plugins(str(self), warn=False) 147 148 return self._module
Return the Python module of the underlying plugin,
or None if the plugin is not installed or its import failed
(check Plugin.import_error for the swallowed exception).
150 @property 151 def import_error(self) -> Union[Exception, None]: 152 """ 153 Return the exception raised by this plugin's most recent failed import 154 (i.e. when `Plugin.module` is `None` even though the plugin is installed), 155 otherwise `None`. 156 """ 157 from meerschaum.plugins import _plugins_import_errors 158 return _plugins_import_errors.get(self.name, None)
Return the exception raised by this plugin's most recent failed import
(i.e. when Plugin.module is None even though the plugin is installed),
otherwise None.
186 @property 187 def requirements_file_path(self) -> Union[pathlib.Path, None]: 188 """ 189 If a file named `requirements.txt` exists, return its path. 190 """ 191 if self.__file__ is None: 192 return None 193 path = pathlib.Path(self.__file__).parent / 'requirements.txt' 194 if not path.exists(): 195 return None 196 return path
If a file named requirements.txt exists, return its path.
199 def is_installed(self, **kw) -> bool: 200 """ 201 Check whether a plugin is correctly installed. 202 203 Returns 204 ------- 205 A `bool` indicating whether a plugin exists and is successfully imported. 206 """ 207 return self.__file__ is not None
Check whether a plugin is correctly installed.
Returns
- A
boolindicating whether a plugin exists and is successfully imported.
210 def make_tar(self, debug: bool = False) -> pathlib.Path: 211 """ 212 Compress the plugin's source files into a `.tar.gz` archive and return the archive's path. 213 214 Parameters 215 ---------- 216 debug: bool, default False 217 Verbosity toggle. 218 219 Returns 220 ------- 221 A `pathlib.Path` to the archive file's path. 222 223 """ 224 import tarfile, pathlib, subprocess, fnmatch 225 from meerschaum.utils.debug import dprint 226 from meerschaum.utils.packages import attempt_import 227 pathspec = attempt_import('pathspec', debug=debug) 228 229 if not self.__file__: 230 from meerschaum.utils.warnings import error 231 error(f"Could not find file for plugin '{self}'.") 232 if '__init__.py' in self.__file__ or os.path.isdir(self.__file__): 233 path = self.__file__.replace('__init__.py', '') 234 is_dir = True 235 else: 236 path = self.__file__ 237 is_dir = False 238 239 old_cwd = os.getcwd() 240 real_parent_path = pathlib.Path(os.path.realpath(path)).parent 241 os.chdir(real_parent_path) 242 243 default_patterns_to_ignore = [ 244 '.pyc', 245 '__pycache__/', 246 'eggs/', 247 '__pypackages__/', 248 '.git', 249 ] 250 251 def parse_gitignore() -> 'Set[str]': 252 gitignore_path = pathlib.Path(path) / '.gitignore' 253 if not gitignore_path.exists(): 254 return set(default_patterns_to_ignore) 255 with open(gitignore_path, 'r', encoding='utf-8') as f: 256 gitignore_text = f.read() 257 return set(pathspec.PathSpec.from_lines( 258 pathspec.patterns.GitWildMatchPattern, 259 default_patterns_to_ignore + gitignore_text.splitlines() 260 ).match_tree(path)) 261 262 patterns_to_ignore = parse_gitignore() if is_dir else set() 263 264 if debug: 265 dprint(f"Patterns to ignore:\n{patterns_to_ignore}") 266 267 with tarfile.open(self.archive_path, 'w:gz') as tarf: 268 if not is_dir: 269 tarf.add(f"{self.name}.py") 270 else: 271 for root, dirs, files in os.walk(self.name): 272 for f in files: 273 good_file = True 274 fp = os.path.join(root, f) 275 for pattern in patterns_to_ignore: 276 if pattern in str(fp) or f.startswith('.'): 277 good_file = False 278 break 279 if good_file: 280 if debug: 281 dprint(f"Adding '{fp}'...") 282 tarf.add(fp) 283 284 ### clean up and change back to old directory 285 os.chdir(old_cwd) 286 287 ### change to 775 to avoid permissions issues with the API in a Docker container 288 self.archive_path.chmod(0o775) 289 290 if debug: 291 dprint(f"Created archive '{self.archive_path}'.") 292 return self.archive_path
Compress the plugin's source files into a .tar.gz archive and return the archive's path.
Parameters
- debug (bool, default False): Verbosity toggle.
Returns
- A
pathlib.Pathto the archive file's path.
295 def install( 296 self, 297 skip_deps: bool = False, 298 force: bool = False, 299 debug: bool = False, 300 ) -> SuccessTuple: 301 """ 302 Extract a plugin's tar archive to the plugins directory. 303 304 This function checks if the plugin is already installed and if the version is equal or 305 greater than the existing installation. 306 307 Parameters 308 ---------- 309 skip_deps: bool, default False 310 If `True`, do not install dependencies. 311 312 force: bool, default False 313 If `True`, continue with installation, even if required packages fail to install. 314 315 debug: bool, default False 316 Verbosity toggle. 317 318 Returns 319 ------- 320 A `SuccessTuple` of success (bool) and a message (str). 321 322 """ 323 installation_key = self.full_name 324 with _ongoing_installations_lock: 325 if installation_key in _ongoing_installations: 326 return True, f"Already installing plugin '{self}'." 327 _ongoing_installations.add(installation_key) 328 329 try: 330 from meerschaum.utils.packages import _pip_install_lock 331 with _pip_install_lock(self.name): 332 return self._install_with_rollback( 333 skip_deps=skip_deps, 334 force=force, 335 debug=debug, 336 ) 337 finally: 338 with _ongoing_installations_lock: 339 _ongoing_installations.discard(installation_key)
Extract a plugin's tar archive to the plugins directory.
This function checks if the plugin is already installed and if the version is equal or greater than the existing installation.
Parameters
- skip_deps (bool, default False):
If
True, do not install dependencies. - force (bool, default False):
If
True, continue with installation, even if required packages fail to install. - debug (bool, default False): Verbosity toggle.
Returns
- A
SuccessTupleof success (bool) and a message (str).
631 def remove_archive( 632 self, 633 debug: bool = False 634 ) -> SuccessTuple: 635 """Remove a plugin's archive file.""" 636 if not self.archive_path.exists(): 637 return True, f"Archive file for plugin '{self}' does not exist." 638 try: 639 self.archive_path.unlink() 640 except Exception as e: 641 return False, f"Failed to remove archive for plugin '{self}':\n{e}" 642 return True, "Success"
Remove a plugin's archive file.
645 def remove_venv( 646 self, 647 debug: bool = False 648 ) -> SuccessTuple: 649 """Remove a plugin's virtual environment.""" 650 if not self.venv_path.exists(): 651 return True, f"Virtual environment for plugin '{self}' does not exist." 652 try: 653 shutil.rmtree(self.venv_path) 654 except Exception as e: 655 return False, f"Failed to remove virtual environment for plugin '{self}':\n{e}" 656 return True, "Success"
Remove a plugin's virtual environment.
659 def uninstall(self, debug: bool = False) -> SuccessTuple: 660 """ 661 Remove a plugin, its virtual environment, and archive file. 662 """ 663 from meerschaum.utils.packages import reload_meerschaum 664 from meerschaum.plugins import sync_plugins_symlinks 665 from meerschaum.utils.warnings import warn, info 666 warnings_thrown_count: int = 0 667 max_warnings: int = 3 668 669 if not self.is_installed(): 670 info( 671 f"Plugin '{self.name}' doesn't seem to be installed.\n " 672 + "Checking for artifacts...", 673 stack = False, 674 ) 675 else: 676 real_path = pathlib.Path(os.path.realpath(self.__file__)) 677 try: 678 if real_path.name == '__init__.py': 679 shutil.rmtree(real_path.parent) 680 else: 681 real_path.unlink() 682 except Exception as e: 683 warn(f"Could not remove source files for plugin '{self.name}':\n{e}", stack=False) 684 warnings_thrown_count += 1 685 else: 686 info(f"Removed source files for plugin '{self.name}'.") 687 688 if self.venv_path.exists(): 689 success, msg = self.remove_venv(debug=debug) 690 if not success: 691 warn(msg, stack=False) 692 warnings_thrown_count += 1 693 else: 694 info(f"Removed virtual environment from plugin '{self.name}'.") 695 696 success = warnings_thrown_count < max_warnings 697 try: 698 from meerschaum.plugins._origins import remove_plugin_origin 699 remove_plugin_origin(self.name, debug=debug) 700 except Exception: 701 pass 702 sync_plugins_symlinks(debug=debug) 703 self.deactivate_venv(force=True, debug=debug) 704 reload_meerschaum(debug=debug) 705 return success, ( 706 f"Successfully uninstalled plugin '{self}'." if success 707 else f"Failed to uninstall plugin '{self}'." 708 )
Remove a plugin, its virtual environment, and archive file.
711 def setup(self, *args: str, debug: bool = False, **kw: Any) -> Union[SuccessTuple, bool]: 712 """ 713 If exists, run the plugin's `setup()` function. 714 715 Parameters 716 ---------- 717 *args: str 718 The positional arguments passed to the `setup()` function. 719 720 debug: bool, default False 721 Verbosity toggle. 722 723 **kw: Any 724 The keyword arguments passed to the `setup()` function. 725 726 Returns 727 ------- 728 A `SuccessTuple` or `bool` indicating success. 729 730 """ 731 from meerschaum.utils.debug import dprint 732 import inspect 733 _setup = None 734 for name, fp in inspect.getmembers(self.module): 735 if name == 'setup' and inspect.isfunction(fp): 736 _setup = fp 737 break 738 739 ### assume success if no setup() is found (not necessary) 740 if _setup is None: 741 return True 742 743 sig = inspect.signature(_setup) 744 has_debug, has_kw = ('debug' in sig.parameters), False 745 for k, v in sig.parameters.items(): 746 if '**' in str(v): 747 has_kw = True 748 break 749 750 _kw = {} 751 if has_kw: 752 _kw.update(kw) 753 if has_debug: 754 _kw['debug'] = debug 755 756 if debug: 757 dprint(f"Running setup for plugin '{self}'...") 758 from meerschaum.utils.venv import Venv 759 try: 760 with Venv(self, debug=debug): 761 return_tuple = _setup(*args, **_kw) 762 except Exception as e: 763 return False, str(e) 764 765 if isinstance(return_tuple, tuple): 766 return return_tuple 767 if isinstance(return_tuple, bool): 768 return return_tuple, f"Setup for Plugin '{self.name}' did not return a message." 769 if return_tuple is None: 770 return False, f"Setup for Plugin '{self.name}' returned None." 771 return False, f"Unknown return value from setup for Plugin '{self.name}': {return_tuple}"
774 def get_dependencies( 775 self, 776 debug: bool = False, 777 ) -> List[str]: 778 """ 779 If the Plugin has specified dependencies in a list called `required`, return the list. 780 781 **NOTE:** Dependecies which start with `'plugin:'` are Meerschaum plugins, not pip packages. 782 Meerschaum plugins may also specify connector keys for a repo after `'@'`. 783 784 Parameters 785 ---------- 786 debug: bool, default False 787 Verbosity toggle. 788 789 Returns 790 ------- 791 A list of required packages and plugins (str). 792 793 """ 794 if '_required' in self.__dict__: 795 return self._required 796 797 ### If the plugin has not yet been imported, 798 ### infer the dependencies from the source text. 799 ### This is not super robust, and it doesn't feel right 800 ### having multiple versions of the logic. 801 ### This is necessary when determining the activation order 802 ### without having import the module. 803 ### For consistency's sake, the module-less method does not cache the requirements. 804 if self.__dict__.get('_module', None) is None: 805 file_path = self.__file__ 806 if file_path is None: 807 return [] 808 with open(file_path, 'r', encoding='utf-8') as f: 809 text = f.read() 810 811 if 'required' not in text: 812 return [] 813 814 ### This has some limitations: 815 ### It relies on `required` being manually declared. 816 ### We lose the ability to dynamically alter the `required` list, 817 ### which is why we've kept the module-reliant method below. 818 import ast, re 819 ### NOTE: This technically would break 820 ### if `required` was the very first line of the file. 821 req_start_match = re.search(r'\nrequired(:\s*)?.*=', text) 822 if not req_start_match: 823 return [] 824 req_start = req_start_match.start() 825 equals_sign = req_start + text[req_start:].find('=') 826 827 ### Dependencies may have brackets within the strings, so push back the index. 828 first_opening_brace = equals_sign + 1 + text[equals_sign:].find('[') 829 if first_opening_brace == -1: 830 return [] 831 832 next_closing_brace = equals_sign + 1 + text[equals_sign:].find(']') 833 if next_closing_brace == -1: 834 return [] 835 836 start_ix = first_opening_brace + 1 837 end_ix = next_closing_brace 838 839 num_braces = 0 840 while True: 841 if '[' not in text[start_ix:end_ix]: 842 break 843 num_braces += 1 844 start_ix = end_ix 845 end_ix += text[end_ix + 1:].find(']') + 1 846 847 req_end = end_ix + 1 848 req_text = ( 849 text[(first_opening_brace-1):req_end] 850 .lstrip() 851 .replace('=', '', 1) 852 .lstrip() 853 .rstrip() 854 ) 855 try: 856 required = ast.literal_eval(req_text) 857 except Exception as e: 858 warn( 859 f"Unable to determine requirements for plugin '{self.name}' " 860 + "without importing the module.\n" 861 + " This may be due to dynamically setting the global `required` list.\n" 862 + f" {e}" 863 ) 864 return [] 865 return required 866 867 import inspect 868 self.activate_venv(dependencies=False, debug=debug) 869 required = [] 870 for name, val in inspect.getmembers(self.module): 871 if name == 'required': 872 required = val 873 break 874 self._required = required 875 self.deactivate_venv(dependencies=False, debug=debug) 876 return required
If the Plugin has specified dependencies in a list called required, return the list.
NOTE: Dependecies which start with 'plugin:' are Meerschaum plugins, not pip packages.
Meerschaum plugins may also specify connector keys for a repo after '@'.
Parameters
- debug (bool, default False): Verbosity toggle.
Returns
- A list of required packages and plugins (str).
879 def get_required_plugins(self, debug: bool=False) -> List[mrsm.plugins.Plugin]: 880 """ 881 Return a list of required Plugin objects. 882 """ 883 from meerschaum.utils.warnings import warn 884 from meerschaum.config import get_config 885 from meerschaum._internal.static import STATIC_CONFIG 886 from meerschaum.connectors.parse import is_valid_connector_keys 887 plugins = [] 888 _deps = self.get_dependencies(debug=debug) 889 sep = STATIC_CONFIG['plugins']['repo_separator'] 890 plugin_names = [ 891 _d[len('plugin:'):] for _d in _deps 892 if _d.startswith('plugin:') and len(_d) > len('plugin:') 893 ] 894 default_repo_keys = get_config('meerschaum', 'repository') 895 skipped_repo_keys = set() 896 897 for _plugin_name in plugin_names: 898 if sep in _plugin_name: 899 try: 900 _plugin_name, _repo_keys = _plugin_name.split(sep) 901 except Exception: 902 _repo_keys = default_repo_keys 903 warn( 904 f"Invalid repo keys for required plugin '{_plugin_name}'.\n " 905 + f"Will try to use '{_repo_keys}' instead.", 906 stack = False, 907 ) 908 else: 909 _repo_keys = default_repo_keys 910 911 if _repo_keys in skipped_repo_keys: 912 continue 913 914 if not is_valid_connector_keys(_repo_keys): 915 warn( 916 f"Invalid connector '{_repo_keys}'.\n" 917 f" Skipping required plugins from repository '{_repo_keys}'", 918 stack=False, 919 ) 920 continue 921 922 plugins.append(Plugin(_plugin_name, repo=_repo_keys)) 923 924 return plugins
Return a list of required Plugin objects.
927 def get_required_packages(self, debug: bool=False) -> List[str]: 928 """ 929 Return the required package names (excluding plugins). 930 """ 931 _deps = self.get_dependencies(debug=debug) 932 return [_d for _d in _deps if not _d.startswith('plugin:')]
Return the required package names (excluding plugins).
935 def activate_venv( 936 self, 937 dependencies: bool = True, 938 init_if_not_exists: bool = True, 939 debug: bool = False, 940 **kw 941 ) -> bool: 942 """ 943 Activate the virtual environments for the plugin and its dependencies. 944 945 Parameters 946 ---------- 947 dependencies: bool, default True 948 If `True`, activate the virtual environments for required plugins. 949 950 Returns 951 ------- 952 A bool indicating success. 953 """ 954 import meerschaum.config.paths as paths 955 from meerschaum.config._paths import _TEAM_SOURCE_NAMESPACE 956 from meerschaum.utils.venv import venv_target_path 957 from meerschaum.utils.packages import activate_venv 958 from meerschaum.utils.misc import make_symlink, is_symlink 959 960 if dependencies: 961 for plugin in self.get_required_plugins(debug=debug): 962 plugin.activate_venv(debug=debug, init_if_not_exists=init_if_not_exists, **kw) 963 964 if _TEAM_SOURCE_NAMESPACE is not None and self.name in _TEAM_SOURCE_NAMESPACE['names']: 965 # A freshly granted Team source can import from its sealed view before it has 966 # a private environment. Let normal activation handle any existing environment. 967 try: 968 (paths.VIRTENV_RESOURCES_PATH / self.name).lstat() 969 except FileNotFoundError: 970 return False 971 972 vtp = venv_target_path(self.name, debug=debug, allow_nonexistent=True) 973 venv_meerschaum_path = vtp / 'meerschaum' 974 975 try: 976 success, msg = True, "Success" 977 if is_symlink(venv_meerschaum_path): 978 if pathlib.Path(os.path.realpath(venv_meerschaum_path)) != paths.PACKAGE_ROOT_PATH: 979 venv_meerschaum_path.unlink() 980 success, msg = make_symlink(venv_meerschaum_path, paths.PACKAGE_ROOT_PATH) 981 except Exception as e: 982 success, msg = False, str(e) 983 if not success: 984 warn( 985 f"Unable to create symlink {venv_meerschaum_path} to {paths.PACKAGE_ROOT_PATH}:\n" 986 f"{msg}" 987 ) 988 989 return activate_venv(self.name, init_if_not_exists=init_if_not_exists, debug=debug, **kw)
Activate the virtual environments for the plugin and its dependencies.
Parameters
- dependencies (bool, default True):
If
True, activate the virtual environments for required plugins.
Returns
- A bool indicating success.
992 def deactivate_venv(self, dependencies: bool=True, debug: bool = False, **kw) -> bool: 993 """ 994 Deactivate the virtual environments for the plugin and its dependencies. 995 996 Parameters 997 ---------- 998 dependencies: bool, default True 999 If `True`, deactivate the virtual environments for required plugins. 1000 1001 Returns 1002 ------- 1003 A bool indicating success. 1004 """ 1005 from meerschaum.utils.packages import deactivate_venv 1006 success = deactivate_venv(self.name, debug=debug, **kw) 1007 if dependencies: 1008 for plugin in self.get_required_plugins(debug=debug): 1009 plugin.deactivate_venv(debug=debug, **kw) 1010 return success
Deactivate the virtual environments for the plugin and its dependencies.
Parameters
- dependencies (bool, default True):
If
True, deactivate the virtual environments for required plugins.
Returns
- A bool indicating success.
1013 def install_dependencies( 1014 self, 1015 force: bool = False, 1016 debug: bool = False, 1017 ) -> bool: 1018 """ 1019 If specified, install dependencies. 1020 1021 **NOTE:** Dependencies that start with `'plugin:'` will be installed as 1022 Meerschaum plugins from the same repository as this Plugin. 1023 To install from a different repository, add the repo keys after `'@'` 1024 (e.g. `'plugin:foo@api:bar'`). 1025 1026 Parameters 1027 ---------- 1028 force: bool, default False 1029 If `True`, continue with the installation, even if some 1030 required packages fail to install. 1031 1032 debug: bool, default False 1033 Verbosity toggle. 1034 1035 Returns 1036 ------- 1037 A bool indicating success. 1038 """ 1039 from meerschaum.utils.packages import pip_install, venv_contains_package 1040 from meerschaum.utils.warnings import warn, info 1041 _deps = self.get_dependencies(debug=debug) 1042 if not _deps and self.requirements_file_path is None: 1043 return True 1044 1045 plugins = self.get_required_plugins(debug=debug) 1046 for _plugin in plugins: 1047 if _plugin.name == self.name: 1048 warn(f"Plugin '{self.name}' cannot depend on itself! Skipping...", stack=False) 1049 continue 1050 _success, _msg = _plugin.repo_connector.install_plugin( 1051 _plugin.name, debug=debug, force=force 1052 ) 1053 if not _success: 1054 warn( 1055 f"Failed to install required plugin '{_plugin}' from '{_plugin.repo_connector}'" 1056 + f" for plugin '{self.name}':\n" + _msg, 1057 stack = False, 1058 ) 1059 if not force: 1060 warn( 1061 "Try installing with the `--force` flag to continue anyway.", 1062 stack = False, 1063 ) 1064 return False 1065 info( 1066 "Continuing with installation despite the failure " 1067 + "(careful, things might be broken!)...", 1068 icon = False 1069 ) 1070 1071 1072 ### First step: parse `requirements.txt` if it exists. 1073 if self.requirements_file_path is not None: 1074 if not pip_install( 1075 requirements_file_path=self.requirements_file_path, 1076 venv=self.name, debug=debug 1077 ): 1078 warn( 1079 f"Failed to resolve 'requirements.txt' for plugin '{self.name}'.", 1080 stack = False, 1081 ) 1082 if not force: 1083 warn( 1084 "Try installing with `--force` to continue anyway.", 1085 stack = False, 1086 ) 1087 return False 1088 info( 1089 "Continuing with installation despite the failure " 1090 + "(careful, things might be broken!)...", 1091 icon = False 1092 ) 1093 1094 1095 ### Don't reinstall packages that are already included in required plugins. 1096 packages = [] 1097 _packages = self.get_required_packages(debug=debug) 1098 accounted_for_packages = set() 1099 for package_name in _packages: 1100 for plugin in plugins: 1101 if venv_contains_package(package_name, plugin.name): 1102 accounted_for_packages.add(package_name) 1103 break 1104 packages = [pkg for pkg in _packages if pkg not in accounted_for_packages] 1105 1106 ### Attempt pip packages installation. 1107 if packages: 1108 for package in packages: 1109 if not pip_install(package, venv=self.name, debug=debug): 1110 warn( 1111 f"Failed to install required package '{package}'" 1112 + f" for plugin '{self.name}'.", 1113 stack = False, 1114 ) 1115 if not force: 1116 warn( 1117 "Try installing with `--force` to continue anyway.", 1118 stack = False, 1119 ) 1120 return False 1121 info( 1122 "Continuing with installation despite the failure " 1123 + "(careful, things might be broken!)...", 1124 icon = False 1125 ) 1126 return True
If specified, install dependencies.
NOTE: Dependencies that start with 'plugin:' will be installed as
Meerschaum plugins from the same repository as this Plugin.
To install from a different repository, add the repo keys after '@'
(e.g. 'plugin:foo@api:bar').
Parameters
- force (bool, default False):
If
True, continue with the installation, even if some required packages fail to install. - debug (bool, default False): Verbosity toggle.
Returns
- A bool indicating success.
1129 @property 1130 def full_name(self) -> str: 1131 """ 1132 Include the repo keys with the plugin's name. 1133 """ 1134 from meerschaum._internal.static import STATIC_CONFIG 1135 sep = STATIC_CONFIG['plugins']['repo_separator'] 1136 return self.name + sep + str(self.repo_connector)
Include the repo keys with the plugin's name.
177def make_action( 178 function: Union[Callable[[Any], Any], str, None] = None, 179 shell: bool = False, 180 activate: bool = True, 181 deactivate: bool = True, 182 debug: bool = False, 183 daemon: bool = True, 184 skip_if_loaded: bool = True, 185 name: Optional[str] = None, 186 _plugin_name: Optional[str] = None, 187) -> Callable[[Any], Any]: 188 """ 189 Make a function a Meerschaum action. Useful for plugins that are adding multiple actions. 190 191 Parameters 192 ---------- 193 function: Callable[[Any], Any] 194 The function to become a Meerschaum action. Must accept all keyword arguments. 195 196 shell: bool, default False 197 Not used. 198 199 daemon: bool, default True 200 If `False`, the action may not be detached with `-d`. 201 202 name: Optional[str], default None 203 The words that run the action, e.g. `'weather wait'` for `mrsm weather wait` (and 204 `mrsm weather wait other words`, which arrive as `action=['other', 'words']`). 205 Defaults to the function's name, where an underscore separates words: `def weather_wait` 206 also runs as `mrsm weather wait`. `@make_action('weather wait')` is the same as 207 `@make_action(name='weather wait')`. 208 209 Returns 210 ------- 211 Another function (this is a decorator function). 212 213 Examples 214 -------- 215 >>> from meerschaum.plugins import make_action 216 >>> 217 >>> @make_action 218 ... def my_action(**kw): 219 ... print('foo') 220 ... return True, "Success" 221 >>> 222 >>> @make_action(name='weather wait') 223 ... def wait_for_counts(action=None, **kw): 224 ... return True, f"Waited for {action}." 225 >>> 226 """ 227 if isinstance(function, str): 228 name, function = function, None 229 words = _action_name_words(name) if name is not None else None 230 231 def _decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: 232 from meerschaum.actions import actions, _custom_actions_plugins, _plugins_actions 233 action_key = '_'.join(words) if words else func.__name__ 234 plugin_name = _plugin_name or _get_parent_plugin(function=func) 235 236 if skip_if_loaded and action_key in actions: 237 existing = actions[action_key] 238 same_function = existing is func or getattr(existing, '__wrapped__', None) is func 239 if words and not same_function and _custom_actions_plugins.get(action_key) != plugin_name: 240 from meerschaum.utils.warnings import warn 241 warn( 242 f"The action '{' '.join(words)}' already exists; " 243 f"plugin '{plugin_name}' does not replace it.", 244 stack=False, 245 ) 246 return func 247 248 plugin = Plugin(plugin_name) if plugin_name else None 249 250 if debug: 251 from meerschaum.utils.debug import dprint 252 dprint( 253 f"Adding action '{action_key}' from plugin " 254 f"'{plugin}'..." 255 ) 256 257 registered = func if action_key == func.__name__ else _named_action(func, action_key) 258 actions[action_key] = registered 259 _custom_actions_plugins[action_key] = plugin_name 260 if plugin_name not in _plugins_actions: 261 _plugins_actions[plugin_name] = [] 262 _plugins_actions[plugin_name].append(action_key) 263 _action_words[action_key] = list(words) if words else [ 264 word for word in action_key.split('_') if word 265 ] or [action_key] 266 if not daemon: 267 _actions_daemon_enabled[action_key] = False 268 return func 269 270 if function is None: 271 return _decorator 272 return _decorator(function)
Make a function a Meerschaum action. Useful for plugins that are adding multiple actions.
Parameters
- function (Callable[[Any], Any]): The function to become a Meerschaum action. Must accept all keyword arguments.
- shell (bool, default False): Not used.
- daemon (bool, default True):
If
False, the action may not be detached with-d. - name (Optional[str], default None):
The words that run the action, e.g.
'weather wait'formrsm weather wait(andmrsm weather wait other words, which arrive asaction=['other', 'words']). Defaults to the function's name, where an underscore separates words:def weather_waitalso runs asmrsm weather wait.@make_action('weather wait')is the same as@make_action(name='weather wait').
Returns
- Another function (this is a decorator function).
Examples
>>> from meerschaum.plugins import make_action
>>>
>>> @make_action
... def my_action(**kw):
... print('foo')
... return True, "Success"
>>>
>>> @make_action(name='weather wait')
... def wait_for_counts(action=None, **kw):
... return True, f"Waited for {action}."
>>>
914def api_plugin(function: Callable[[Any], Any]) -> Callable[[Any], Any]: 915 """ 916 Execute the function when initializing the Meerschaum API module. 917 Useful for lazy-loading heavy plugins only when the API is started, 918 such as when editing the `meerschaum.api.app` FastAPI app. 919 920 The FastAPI app will be passed as the only parameter. 921 922 Examples 923 -------- 924 >>> from meerschaum.plugins import api_plugin 925 >>> 926 >>> @api_plugin 927 >>> def initialize_plugin(app): 928 ... @app.get('/my/new/path') 929 ... def new_path(): 930 ... return {'message': 'It works!'} 931 >>> 932 """ 933 with _locks['_api_plugins']: 934 try: 935 plugin_name = _get_parent_plugin(function=function) 936 if plugin_name not in _api_plugins: 937 _api_plugins[plugin_name] = [] 938 _api_plugins[plugin_name].append(function) 939 except Exception as e: 940 from meerschaum.utils.warnings import warn 941 warn(e) 942 return function
Execute the function when initializing the Meerschaum API module.
Useful for lazy-loading heavy plugins only when the API is started,
such as when editing the meerschaum.api.app FastAPI app.
The FastAPI app will be passed as the only parameter.
Examples
>>> from meerschaum.plugins import api_plugin
>>>
>>> @api_plugin
>>> def initialize_plugin(app):
... @app.get('/my/new/path')
... def new_path():
... return {'message': 'It works!'}
>>>
739def dash_plugin( 740 function: Optional[Callable[[Any], Any]] = None, 741 *, 742 public: bool = False, 743) -> Callable[[Any], Any]: 744 """ 745 Execute the function when starting the Dash application (the web console), with the console's 746 `dash_app` as its argument: register your callbacks in it with `@dash_app.callback(...)`. 747 748 Parameters 749 ---------- 750 public: bool, default False 751 Every callback the function registers runs without a console session. By default a 752 callback answers only signed-in visitors (`api:dash:callbacks_require_session`); make 753 callbacks public only for pages anyone may use (`@web_page(login_required=False)`), and 754 use `@web_callback(..., public=True)` to choose callbacks one at a time. 755 756 Examples 757 -------- 758 >>> from meerschaum.plugins import dash_plugin 759 >>> 760 >>> @dash_plugin(public=True) 761 ... def init_dash(dash_app): 762 ... from dash import Input, Output 763 ... @dash_app.callback(Output('greeting', 'children'), Input('name', 'value')) 764 ... def greet(name): 765 ... return f"Hello, {name}!" 766 """ 767 def _decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: 768 registered = func 769 if public: 770 @functools.wraps(func) 771 def _public_dash_plugin(dash_app, *args, **kwargs): 772 with _registering_public_callbacks(dash_app): 773 return func(dash_app, *args, **kwargs) 774 registered = _public_dash_plugin 775 776 with _locks['_dash_plugins']: 777 plugin_name = _get_parent_plugin(function=func) 778 try: 779 if plugin_name not in _dash_plugins: 780 _dash_plugins[plugin_name] = [] 781 _dash_plugins[plugin_name].append(registered) 782 except Exception as e: 783 from meerschaum.utils.warnings import warn 784 warn(e) 785 return func 786 787 if function is not None: 788 if not callable(function): 789 raise TypeError("`@dash_plugin` decorates a function.") 790 return _decorator(function) 791 return _decorator
Execute the function when starting the Dash application (the web console), with the console's
dash_app as its argument: register your callbacks in it with @dash_app.callback(...).
Parameters
- public (bool, default False):
Every callback the function registers runs without a console session. By default a
callback answers only signed-in visitors (
api:dash:callbacks_require_session); make callbacks public only for pages anyone may use (@web_page(login_required=False)), and use@web_callback(..., public=True)to choose callbacks one at a time.
Examples
>>> from meerschaum.plugins import dash_plugin
>>>
>>> @dash_plugin(public=True)
... def init_dash(dash_app):
... from dash import Input, Output
... @dash_app.callback(Output('greeting', 'children'), Input('name', 'value'))
... def greet(name):
... return f"Hello, {name}!"
497def web_page( 498 page: Union[str, None, Callable[[Any], Any]] = None, 499 login_required: bool = True, 500 skip_navbar: bool = False, 501 page_group: Optional[str] = None, 502 dark_theme: Optional[bool] = None, 503 theme: Optional[str] = None, 504 head: Optional[List[Any]] = None, 505 **kwargs 506) -> Any: 507 """ 508 Quickly add pages to the dash application. 509 510 Parameters 511 ---------- 512 page: Union[str, None, Callable[[Any], Any]], default None 513 The page's path in the console (`'foo/bar'` is served at `/dash/foo/bar`; sub-paths 514 such as `/dash/foo/bar/1` route to it too). Defaults to the function's name. 515 516 login_required: bool, default True 517 If `True`, visitors without a console session see the login page instead. 518 A public page (`login_required=False`) runs its callbacks for anonymous visitors only if 519 they are public too: register them with `@web_callback(..., public=True)` or inside a 520 `@dash_plugin(public=True)` function. 521 522 skip_navbar: bool, default False 523 If `True`, the console's navigation bar is not added above the page. 524 525 navbar: bool, default False 526 If `True`, the page gets the console's top navigation (its pages, the instance selector 527 and the user menu). By default a plugin's page keeps its own layout under a plain bar 528 (the logo, a link to the Overview, and Sign out). 529 530 page_group: Optional[str], default None 531 The group the page is listed under (defaults to the plugin's name). 532 533 dark_theme: Optional[bool], default None 534 Whether the `dbc_dark` component overrides apply to this page. By default they do for the 535 console's dark theme and do not for `theme='light'` or a custom stylesheet. 536 `dark_theme=False` without a `theme` gives the light theme, as before. 537 538 theme: Optional[str], default None 539 The Bootstrap theme of this page: `'dark'` (the console's theme, the default), `'light'`, 540 or the URL of a Bootstrap stylesheet (for example `dash_bootstrap_components.themes.LUX`, 541 or a file you serve with `meerschaum.api.mount_static`). Exactly one theme stylesheet 542 applies while the page is open, and the console's theme returns on other pages. 543 544 head: Optional[List[Any]], default None 545 Tags to add to the page's `<head>` while it is open: HTML strings, dictionaries 546 (`{'tag': 'link', 'rel': 'stylesheet', 'href': '...'}`) or Dash components 547 (`html.Script(src='...')`). Stylesheets and meta tags apply only while the page is open; 548 a script runs once, the first time the page opens. `add_head()` adds tags to every page. 549 550 Examples 551 -------- 552 >>> import meerschaum as mrsm 553 >>> from meerschaum.plugins import web_page 554 >>> html = mrsm.attempt_import('dash.html') 555 >>> 556 >>> @web_page('foo/bar', login_required=False) 557 >>> def foo_bar(): 558 ... return html.Div([html.H1("Hello, World!")]) 559 >>> 560 >>> @web_page('reports', theme='light', head=['<meta name="robots" content="noindex">']) 561 >>> def reports(): 562 ... return html.Div([html.H1("Reports")]) 563 >>> 564 """ 565 page_str = None 566 theme_kind, theme_url = _normalize_theme(theme) 567 if theme_kind in ('dark', 'light'): 568 if dark_theme is not None and dark_theme != (theme_kind == 'dark'): 569 from meerschaum.utils.warnings import warn 570 warn( 571 f"`@web_page(theme={theme!r}, dark_theme={dark_theme})`: " 572 f"the {theme_kind} theme applies.", 573 stack=False, 574 ) 575 resolved_dark = theme_kind == 'dark' 576 elif theme_kind == 'url': 577 resolved_dark = bool(dark_theme) if dark_theme is not None else False 578 else: 579 resolved_dark = True if dark_theme is None else bool(dark_theme) 580 resolved_theme = theme_url if theme_kind == 'url' else ('dark' if resolved_dark else 'light') 581 head_tags = _head_tags_html(head) 582 583 def _decorator(_func: Callable[[Any], Any]) -> Callable[[Any], Any]: 584 nonlocal page_str, page_group 585 586 @functools.wraps(_func) 587 def wrapper(*_args, **_kwargs): 588 return _func(*_args, **_kwargs) 589 590 if page_str is None: 591 page_str = _func.__name__ 592 593 page_str = page_str.lstrip('/').rstrip('/').strip() 594 if not page_str.startswith('dash'): 595 page_str = f'/dash/{page_str}' 596 page_key = ( 597 ' '.join( 598 [ 599 word.capitalize() 600 for word in ( 601 page_str.replace('/dash', '').lstrip('/').rstrip('/').strip() 602 .replace('-', ' ').replace('_', ' ').split(' ') 603 ) 604 ] 605 ) 606 ) 607 608 plugin_name = _get_parent_plugin(function=_func) 609 page_group = page_group or plugin_name 610 if page_group not in _plugin_endpoints_to_pages: 611 _plugin_endpoints_to_pages[page_group] = {} 612 _plugin_endpoints_to_pages[page_group][page_str] = { 613 'function': _func, 614 'login_required': login_required, 615 'skip_navbar': skip_navbar, 616 ### The console's top navigation instead of the plain bar (`build_plugin_navbar`). 617 'navbar': bool(kwargs.get('navbar', False)), 618 'page_key': page_key, 619 'dark_theme': resolved_dark, 620 'theme': resolved_theme, 621 'head': list(head_tags), 622 } 623 if plugin_name not in _plugins_web_pages: 624 _plugins_web_pages[plugin_name] = [] 625 _plugins_web_pages[plugin_name].append(_func) 626 return wrapper 627 628 if callable(page): 629 decorator_to_return = _decorator(page) 630 page_str = page.__name__ 631 else: 632 decorator_to_return = _decorator 633 page_str = page 634 635 return decorator_to_return
Quickly add pages to the dash application.
Parameters
- page (Union[str, None, Callable[[Any], Any]], default None):
The page's path in the console (
'foo/bar'is served at/dash/foo/bar; sub-paths such as/dash/foo/bar/1route to it too). Defaults to the function's name. - login_required (bool, default True):
If
True, visitors without a console session see the login page instead. A public page (login_required=False) runs its callbacks for anonymous visitors only if they are public too: register them with@web_callback(..., public=True)or inside a@dash_plugin(public=True)function. - skip_navbar (bool, default False):
If
True, the console's navigation bar is not added above the page. - navbar (bool, default False):
If
True, the page gets the console's top navigation (its pages, the instance selector and the user menu). By default a plugin's page keeps its own layout under a plain bar (the logo, a link to the Overview, and Sign out). - page_group (Optional[str], default None): The group the page is listed under (defaults to the plugin's name).
- dark_theme (Optional[bool], default None):
Whether the
dbc_darkcomponent overrides apply to this page. By default they do for the console's dark theme and do not fortheme='light'or a custom stylesheet.dark_theme=Falsewithout athemegives the light theme, as before. - theme (Optional[str], default None):
The Bootstrap theme of this page:
'dark'(the console's theme, the default),'light', or the URL of a Bootstrap stylesheet (for exampledash_bootstrap_components.themes.LUX, or a file you serve withmeerschaum.api.mount_static). Exactly one theme stylesheet applies while the page is open, and the console's theme returns on other pages. - head (Optional[List[Any]], default None):
Tags to add to the page's
<head>while it is open: HTML strings, dictionaries ({'tag': 'link', 'rel': 'stylesheet', 'href': '...'}) or Dash components (html.Script(src='...')). Stylesheets and meta tags apply only while the page is open; a script runs once, the first time the page opens.add_head()adds tags to every page.
Examples
>>> import meerschaum as mrsm
>>> from meerschaum.plugins import web_page
>>> html = mrsm.attempt_import('dash.html')
>>>
>>> @web_page('foo/bar', login_required=False)
>>> def foo_bar():
... return html.Div([html.H1("Hello, World!")])
>>>
>>> @web_page('reports', theme='light', head=['<meta name="robots" content="noindex">'])
>>> def reports():
... return html.Div([html.H1("Reports")])
>>>
819def web_callback( 820 *args: Any, 821 public: bool = False, 822 output: Any = None, 823 inputs: Any = None, 824 state: Any = None, 825 **kwargs: Any 826) -> Callable[[Any], Any]: 827 """ 828 Register a Dash callback on the web console: `@web_callback(...)` takes what 829 `@dash_app.callback(...)` takes (outputs, inputs, states, `prevent_initial_call`, ...), 830 at the top level of your plugin, without a `@dash_plugin` function. 831 832 Parameters 833 ---------- 834 public: bool, default False 835 If `True`, the callback runs for visitors without a console session (for a page with 836 `@web_page(login_required=False)`). Otherwise the console answers it only for signed-in 837 visitors and sends the others to the login page. 838 839 output: Union[str, List[str], None], default None 840 The outputs as `'component-id.property'` strings (instead of `Output(...)` arguments), so 841 your plugin need not import Dash: it is imported when the console starts. 842 843 inputs: Union[str, List[str], None], default None 844 The inputs, likewise (`'my-button.n_clicks'`). 845 846 state: Union[str, List[str], None], default None 847 The states, likewise (`'session-store.data'`). 848 849 Examples 850 -------- 851 >>> from meerschaum.plugins import web_page, web_callback 852 >>> 853 >>> @web_callback(output='visits.children', inputs='visit-button.n_clicks', public=True) 854 ... def count_visits(n_clicks): 855 ... return f"{n_clicks or 0} visits" 856 >>> 857 >>> from dash import Input, Output 858 >>> @web_callback(Output('clock', 'children'), Input('tick', 'n_intervals')) 859 ... def clock(n_intervals): 860 ... return str(n_intervals) 861 """ 862 if ( 863 len(args) == 1 and not kwargs and output is None and inputs is None and state is None 864 and callable(args[0]) and not hasattr(args[0], 'component_id') 865 ): 866 raise TypeError( 867 "`@web_callback` takes the callback's outputs and inputs, e.g. " 868 "`@web_callback(output='out.children', inputs='button.n_clicks')`." 869 ) 870 871 def _arguments() -> Tuple[List[Any], Dict[str, Any]]: 872 """The positional and keyword arguments for `dash_app.callback` (Dash imported now).""" 873 dependencies = list(args) 874 flexible = dict(kwargs) 875 for kind, specs in (('output', output), ('inputs', inputs), ('state', state)): 876 if specs is None: 877 continue 878 if isinstance(specs, dict): 879 flexible[kind] = specs 880 continue 881 dependencies.extend(_dash_dependencies(kind, specs)) 882 return dependencies, flexible 883 884 def _decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: 885 if public: 886 _mark_public_callback(func) 887 dash_app = _built_dash_app() 888 if dash_app is not None: 889 dependencies, flexible = _arguments() 890 dash_app.callback(*dependencies, **flexible)(func) 891 return func 892 893 ### The console is built later (by the API host): register the callback then, as the 894 ### `@dash_plugin` functions are. 895 def _register(app): 896 dependencies, flexible = _arguments() 897 app.callback(*dependencies, **flexible)(func) 898 899 for attr in ('__module__', '__name__', '__qualname__', '__doc__'): 900 try: 901 setattr(_register, attr, getattr(func, attr)) 902 except (AttributeError, TypeError): 903 pass 904 with _locks['_dash_plugins']: 905 plugin_name = _get_parent_plugin(function=func) 906 if plugin_name not in _dash_plugins: 907 _dash_plugins[plugin_name] = [] 908 _dash_plugins[plugin_name].append(_register) 909 return func 910 911 return _decorator
Register a Dash callback on the web console: @web_callback(...) takes what
@dash_app.callback(...) takes (outputs, inputs, states, prevent_initial_call, ...),
at the top level of your plugin, without a @dash_plugin function.
Parameters
- public (bool, default False):
If
True, the callback runs for visitors without a console session (for a page with@web_page(login_required=False)). Otherwise the console answers it only for signed-in visitors and sends the others to the login page. - output (Union[str, List[str], None], default None):
The outputs as
'component-id.property'strings (instead ofOutput(...)arguments), so your plugin need not import Dash: it is imported when the console starts. - inputs (Union[str, List[str], None], default None):
The inputs, likewise (
'my-button.n_clicks'). - state (Union[str, List[str], None], default None):
The states, likewise (
'session-store.data').
Examples
>>> from meerschaum.plugins import web_page, web_callback
>>>
>>> @web_callback(output='visits.children', inputs='visit-button.n_clicks', public=True)
... def count_visits(n_clicks):
... return f"{n_clicks or 0} visits"
>>>
>>> from dash import Input, Output
>>> @web_callback(Output('clock', 'children'), Input('tick', 'n_intervals'))
... def clock(n_intervals):
... return str(n_intervals)
458def add_head(*tags: Any) -> None: 459 """ 460 Add tags to the `<head>` of every page of the web console (and of the documents of 461 page-contract pages): meta tags, stylesheets, scripts, fonts, a web app manifest... 462 463 Each tag is an HTML string, a dictionary (`{'tag': 'meta', 'name': 'theme-color', 464 'content': '#222'}`; the text of a `script` or `style` goes under `children`) or a Dash 465 component (`html.Link(rel='stylesheet', href='...')`). Call it at the top level of your plugin 466 (it applies when the console starts); `@web_page(head=[...])` adds tags to one page only. 467 468 Examples 469 -------- 470 >>> from meerschaum.plugins import add_head 471 >>> add_head( 472 ... '<meta name="theme-color" content="#222222">', 473 ... {'tag': 'link', 'rel': 'preconnect', 'href': 'https://fonts.gstatic.com'}, 474 ... ) 475 """ 476 rendered = _head_tags_html(list(tags)) 477 if not rendered: 478 return 479 plugin_name = _get_parent_plugin() 480 with _locks['_console_head']: 481 existing = _console_head.setdefault(plugin_name, []) 482 for tag in rendered: 483 if tag not in existing: 484 existing.append(tag)
Add tags to the <head> of every page of the web console (and of the documents of
page-contract pages): meta tags, stylesheets, scripts, fonts, a web app manifest...
Each tag is an HTML string, a dictionary ({'tag': 'meta', 'name': 'theme-color',
'content': '#222'}; the text of a script or style goes under children) or a Dash
component (html.Link(rel='stylesheet', href='...')). Call it at the top level of your plugin
(it applies when the console starts); @web_page(head=[...]) adds tags to one page only.
Examples
>>> from meerschaum.plugins import add_head
>>> add_head(
... '<meta name="theme-color" content="#222222">',
... {'tag': 'link', 'rel': 'preconnect', 'href': 'https://fonts.gstatic.com'},
... )
1115def import_plugins( 1116 *plugins_to_import: Union[str, List[str], None], 1117 warn: bool = True, 1118) -> Union[ 1119 'ModuleType', Tuple['ModuleType', None] 1120]: 1121 """ 1122 Import the Meerschaum plugins directory. 1123 1124 Parameters 1125 ---------- 1126 plugins_to_import: Union[str, List[str], None] 1127 If provided, only import the specified plugins. 1128 Otherwise import the entire plugins module. May be a string, list, or `None`. 1129 Defaults to `None`. 1130 1131 warn: bool, default True 1132 Print import errors. A named plugin's error is also available on `Plugin.import_error`. 1133 1134 Returns 1135 ------- 1136 A module of list of modules, depening on the number of plugins provided. 1137 1138 """ 1139 import sys 1140 import importlib 1141 import meerschaum.config._paths as native_paths 1142 import meerschaum.config.paths as paths 1143 from meerschaum.utils.misc import flatten_list 1144 from meerschaum.utils.venv import ( 1145 is_venv_active, activate_venv, deactivate_venv, Venv, ensure_default_venvs, 1146 ) 1147 from meerschaum.utils.warnings import warn as _warn 1148 plugins_to_import = list(plugins_to_import) 1149 ### PARITY: v4 had already activated the shared 'mrsm' venv (`attempt_import`) before the first 1150 ### plugin was imported, so plugin code with its own `required` venv still saw it. 1151 ensure_default_venvs() 1152 prepended_sys_path = False 1153 with _locks['sys.path']: 1154 1155 ### Since plugins may depend on other plugins, 1156 ### we need to activate the virtual environments for library plugins. 1157 ### This logic exists in `Plugin.activate_venv()`, 1158 ### but that code requires the plugin's module to already be imported. 1159 ### It's not a guarantee of correct activation order, 1160 ### e.g. if a library plugin pins a specific package and another 1161 plugins_names = get_plugins_names() 1162 already_active_venvs = { 1163 plugin_name 1164 for plugin_name in plugins_names 1165 if is_venv_active(plugin_name) 1166 } 1167 1168 if not sys.path or sys.path[0] != str(paths.PLUGINS_RESOURCES_PATH.parent): 1169 prepended_sys_path = True 1170 sys.path.insert(0, str(paths.PLUGINS_RESOURCES_PATH.parent)) 1171 1172 if not plugins_to_import: 1173 # The launcher creates an empty package for these sources. Its individual 1174 # plugins activate their own dependencies when they are imported. 1175 package_venvs = plugins_names if native_paths._TEAM_SOURCE_NAMESPACE is None else () 1176 for plugin_name in package_venvs: 1177 activate_venv(plugin_name) 1178 try: 1179 with plugin_import_guard(): 1180 imported_plugins = importlib.import_module(paths.PLUGINS_RESOURCES_PATH.stem) 1181 except ImportError as e: 1182 if warn: 1183 _warn(f"Failed to import the plugins module:\n {e}") 1184 import traceback 1185 traceback.print_exc() 1186 imported_plugins = None 1187 for plugin_name in package_venvs: 1188 if plugin_name in already_active_venvs: 1189 continue 1190 deactivate_venv(plugin_name) 1191 1192 else: 1193 imported_plugins = [] 1194 for plugin_name in flatten_list(plugins_to_import): 1195 plugin = Plugin(plugin_name) 1196 try: 1197 with Venv(plugin, init_if_not_exists=False), plugin_import_guard(): 1198 imported_plugins.append( 1199 importlib.import_module( 1200 f'{paths.PLUGINS_RESOURCES_PATH.stem}.{plugin_name}' 1201 ) 1202 ) 1203 _ = _plugins_import_errors.pop(plugin_name, None) 1204 except Exception as e: 1205 _plugins_import_errors[plugin_name] = e 1206 imported_plugins.append(None) 1207 if not warn: 1208 continue 1209 native_team_source = native_paths._TEAM_SOURCE_NAMESPACE is not None 1210 _warn( 1211 f"Failed to import plugin '{plugin_name}':\n " 1212 + f"{e}\n\nHere's a stacktrace:", 1213 stack = False, 1214 color = not native_team_source, 1215 ) 1216 if native_team_source: 1217 # Reporting a failed import does not need any additional packages. 1218 import traceback 1219 traceback.print_exc() 1220 else: 1221 from meerschaum.utils.formatting import print_exception 1222 print_exception( 1223 suppress = [ 1224 'meerschaum/plugins/__init__.py', 1225 importlib, 1226 importlib._bootstrap, 1227 ] 1228 ) 1229 1230 if imported_plugins is None and warn: 1231 _warn("Failed to import plugins.", stacklevel=3) 1232 1233 if prepended_sys_path and str(paths.PLUGINS_RESOURCES_PATH.parent) in sys.path: 1234 sys.path.remove(str(paths.PLUGINS_RESOURCES_PATH.parent)) 1235 1236 if isinstance(imported_plugins, list): 1237 return (imported_plugins[0] if len(imported_plugins) == 1 else tuple(imported_plugins)) 1238 return imported_plugins
Import the Meerschaum plugins directory.
Parameters
- plugins_to_import (Union[str, List[str], None]):
If provided, only import the specified plugins.
Otherwise import the entire plugins module. May be a string, list, or
None. Defaults toNone. - warn (bool, default True):
Print import errors. A named plugin's error is also available on
Plugin.import_error.
Returns
- A module of list of modules, depening on the number of plugins provided.
1241def from_plugin_import(plugin_import_name: str, *attrs: str) -> Any: 1242 """ 1243 Emulate the `from module import x` behavior. 1244 1245 Parameters 1246 ---------- 1247 plugin_import_name: str 1248 The import name of the plugin's module. 1249 Separate submodules with '.' (e.g. 'compose.utils.pipes') 1250 1251 attrs: str 1252 Names of the attributes to return. 1253 1254 Returns 1255 ------- 1256 Objects from a plugin's submodule. 1257 If multiple objects are provided, return a tuple. 1258 1259 Examples 1260 -------- 1261 >>> init = from_plugin_import('compose.utils', 'init') 1262 >>> with mrsm.Venv('compose'): 1263 ... cf = init() 1264 >>> build_parent_pipe, get_defined_pipes = from_plugin_import( 1265 ... 'compose.utils.pipes', 1266 ... 'build_parent_pipe', 1267 ... 'get_defined_pipes', 1268 ... ) 1269 >>> parent_pipe = build_parent_pipe(cf) 1270 >>> defined_pipes = get_defined_pipes(cf) 1271 """ 1272 import importlib 1273 from meerschaum.utils.warnings import warn as _warn 1274 if plugin_import_name.startswith('plugins.'): 1275 plugin_import_name = plugin_import_name[len('plugins.'):] 1276 plugin_import_parts = plugin_import_name.split('.') 1277 plugin_root_name = plugin_import_parts[0] 1278 1279 plugins_package_name = _get_plugins_package_name() 1280 submodule_import_name = '.'.join([plugins_package_name] + plugin_import_parts) 1281 if len(attrs) == 0: 1282 raise ValueError(f"Provide which attributes to return from '{submodule_import_name}'.") 1283 1284 def _get_attrs(module) -> Any: 1285 attrs_to_return = [] 1286 for attr in attrs: 1287 try: 1288 attrs_to_return.append(getattr(module, attr)) 1289 except Exception: 1290 _warn(f"Failed to access '{attr}' from '{submodule_import_name}'.") 1291 attrs_to_return.append(None) 1292 return attrs_to_return[0] if len(attrs_to_return) == 1 else tuple(attrs_to_return) 1293 1294 first_party_submodule = _import_first_party_plugin(plugin_import_name) 1295 if first_party_submodule is not None: 1296 attrs_to_return = [getattr(first_party_submodule, attr) for attr in attrs] 1297 return attrs_to_return[0] if len(attrs_to_return) == 1 else tuple(attrs_to_return) 1298 1299 ### Skip building the plugin and activating its venv when the submodule is already imported. 1300 loaded_submodule = _get_loaded_module(submodule_import_name) 1301 if ( 1302 loaded_submodule is not None 1303 and _get_loaded_module(f'{plugins_package_name}.{plugin_root_name}') is not None 1304 ): 1305 return _get_attrs(loaded_submodule) 1306 1307 plugin = mrsm.Plugin(plugin_root_name) 1308 with mrsm.Venv(plugin): 1309 if plugin.module is None: 1310 raise ImportError(f"Unable to import plugin '{plugin}'.") 1311 1312 try: 1313 with plugin_import_guard(): 1314 submodule = importlib.import_module(submodule_import_name) 1315 except ImportError as e: 1316 _warn( 1317 f"Failed to import plugin '{submodule_import_name}':\n " 1318 + f"{e}\n\nHere's a stacktrace:", 1319 stack=False, 1320 ) 1321 from meerschaum.utils.formatting import print_exception 1322 print_exception( 1323 suppress=[ 1324 'meerschaum/plugins/__init__.py', 1325 importlib, 1326 importlib._bootstrap, 1327 ] 1328 ) 1329 ### Return one `None` per attribute so tuple unpacking still works. 1330 return None if len(attrs) == 1 else (None,) * len(attrs) 1331 1332 return _get_attrs(submodule)
Emulate the from module import x behavior.
Parameters
- plugin_import_name (str): The import name of the plugin's module. Separate submodules with '.' (e.g. 'compose.utils.pipes')
- attrs (str): Names of the attributes to return.
Returns
- Objects from a plugin's submodule.
- If multiple objects are provided, return a tuple.
Examples
>>> init = from_plugin_import('compose.utils', 'init')
>>> with mrsm.Venv('compose'):
... cf = init()
>>> build_parent_pipe, get_defined_pipes = from_plugin_import(
... 'compose.utils.pipes',
... 'build_parent_pipe',
... 'get_defined_pipes',
... )
>>> parent_pipe = build_parent_pipe(cf)
>>> defined_pipes = get_defined_pipes(cf)
1547def invalidate_plugins_cache() -> None: 1548 """ 1549 Pop the cached `plugins` package and its submodules from `sys.modules` 1550 and reset the loaded-plugins state. 1551 1552 The `plugins` package caches its `__path__` (the resolved 1553 `PLUGINS_RESOURCES_PATH`) at import time. When the active root or 1554 plugins-dir scope changes in-process (e.g. via 1555 `meerschaum.config.environment.replace_env`), that stale `__path__` 1556 makes subsequent plugin imports re-discover plugins under the previous 1557 scope's `.internal/plugins` directory. Call this whenever the plugins 1558 scope changes so the next import rebuilds against the current 1559 `PLUGINS_RESOURCES_PATH`. 1560 """ 1561 global _loaded_plugins, _synced_symlinks 1562 import sys 1563 import meerschaum.config.paths as paths 1564 1565 plugins_stem = paths.PLUGINS_RESOURCES_PATH.stem 1566 module_prefix = plugins_stem + '.' 1567 for mod_name in [ 1568 mod_name 1569 for mod_name in sys.modules 1570 if mod_name == plugins_stem or mod_name.startswith(module_prefix) 1571 ]: 1572 _ = sys.modules.pop(mod_name, None) 1573 1574 _loaded_plugins = False 1575 ### Also reset the symlinks counter — it's per-scope state, and leaving it 1576 ### >1 makes `sync_plugins_symlinks` skip creating the new scope's 1577 ### `.internal/plugins` (so `plugins` imports as an empty namespace package). 1578 _synced_symlinks = 0
Pop the cached plugins package and its submodules from sys.modules
and reset the loaded-plugins state.
The plugins package caches its __path__ (the resolved
PLUGINS_RESOURCES_PATH) at import time. When the active root or
plugins-dir scope changes in-process (e.g. via
meerschaum.config.environment.replace_env), that stale __path__
makes subsequent plugin imports re-discover plugins under the previous
scope's .internal/plugins directory. Call this whenever the plugins
scope changes so the next import rebuilds against the current
PLUGINS_RESOURCES_PATH.
1581def reload_plugins(plugins: Optional[List[str]] = None, debug: bool = False) -> None: 1582 """ 1583 Reload plugins back into memory. 1584 1585 Parameters 1586 ---------- 1587 plugins: Optional[List[str]], default None 1588 The plugins to reload. `None` will reload all plugins. 1589 1590 """ 1591 global _synced_symlinks 1592 unload_plugins(plugins, debug=debug) 1593 _synced_symlinks = 0 1594 sync_plugins_symlinks(debug=debug) 1595 load_plugins(skip_if_loaded=False, debug=debug)
Reload plugins back into memory.
Parameters
- plugins (Optional[List[str]], default None):
The plugins to reload.
Nonewill reload all plugins.
1598def get_plugins(*to_load, try_import: bool = True) -> Union[Tuple[Plugin], Plugin]: 1599 """ 1600 Return a list of `Plugin` objects. 1601 1602 Parameters 1603 ---------- 1604 to_load: 1605 If specified, only load specific plugins. 1606 Otherwise return all plugins. 1607 1608 try_import: bool, default True 1609 If `True`, allow for plugins to be imported. 1610 """ 1611 import meerschaum.config.paths as paths 1612 import os 1613 sync_plugins_symlinks() 1614 sandboxed_names = sandboxed_plugins_names() 1615 if to_load: 1616 names = list(to_load) 1617 elif sandboxed_names is not None: 1618 names = sandboxed_names 1619 else: 1620 names = [ 1621 ( 1622 name if (paths.PLUGINS_RESOURCES_PATH / name).is_dir() 1623 else name[:-3] 1624 ) 1625 for name in os.listdir(paths.PLUGINS_RESOURCES_PATH) 1626 if name != '__init__.py' 1627 ] 1628 _plugins = [Plugin(name) for name in names] 1629 plugins = tuple(plugin for plugin in _plugins if plugin.is_installed(try_import=try_import)) 1630 if len(to_load) == 1: 1631 if len(plugins) == 0: 1632 raise ValueError(f"Plugin '{to_load[0]}' is not installed.") 1633 return plugins[0] 1634 return plugins
Return a list of Plugin objects.
Parameters
- to_load:: If specified, only load specific plugins. Otherwise return all plugins.
- try_import (bool, default True):
If
True, allow for plugins to be imported.
1686def get_data_plugins() -> List[Plugin]: 1687 """ 1688 Only return the modules of plugins with either `fetch()` or `sync()` functions. 1689 """ 1690 import inspect 1691 plugins = get_plugins() 1692 1693 ### ponytail: cache on the installed plugins' names. 1694 ### Accessing `plugin.module` re-enters `import_plugins()` (venv activation + 1695 ### a nested `get_plugins()`) for every plugin, so an uncached call costs 1696 ### hundreds of milliseconds. The shell completer calls this on every keystroke 1697 ### (via `get_connector_labels()`), which is what made typing `-c` laggy. 1698 ### Installing or removing a plugin changes the key, so the cache self-invalidates; 1699 ### editing a plugin in place requires a restart to pick up a new `fetch()`/`sync()`. 1700 cache_key = tuple(plugin.name for plugin in plugins) 1701 if cache_key in _data_plugins_cache: 1702 return _data_plugins_cache[cache_key] 1703 1704 data_names = {'sync', 'fetch'} 1705 data_plugins = [] 1706 for plugin in plugins: 1707 if plugin.module is None: 1708 continue 1709 for name, ob in list(vars(plugin.module).items()): 1710 if not inspect.isfunction(ob): 1711 continue 1712 if name not in data_names: 1713 continue 1714 data_plugins.append(plugin) 1715 1716 _data_plugins_cache[cache_key] = data_plugins 1717 return data_plugins
Only return the modules of plugins with either fetch() or sync() functions.
1720def add_plugin_argument(*args, **kwargs) -> None: 1721 """ 1722 Add argparse arguments under the 'Plugins options' group. 1723 Takes the same parameters as the regular argparse `add_argument()` function. 1724 1725 Examples 1726 -------- 1727 >>> add_plugin_argument('--foo', type=int, help="This is my help text!") 1728 >>> 1729 """ 1730 from meerschaum._internal.arguments._parser import groups, _seen_plugin_args, parser 1731 from meerschaum.utils.warnings import warn 1732 _parent_plugin_name = _get_parent_plugin() 1733 title = f"Plugin '{_parent_plugin_name}' options" if _parent_plugin_name else 'Custom options' 1734 group_key = 'plugin_' + (_parent_plugin_name or '') 1735 if group_key not in groups: 1736 groups[group_key] = parser.add_argument_group( 1737 title = title, 1738 ) 1739 _seen_plugin_args[group_key] = set() 1740 try: 1741 if str(args) not in _seen_plugin_args[group_key]: 1742 groups[group_key].add_argument(*args, **kwargs) 1743 _seen_plugin_args[group_key].add(str(args)) 1744 except Exception as e: 1745 warn(e)
Add argparse arguments under the 'Plugins options' group.
Takes the same parameters as the regular argparse add_argument() function.
Examples
>>> add_plugin_argument('--foo', type=int, help="This is my help text!")
>>>
275def pre_sync_hook( 276 function: Callable[[Any], Any], 277) -> Callable[[Any], Any]: 278 """ 279 Register a function as a sync hook to be executed right before sync. 280 281 Parameters 282 ---------- 283 function: Callable[[Any], Any] 284 The function to execute right before a sync. 285 286 Returns 287 ------- 288 Another function (this is a decorator function). 289 290 Examples 291 -------- 292 >>> from meerschaum.plugins import pre_sync_hook 293 >>> 294 >>> @pre_sync_hook 295 ... def log_sync(pipe, **kwargs): 296 ... print(f"About to sync {pipe} with kwargs:\n{kwargs}.") 297 >>> 298 """ 299 with _locks['_pre_sync_hooks']: 300 plugin_name = _get_parent_plugin(function=function) 301 try: 302 if plugin_name not in _pre_sync_hooks: 303 _pre_sync_hooks[plugin_name] = [] 304 _pre_sync_hooks[plugin_name].append(function) 305 except Exception as e: 306 from meerschaum.utils.warnings import warn 307 warn(e) 308 return function
Register a function as a sync hook to be executed right before sync.
Parameters
----------
function: Callable[[Any], Any]
The function to execute right before a sync.
Returns
-------
Another function (this is a decorator function).
Examples
--------
>>> from meerschaum.plugins import pre_sync_hook
>>>
>>> @pre_sync_hook
... def log_sync(pipe, **kwargs):
... print(f"About to sync {pipe} with kwargs:
{kwargs}.")
>
311def post_sync_hook( 312 function: Callable[[Any], Any], 313) -> Callable[[Any], Any]: 314 """ 315 Register a function as a sync hook to be executed upon completion of a sync. 316 317 Parameters 318 ---------- 319 function: Callable[[Any], Any] 320 The function to execute upon completion of a sync. 321 322 Returns 323 ------- 324 Another function (this is a decorator function). 325 326 Examples 327 -------- 328 >>> from meerschaum.plugins import post_sync_hook 329 >>> from meerschaum.utils.misc import interval_str 330 >>> from datetime import timedelta 331 >>> 332 >>> @post_sync_hook 333 ... def log_sync(pipe, success_tuple, duration=None, **kwargs): 334 ... duration_delta = timedelta(seconds=duration) 335 ... duration_text = interval_str(duration_delta) 336 ... print(f"It took {duration_text} to sync {pipe}.") 337 >>> 338 """ 339 with _locks['_post_sync_hooks']: 340 try: 341 plugin_name = _get_parent_plugin(function=function) 342 if plugin_name not in _post_sync_hooks: 343 _post_sync_hooks[plugin_name] = [] 344 _post_sync_hooks[plugin_name].append(function) 345 except Exception as e: 346 from meerschaum.utils.warnings import warn 347 warn(e) 348 return function
Register a function as a sync hook to be executed upon completion of a sync.
Parameters
- function (Callable[[Any], Any]): The function to execute upon completion of a sync.
Returns
- Another function (this is a decorator function).
Examples
>>> from meerschaum.plugins import post_sync_hook
>>> from meerschaum.utils.misc import interval_str
>>> from datetime import timedelta
>>>
>>> @post_sync_hook
... def log_sync(pipe, success_tuple, duration=None, **kwargs):
... duration_delta = timedelta(seconds=duration)
... duration_text = interval_str(duration_delta)
... print(f"It took {duration_text} to sync {pipe}.")
>>>
78def figure( 79 fig: Union[Dict[str, Any], str, Any], 80 id: Optional[str] = None, 81 aria_label: Optional[str] = None, 82) -> str: 83 """ 84 Embed a Plotly figure in a page-contract HTML fragment. 85 86 Parameters 87 ---------- 88 fig: Union[Dict[str, Any], str, plotly.graph_objects.Figure] 89 The figure (see `figure_json()`). 90 91 id: Optional[str], default None 92 An optional element ID, so the page can target the chart with HTMX. 93 94 aria_label: Optional[str], default None 95 An optional accessible name for the chart. 96 97 Returns 98 ------- 99 A string like `<div data-mrsm-figure="{...figure JSON...}"></div>`, with the JSON 100 attribute-escaped. The console reads the attribute back as the same JSON that 101 `figure_json(fig)` returns. 102 103 Examples 104 -------- 105 >>> import plotly.graph_objects as go 106 >>> from meerschaum.plugins import figure, web_page 107 >>> 108 >>> @web_page('counts', login_required=True, page_group='Acme') 109 >>> def counts_page(): 110 ... fig = go.Figure(go.Bar(x=['a', 'b'], y=[1, 2])) 111 ... return f"<section><h2>Counts</h2>{figure(fig)}</section>" 112 """ 113 attributes = [] 114 if id is not None: 115 attributes.append(f' id="{html.escape(str(id), quote=True)}"') 116 if aria_label is not None: 117 attributes.append(f' role="img" aria-label="{html.escape(str(aria_label), quote=True)}"') 118 escaped = html.escape(figure_json(fig), quote=True) 119 return f'<div{"".join(attributes)} data-mrsm-figure="{escaped}"></div>'
Embed a Plotly figure in a page-contract HTML fragment.
Parameters
- fig (Union[Dict[str, Any], str, plotly.graph_objects.Figure]):
The figure (see
figure_json()). - id (Optional[str], default None): An optional element ID, so the page can target the chart with HTMX.
- aria_label (Optional[str], default None): An optional accessible name for the chart.
Returns
- A string like
<div data-mrsm-figure="{...figure JSON...}"></div>, with the JSON - attribute-escaped. The console reads the attribute back as the same JSON that
figure_json(fig)returns.
Examples
>>> import plotly.graph_objects as go
>>> from meerschaum.plugins import figure, web_page
>>>
>>> @web_page('counts', login_required=True, page_group='Acme')
>>> def counts_page():
... fig = go.Figure(go.Bar(x=['a', 'b'], y=[1, 2]))
... return f"<section><h2>Counts</h2>{figure(fig)}</section>"
24def figure_json(fig: Union[Dict[str, Any], str, Any]) -> str: 25 """ 26 Return the compact Plotly figure JSON for `fig`. 27 28 Parameters 29 ---------- 30 fig: Union[Dict[str, Any], str, plotly.graph_objects.Figure] 31 A `plotly.py` figure (anything with `to_json()` or `to_plotly_json()`), 32 a figure `dict` (`{'data': [...], 'layout': {...}}`) or an already serialized JSON string. 33 34 Returns 35 ------- 36 A JSON string with no insignificant whitespace, `{"data":[...],"layout":{...}}`. 37 Key order is the order the figure produced, so the same figure always serializes to the same 38 bytes. 39 """ 40 if isinstance(fig, str): 41 document = json.loads(fig) 42 elif hasattr(fig, 'to_json'): 43 document = json.loads(fig.to_json()) 44 elif hasattr(fig, 'to_plotly_json'): 45 document = fig.to_plotly_json() 46 elif isinstance(fig, dict): 47 document = fig 48 else: 49 raise TypeError( 50 "A figure must be a plotly.py figure, a dict or a JSON string, " 51 f"not '{type(fig).__name__}'." 52 ) 53 54 if not isinstance(document, dict): 55 raise ValueError("A Plotly figure is a JSON object with `data` and `layout`.") 56 57 encoder = _get_encoder() 58 return json.dumps( 59 document, 60 separators=(',', ':'), 61 cls=encoder, 62 allow_nan=False if encoder is None else True, 63 )
Return the compact Plotly figure JSON for fig.
Parameters
- fig (Union[Dict[str, Any], str, plotly.graph_objects.Figure]):
A
plotly.pyfigure (anything withto_json()orto_plotly_json()), a figuredict({'data': [...], 'layout': {...}}) or an already serialized JSON string.
Returns
**A JSON string with no insignificant whitespace,
{"data":[...],"layout"** ({...}}.):Key order is the order the figure produced, so the same figure always serializes to the same
- bytes.