meerschaum.connectors.parse
Utility functions for parsing connector keys.
1#! /usr/bin/env python 2# -*- coding: utf-8 -*- 3# vim:fenc=utf-8 4 5""" 6Utility functions for parsing connector keys. 7""" 8 9from __future__ import annotations 10 11import meerschaum as mrsm 12from meerschaum.utils.typing import Any, Union, Optional, Dict, Tuple 13 14 15def parse_connector_keys( 16 keys: str, 17 construct: bool = True, 18 as_tuple: bool = False, 19 **kw: Any 20) -> ( 21 Union[ 22 mrsm.connectors.Connector, 23 Dict[str, Any], 24 Tuple[ 25 Union[ 26 mrsm.connectors.Connector, 27 Dict[str, Any], 28 None, 29 ], 30 str 31 ], 32 None 33 ] 34): 35 """ 36 Convenience function for parsing connector keys and returning Connector objects. 37 38 Parameters 39 ---------- 40 keys: str 41 Keys are split by a colon (`':'`) into type and label. If the label is omitted, 42 (e.g. 'sql'), pass it along to `meerschaum.connectors.get_connector` to parse. 43 44 construct: bool, default True 45 If True, return a Connector. Otherwise return the configuration dictionary for a Connector. 46 **NOTE:** This may include passwords, so be careful. 47 48 as_tuple: bool, default False 49 If True, return a tuple of (conn, keys). `conn` may be a dict or connector. 50 51 Returns 52 ------- 53 A connector or dictionary of attributes. If `as_tuple`, also return the connector's keys. 54 55 """ 56 import copy 57 from meerschaum.connectors import get_connector 58 from meerschaum.config import get_config 59 from meerschaum._internal.static import STATIC_CONFIG 60 from meerschaum.utils.warnings import error 61 62 ### `get_connector()` handles the logic for falling back to 'main', 63 ### so don't make any decisions here. 64 vals = str(keys).split(':') 65 _type = vals[0] 66 _label = vals[1] if len(vals) > 1 else STATIC_CONFIG['connectors']['default_label'] 67 _get_connector_kw = {'type': _type, 'label': _label} 68 _get_connector_kw.update(kw) 69 70 if construct: 71 conn = get_connector(**_get_connector_kw, _warn_undefined=False) 72 if conn is None: 73 from meerschaum.connectors import _undefined_connector_message 74 attributes = {key: val for key, val in kw.items() if key != 'debug'} 75 undefined = _undefined_connector_message(_type, _label, attributes) 76 ### v4's sentence, then why (a connector defined nowhere). 77 message = f"Unable to parse connector keys '{keys}'" 78 error(f"{message}. {undefined}" if undefined else message, stack=False) 79 else: 80 connectors_config = get_config('meerschaum', 'connectors', patch=True) 81 ### invalid type 82 if vals[0] not in connectors_config: 83 return None 84 type_config = get_config('meerschaum', 'connectors', _type) 85 86 default_config = copy.deepcopy(type_config.get('default', {})) 87 conn = type_config.get(_label, None) 88 if default_config is not None and conn is not None: 89 default_config.update(conn) 90 conn = default_config 91 92 if as_tuple: 93 return conn, _type + ':' + _label 94 return conn 95 96 97def parse_instance_keys( 98 keys: Optional[str], 99 construct: bool = True, 100 as_tuple: bool = False, 101 **kw 102): 103 """ 104 Parse the Meerschaum instance value into a Connector object. 105 """ 106 from meerschaum.config import get_config 107 108 if keys is None: 109 keys = get_config('meerschaum', 'instance') 110 keys = str(keys) 111 112 return parse_connector_keys(keys, construct=construct, as_tuple=as_tuple, **kw) 113 114 115def parse_repo_keys(keys: Optional[str] = None, **kw): 116 """Parse the Meerschaum repository value into an APIConnector.""" 117 from meerschaum.config import get_config 118 if keys is None: 119 keys = get_config('meerschaum', 'repository', patch=True) 120 keys = str(keys) 121 if ':' not in keys: 122 keys = 'api:' + keys 123 124 if not keys.startswith('api:'): 125 raise ValueError("Only APIConnectors may be treated as repositories.") 126 127 return parse_connector_keys(keys, _load_plugins=kw.pop('_load_plugins', False), **kw) 128 129 130def parse_executor_keys(keys: Optional[str] = None, **kw): 131 """Parse the executor keys into an APIConnector, SystemdConnector, or string.""" 132 from meerschaum.jobs import get_executor_keys_from_context 133 if keys is None: 134 keys = get_executor_keys_from_context() 135 136 if keys is None or keys == 'local': 137 return 'local' 138 139 keys = str(keys) 140 return parse_connector_keys(keys, **kw) 141 142 143def is_valid_connector_keys( 144 keys: str 145) -> bool: 146 """ 147 Verify a connector_keys string references a valid connector. 148 """ 149 try: 150 success = parse_connector_keys(keys, construct=False) is not None 151 except Exception: 152 success = False 153 return success
def
parse_connector_keys( keys: str, construct: bool = True, as_tuple: bool = False, **kw: Any) -> meerschaum.Connector | Dict[str, Any] | Tuple[meerschaum.Connector | Dict[str, Any] | None, str] | None:
16def parse_connector_keys( 17 keys: str, 18 construct: bool = True, 19 as_tuple: bool = False, 20 **kw: Any 21) -> ( 22 Union[ 23 mrsm.connectors.Connector, 24 Dict[str, Any], 25 Tuple[ 26 Union[ 27 mrsm.connectors.Connector, 28 Dict[str, Any], 29 None, 30 ], 31 str 32 ], 33 None 34 ] 35): 36 """ 37 Convenience function for parsing connector keys and returning Connector objects. 38 39 Parameters 40 ---------- 41 keys: str 42 Keys are split by a colon (`':'`) into type and label. If the label is omitted, 43 (e.g. 'sql'), pass it along to `meerschaum.connectors.get_connector` to parse. 44 45 construct: bool, default True 46 If True, return a Connector. Otherwise return the configuration dictionary for a Connector. 47 **NOTE:** This may include passwords, so be careful. 48 49 as_tuple: bool, default False 50 If True, return a tuple of (conn, keys). `conn` may be a dict or connector. 51 52 Returns 53 ------- 54 A connector or dictionary of attributes. If `as_tuple`, also return the connector's keys. 55 56 """ 57 import copy 58 from meerschaum.connectors import get_connector 59 from meerschaum.config import get_config 60 from meerschaum._internal.static import STATIC_CONFIG 61 from meerschaum.utils.warnings import error 62 63 ### `get_connector()` handles the logic for falling back to 'main', 64 ### so don't make any decisions here. 65 vals = str(keys).split(':') 66 _type = vals[0] 67 _label = vals[1] if len(vals) > 1 else STATIC_CONFIG['connectors']['default_label'] 68 _get_connector_kw = {'type': _type, 'label': _label} 69 _get_connector_kw.update(kw) 70 71 if construct: 72 conn = get_connector(**_get_connector_kw, _warn_undefined=False) 73 if conn is None: 74 from meerschaum.connectors import _undefined_connector_message 75 attributes = {key: val for key, val in kw.items() if key != 'debug'} 76 undefined = _undefined_connector_message(_type, _label, attributes) 77 ### v4's sentence, then why (a connector defined nowhere). 78 message = f"Unable to parse connector keys '{keys}'" 79 error(f"{message}. {undefined}" if undefined else message, stack=False) 80 else: 81 connectors_config = get_config('meerschaum', 'connectors', patch=True) 82 ### invalid type 83 if vals[0] not in connectors_config: 84 return None 85 type_config = get_config('meerschaum', 'connectors', _type) 86 87 default_config = copy.deepcopy(type_config.get('default', {})) 88 conn = type_config.get(_label, None) 89 if default_config is not None and conn is not None: 90 default_config.update(conn) 91 conn = default_config 92 93 if as_tuple: 94 return conn, _type + ':' + _label 95 return conn
Convenience function for parsing connector keys and returning Connector objects.
Parameters
- keys (str):
Keys are split by a colon (
':') into type and label. If the label is omitted, (e.g. 'sql'), pass it along tomeerschaum.connectors.get_connectorto parse. - construct (bool, default True): If True, return a Connector. Otherwise return the configuration dictionary for a Connector. NOTE: This may include passwords, so be careful.
- as_tuple (bool, default False):
If True, return a tuple of (conn, keys).
connmay be a dict or connector.
Returns
- A connector or dictionary of attributes. If
as_tuple, also return the connector's keys.
def
parse_instance_keys( keys: str | None, construct: bool = True, as_tuple: bool = False, **kw):
98def parse_instance_keys( 99 keys: Optional[str], 100 construct: bool = True, 101 as_tuple: bool = False, 102 **kw 103): 104 """ 105 Parse the Meerschaum instance value into a Connector object. 106 """ 107 from meerschaum.config import get_config 108 109 if keys is None: 110 keys = get_config('meerschaum', 'instance') 111 keys = str(keys) 112 113 return parse_connector_keys(keys, construct=construct, as_tuple=as_tuple, **kw)
Parse the Meerschaum instance value into a Connector object.
def
parse_repo_keys(keys: str | None = None, **kw):
116def parse_repo_keys(keys: Optional[str] = None, **kw): 117 """Parse the Meerschaum repository value into an APIConnector.""" 118 from meerschaum.config import get_config 119 if keys is None: 120 keys = get_config('meerschaum', 'repository', patch=True) 121 keys = str(keys) 122 if ':' not in keys: 123 keys = 'api:' + keys 124 125 if not keys.startswith('api:'): 126 raise ValueError("Only APIConnectors may be treated as repositories.") 127 128 return parse_connector_keys(keys, _load_plugins=kw.pop('_load_plugins', False), **kw)
Parse the Meerschaum repository value into an APIConnector.
def
parse_executor_keys(keys: str | None = None, **kw):
131def parse_executor_keys(keys: Optional[str] = None, **kw): 132 """Parse the executor keys into an APIConnector, SystemdConnector, or string.""" 133 from meerschaum.jobs import get_executor_keys_from_context 134 if keys is None: 135 keys = get_executor_keys_from_context() 136 137 if keys is None or keys == 'local': 138 return 'local' 139 140 keys = str(keys) 141 return parse_connector_keys(keys, **kw)
Parse the executor keys into an APIConnector, SystemdConnector, or string.
def
is_valid_connector_keys(keys: str) -> bool:
144def is_valid_connector_keys( 145 keys: str 146) -> bool: 147 """ 148 Verify a connector_keys string references a valid connector. 149 """ 150 try: 151 success = parse_connector_keys(keys, construct=False) is not None 152 except Exception: 153 success = False 154 return success
Verify a connector_keys string references a valid connector.