Skip to content

resource_manager

Resource manager for shared multiprocessing synchronization primitives.

This module provides a ResourceManager class and multiprocessing manager integration for sharing locks, events, queues, and other synchronization objects across processes.

ResourceManager

Thread-safe resource manager with weak reference tracking.

Manages named resources by class, creating them on demand and automatically cleaning up when no longer referenced.

Example
import threading

from py_misc_utils import resource_manager as rm

m = rm.ResourceManager()
lk = m.get('LOCKS', threading.Lock, 'job1')

print(lk.acquire())  # True
lk.release()

m.delete('LOCKS', 'job1')
print(m.get('LOCKS', threading.Lock, 'job1') is lk)  # False
Source code in py_misc_utils/resource_manager.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class ResourceManager:
  """Thread-safe resource manager with weak reference tracking.

  Manages named resources by class, creating them on demand and
  automatically cleaning up when no longer referenced.

  Example:
    import threading

    from py_misc_utils import resource_manager as rm

    m = rm.ResourceManager()
    lk = m.get('LOCKS', threading.Lock, 'job1')

    print(lk.acquire())  # True
    lk.release()

    m.delete('LOCKS', 'job1')
    print(m.get('LOCKS', threading.Lock, 'job1') is lk)  # False
  """

  def __init__(self):
    """Initialize an empty resource manager."""
    self._lock = threading.Lock()
    self._resources = collections.defaultdict(dict)

  def get(self, cls, ctor, name, *args, **kwargs):
    """Get or create a named resource.

    Args:
      cls: Resource class/category name (e.g., 'LOCKS', 'EVENTS').
      ctor: Callable to create the resource if needed.
      name: Resource name.
      *args: Positional arguments passed to ctor.
      **kwargs: Keyword arguments passed to ctor.

    Returns:
      The resource instance (existing or newly created).

    Example:
      import threading

      from py_misc_utils import resource_manager as rm

      m = rm.ResourceManager()
      lk = m.get('LOCKS', threading.Lock, 'job1')

      print(type(lk).__name__)  # lock
    """
    alog.debug(f'Get resource {cls}.{name}')
    with self._lock:
      cdict = self._resources[cls]
      res = cdict.get(name)
      if res is not None:
        res = res()
      if res is None:
        alog.debug(f'Creating resource {cls}.{name}')
        res = ctor(*args, **kwargs)
        cdict[name] = weakref.ref(res)

      return res

  def delete(self, cls, name):
    """Remove a named resource from the manager.

    Args:
      cls: Resource class/category name.
      name: Resource name to remove.

    Example:
      import threading

      from py_misc_utils import resource_manager as rm

      m = rm.ResourceManager()
      lk = m.get('LOCKS', threading.Lock, 'job2')

      m.delete('LOCKS', 'job2')
      print(m.get('LOCKS', threading.Lock, 'job2') is lk)  # False
    """
    alog.debug(f'Remove resource {cls}.{name}')
    with self._lock:
      cdict = self._resources[cls]
      cdict.pop(name, None)

get(cls, ctor, name, *args, **kwargs)

Get or create a named resource.

Parameters:

Name Type Description Default
cls

Resource class/category name (e.g., 'LOCKS', 'EVENTS').

required
ctor

Callable to create the resource if needed.

required
name

Resource name.

required
*args

Positional arguments passed to ctor.

()
**kwargs

Keyword arguments passed to ctor.

{}

Returns:

Type Description

The resource instance (existing or newly created).

Example
import threading

from py_misc_utils import resource_manager as rm

m = rm.ResourceManager()
lk = m.get('LOCKS', threading.Lock, 'job1')

print(type(lk).__name__)  # lock
Source code in py_misc_utils/resource_manager.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def get(self, cls, ctor, name, *args, **kwargs):
  """Get or create a named resource.

  Args:
    cls: Resource class/category name (e.g., 'LOCKS', 'EVENTS').
    ctor: Callable to create the resource if needed.
    name: Resource name.
    *args: Positional arguments passed to ctor.
    **kwargs: Keyword arguments passed to ctor.

  Returns:
    The resource instance (existing or newly created).

  Example:
    import threading

    from py_misc_utils import resource_manager as rm

    m = rm.ResourceManager()
    lk = m.get('LOCKS', threading.Lock, 'job1')

    print(type(lk).__name__)  # lock
  """
  alog.debug(f'Get resource {cls}.{name}')
  with self._lock:
    cdict = self._resources[cls]
    res = cdict.get(name)
    if res is not None:
      res = res()
    if res is None:
      alog.debug(f'Creating resource {cls}.{name}')
      res = ctor(*args, **kwargs)
      cdict[name] = weakref.ref(res)

    return res

delete(cls, name)

Remove a named resource from the manager.

Parameters:

Name Type Description Default
cls

Resource class/category name.

required
name

Resource name to remove.

required
Example
import threading

from py_misc_utils import resource_manager as rm

m = rm.ResourceManager()
lk = m.get('LOCKS', threading.Lock, 'job2')

m.delete('LOCKS', 'job2')
print(m.get('LOCKS', threading.Lock, 'job2') is lk)  # False
Source code in py_misc_utils/resource_manager.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def delete(self, cls, name):
  """Remove a named resource from the manager.

  Args:
    cls: Resource class/category name.
    name: Resource name to remove.

  Example:
    import threading

    from py_misc_utils import resource_manager as rm

    m = rm.ResourceManager()
    lk = m.get('LOCKS', threading.Lock, 'job2')

    m.delete('LOCKS', 'job2')
    print(m.get('LOCKS', threading.Lock, 'job2') is lk)  # False
  """
  alog.debug(f'Remove resource {cls}.{name}')
  with self._lock:
    cdict = self._resources[cls]
    cdict.pop(name, None)

get_resource_manager()

Get the global singleton resource manager.

Returns:

Type Description

The global ResourceManager instance.

Example
import threading

from py_misc_utils import resource_manager as rm

resmgr = rm.get_resource_manager()
lk = resmgr.get('LOCKS', threading.Lock, 'shared')

print(type(lk).__name__)  # lock
Source code in py_misc_utils/resource_manager.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def get_resource_manager():
  """Get the global singleton resource manager.

  Returns:
    The global ResourceManager instance.

  Example:
    import threading

    from py_misc_utils import resource_manager as rm

    resmgr = rm.get_resource_manager()
    lk = resmgr.get('LOCKS', threading.Lock, 'shared')

    print(type(lk).__name__)  # lock
  """
  return _RESMGR

crypt_object(obj, key)

Serialize and encrypt an object into an authenticated blob.

Parameters:

Name Type Description Default
obj

The object to serialize and encrypt.

required
key

The encryption key - bytes.

required

Returns:

Type Description

The nonce || ciphertext || tag blob.

Source code in py_misc_utils/resource_manager.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def crypt_object(obj, key):
  """Serialize and encrypt an object into an authenticated blob.

  Args:
    obj: The object to serialize and encrypt.
    key: The encryption key - bytes.

  Returns:
    The nonce || ciphertext || tag blob.
  """
  nonce = os.urandom(16)
  seed, mackey = _crypt_seed(key, nonce)
  pdata = pickle.dumps(obj)
  cdata = _crypt_xor(pdata, seed)
  tag = hmac.new(mackey, nonce + cdata, hashlib.sha256).digest()

  return nonce + cdata + tag

decrypt_object(blob, key)

Decrypt an authenticated blob back into the serialized object.

Parameters:

Name Type Description Default
blob

The nonce || ciphertext || tag blob to decrypt.

required
key

The decryption key - bytes.

required

Returns:

Type Description

The deserialized object, or None when the tag does not validate

(wrong key or corrupted blob).

Source code in py_misc_utils/resource_manager.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def decrypt_object(blob, key):
  """Decrypt an authenticated blob back into the serialized object.

  Args:
    blob: The nonce || ciphertext || tag blob to decrypt.
    key: The decryption key - bytes.

  Returns:
    The deserialized object, or None when the tag does not validate
    (wrong key or corrupted blob).
  """
  if len(blob) < 16 + 32:
    return None

  nonce, cdata, tag = blob[:16], blob[16:-32], blob[-32:]
  seed, mackey = _crypt_seed(key, nonce)
  xtag = hmac.new(mackey, nonce + cdata, hashlib.sha256).digest()
  if not hmac.compare_digest(tag, xtag):
    return None

  return pickle.loads(_crypt_xor(cdata, seed))

get_status_dirs(name)

Get the status directories of a resource manager server.

Parameters:

Name Type Description Default
name

Server name to look up.

required

Returns:

Type Description

The list of the status directory paths - possibly stale ones - of

the resource manager server.

Source code in py_misc_utils/resource_manager.py
329
330
331
332
333
334
335
336
337
338
339
def get_status_dirs(name):
  """Get the status directories of a resource manager server.

  Args:
    name: Server name to look up.

  Returns:
    The list of the status directory paths - possibly stale ones - of
    the resource manager server.
  """
  return glob.glob(_status_glob(name))

get_manager(name, *args, authkey=None, address=None, **kwargs)

Start or connect to a resource manager server.

Starts a daemon process running the server if not already running, then connects to it - reading the server address, published by the daemon through its encrypted status directory, when not provided.

Parameters:

Name Type Description Default
name

Server name (used for daemon identification and logging).

required
*args

Positional arguments for _create_manager.

()
authkey

The shared authentication key of the server - generated when None. Callers attaching to an already running server must pass the same authkey the starting caller used.

None
address

An optional address to connect to. When None the address is discovered from the server status directory.

None
**kwargs

Keyword arguments for _create_manager.

{}

Returns:

Type Description

Connected SyncManager instance.

Source code in py_misc_utils/resource_manager.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def get_manager(name, *args, authkey=None, address=None, **kwargs):
  """Start or connect to a resource manager server.

  Starts a daemon process running the server if not already running,
  then connects to it - reading the server address, published by the
  daemon through its encrypted status directory, when not provided.

  Args:
    name: Server name (used for daemon identification and logging).
    *args: Positional arguments for _create_manager.
    authkey: The shared authentication key of the server - generated
      when None. Callers attaching to an already running server must
      pass the same authkey the starting caller used.
    address: An optional address to connect to. When None the address
      is discovered from the server status directory.
    **kwargs: Keyword arguments for _create_manager.

  Returns:
    Connected SyncManager instance.
  """
  if authkey is None:
    authkey = os.urandom(32)

  if address is None:
    daemon = dp.Daemon(name)
    key = _crypt_key(authkey, name)
    deadline = time.monotonic() + _RESMGR_STATUS_DEADLINE
    while True:
      # Restart the daemon each round: its death - and its status write -
      # is re-evaluated every poll cycle.
      if daemon.getpid() is None:
        alog.info(f'[{name}] Starting server daemon')
        try:
          daemon.start(
              functools.partial(_server_runner, name, *args, authkey=authkey, **kwargs))
        except FileExistsError:
          pass

      status = _read_status(name, key)
      if isinstance(status, dict):
        break
      if status == errno.ENODATA:
        # Status files exist but none decrypts under the given key: the
        # daemon was started with a different authkey.
        alog.xraise(
            PermissionError, f'Unable to decrypt the "{name}" resource manager '
            'server status - wrong authkey?')

      if time.monotonic() > deadline:
        alog.xraise(ConnectionError, f'Unable to get the "{name}" resource manager '
                    'server status')

      time.sleep(_RESMGR_STATUS_POLL)

    address = status['address']
    if status['family'] == 'AF_INET':
      address = tuple(address)

    if not status['ok']:
      alog.xraise(
          ConnectionError, f'Unable to start the "{name}" resource manager '
          f'server: {status["error"]}')

  alog.info(f'[{name}] Connecting to {address!r}')

  manager = _create_manager(*args, authkey=authkey, address=address, **kwargs)
  manager.connect()

  alog.info(f'[{name}] Connected to the manager')

  return manager

stop_manager(name)

Stop a resource manager server daemon.

Parameters:

Name Type Description Default
name

Server name to stop.

required

Returns:

Type Description

True if daemon was stopped, False otherwise.

Example
from py_misc_utils import resource_manager as rm

rm.stop_manager('my-resmgr')
Source code in py_misc_utils/resource_manager.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def stop_manager(name):
  """Stop a resource manager server daemon.

  Args:
    name: Server name to stop.

  Returns:
    True if daemon was stopped, False otherwise.

  Example:
    from py_misc_utils import resource_manager as rm

    rm.stop_manager('my-resmgr')
  """
  xpid = dp.Daemon(name).stop()

  _remove_status(name)

  return xpid