cjnfuncs 2.3__tar.gz → 2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cjnfuncs
3
- Version: 2.3
3
+ Version: 2.4
4
4
  Summary: A collection of core functions for tool script writing
5
5
  Author-email: Chris Nelson <github@cjnaz.com>
6
6
  License: MIT License
@@ -75,6 +75,7 @@ Project repo: https://github.com/cjnaz/cjnfuncs
75
75
  <br/>
76
76
 
77
77
  ## Revision history
78
+ - 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
78
79
  - 2.3 240821 - Added mungePath ./ support.
79
80
  Resolved check_path_exists() memory leak.
80
81
  Added `same_process_ok` to resourcelock.getlock()
@@ -38,6 +38,7 @@ Project repo: https://github.com/cjnaz/cjnfuncs
38
38
  <br/>
39
39
 
40
40
  ## Revision history
41
+ - 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
41
42
  - 2.3 240821 - Added mungePath ./ support.
42
43
  Resolved check_path_exists() memory leak.
43
44
  Added `same_process_ok` to resourcelock.getlock()
@@ -1,11 +1,18 @@
1
1
  [build-system]
2
- requires = ["setuptools"] #, "setuptools-scm"]
2
+ requires = ["setuptools"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
 
6
6
  [project]
7
7
  name = "cjnfuncs"
8
- version = "2.3"
8
+ version = "2.4"
9
+ # 2.4 - release
10
+ # 2.4rc2 - check_path_exists() exception fix for unmounted network path (OSError: [Errno 19] No such device)
11
+ # 2.4rc1 - doc fix on setuplogging()
12
+ # 2.4b4 - resourcelock closed attribute
13
+ # 2.4b3 - Added lock_info to resource_lock
14
+ # 2.4b2 - Added where_called to resource_lock unget for debugging aid
15
+ # 2.4b1 - Added Twilio support to snd_notif
9
16
  description = "A collection of core functions for tool script writing"
10
17
  readme = "README.md"
11
18
  requires-python = ">=3.6" # Centos 7 uses 3.6.8
@@ -9,6 +9,9 @@
9
9
  #==========================================================
10
10
 
11
11
  import time
12
+ import sys
13
+ import importlib
14
+ import re
12
15
  import smtplib
13
16
  from email.mime.text import MIMEText
14
17
  from email.utils import formatdate
@@ -16,14 +19,17 @@ from pathlib import Path
16
19
  import dkim
17
20
 
18
21
  from .core import logging, SndEmailError
19
- from .mungePath import mungePath
22
+ from .mungePath import mungePath, check_path_exists
20
23
  from .timevalue import timevalue
21
24
  import cjnfuncs.core as core
22
25
 
23
26
  # Configs / Constants
24
- SND_EMAIL_NTRIES = 3 # Number of tries to send email before aborting
25
- RETRY_WAIT = '2s' # seconds between retries
26
- SERVER_TIMEOUT = '2s' # server connection timeout
27
+ SND_EMAIL_NTRIES = 3 # Number of tries to send email before aborting
28
+ RETRY_WAIT = '2s' # seconds between retries
29
+ SERVER_TIMEOUT = '2s' # server connection timeout
30
+
31
+ COUNTRY_CODE = 1 # US/Canada
32
+ PHONE_NUM_LENGTH = 10 # US/Canada
27
33
 
28
34
 
29
35
  #=====================================================================================
@@ -32,11 +38,11 @@ SERVER_TIMEOUT = '2s' # server connection timeout
32
38
  #=====================================================================================
33
39
  #=====================================================================================
34
40
 
35
- def snd_notif(subj='Notification message', msg='', to='NotifList', log=False, smtp_config=None):
41
+ def snd_notif(subj='Notification message', msg='', urls_list=[], to='NotifList', log=False, smtp_config=None):
36
42
  """
37
- ## snd_notif (subj='Notification message', msg=' ', to='NotifList', log=False, smtp_config=None) - Send a text message using info from the config file
43
+ ## snd_notif (subj='Notification message', msg='', urls_list=[], to='NotifList', log=False, smtp_config=None) - Send a text message using info from the config file
38
44
 
39
- Intended for use of your mobile provider's email-to-text bridge email address, eg,
45
+ Intended for use the mobile provider's (carrier's) email-to-SMS gateway email address, eg,
40
46
  `5405551212@vzwtxt.com` for Verizon, but any email address will work.
41
47
 
42
48
  The `to` string may be the name of a config param (who's value is one or more email addresses, default
@@ -52,9 +58,14 @@ Three attempts are made to send the message.
52
58
  - Text message subject field
53
59
  - Some SMS/MMS apps display the subj field in bold, some in raw form, and some not at all.
54
60
 
55
- `msg` (str, default ' ')
61
+ `msg` (str, default '')
56
62
  - Text message body
57
63
 
64
+ `urls_list` (list, default [])
65
+ - A list of url strings to be passed to the message sending plugin module, which should pass them to the messaging service.
66
+ - This list is discarded by `snd_notif()` if not using a messaging service. If you want to send a message with
67
+ urls then included them in the `msg` body text.
68
+
58
69
  `to` (str, default 'NotifList')
59
70
  - To whom to send the message. `to` may be either an explicit string list of email addresses
60
71
  (whitespace or comma separated) or a config param name (also listing one
@@ -71,17 +82,30 @@ The `subj` field is part of the log message.
71
82
  - config_item class instance containing the [SMTP] section and related params
72
83
 
73
84
 
74
- ### cfg dictionary params in the [SMTP] section, in addition to the cfg dictionary params required for snd_email
85
+ ### config dictionary params in the [SMTP] section, in addition to the config dictionary params required for snd_email
75
86
  `NotifList` (optional)
76
87
  - string list of email addresses (whitespace or comma separated).
77
88
  - Defining `NotifList` in the config is only required if any call to `snd_notif()` uses this
78
89
  default `to` parameter value.
79
90
 
80
91
  `DontNotif` (default False)
81
- - If True, notification messages are not sent. Useful for debug. All email and notification
82
- messages are also blocked if `DontEmail` is True.
92
+ - If True, notification messages are not sent. `log` is still honored. Useful for debug.
93
+ - Setting `DontEmail` True also blocks sending notification messages if using a carrier email-to-SMS gateway
94
+ (not using a messaging service). If using a messaging service then `DontEmail` has no effect.
83
95
 
96
+ `Msg_Handler` (str, absolute path or package.module, default None)
97
+ - If using a messaging service, such as Twilio, this param declares the path to the message sending plugin module.
98
+ - The module must implement a `sender()` function, which will be called with a `package` dictionary containing `subj`, `msg`, `urls`, and `to` key:value pairs, and
99
+ a reference to the `smtp_config`. See the [SMTP.md](https://github.com/cjnaz/cjnfuncs/blob/main/SMTP.md) for an example Msg_Handler module implementation.
100
+ - `Msg_Handler` may be a full absolute path to a Python module (eg, `/path-to-module/twilioSender.py`), or an installed package.module reference (eg, `mypackage.twilioSender`).
84
101
 
102
+ `country_code` (int or str, default 1 (US/Canada), required only if `Msg_Handler` is defined in the config [SMTP] section)
103
+ - Number without a preceding '+', eg '1' for US/Canada phone numbers
104
+ - If `get_type='numbers'` then each phone number is prepended with `+` plus `country_code` (eg, '+1'), but only if the number does not already have a country code.
105
+ - If a `to` phone number has a different country code, it is retained.
106
+
107
+ `number_length` (int, default 10 (US/Canada), required only if `Msg_Handler` is defined in the config [SMTP] section)
108
+ - The number of digits in a valid phone number (not including the country code), eg 10 for US/Canada phone numbers
85
109
 
86
110
 
87
111
  ### Returns
@@ -93,22 +117,54 @@ messages are also blocked if `DontEmail` is True.
93
117
  - `snd_notif()` uses `snd_email()` to send the message. See `snd_email()` for related setup.
94
118
  """
95
119
 
96
- if smtp_config.getcfg('DontNotif', fallback=False, section='SMTP') or smtp_config.getcfg('DontEmail', fallback=False, section='SMTP'):
120
+ if smtp_config.getcfg('DontNotif', fallback=False, section='SMTP'):
97
121
  if log:
98
122
  logging.warning (f"Notification NOT sent <{subj}> <{msg}>")
99
123
  else:
100
124
  logging.debug (f"Notification NOT sent <{subj}> <{msg}>")
101
125
  return
102
126
 
103
- try:
127
+ msg_handler = smtp_config.getcfg('Msg_Handler', fallback=None, section='SMTP')
128
+
129
+ if msg_handler:
130
+ # Import the messaging service handler
131
+ if msg_handler.startswith('/'): # Absolute path case
132
+ if not check_path_exists(msg_handler):
133
+ raise FileNotFoundError (f"Can't find SMS/MMS message handler <{msg_handler}>")
134
+ if msg_handler.endswith('.py'):
135
+ msg_handler = msg_handler[:-3]
136
+ xx = mungePath(msg_handler)
137
+ xx_parent = str(xx.parent)
138
+ if xx_parent not in sys.path:
139
+ sys.path.append(xx_parent)
140
+ try:
141
+ logging.info (xx)
142
+ sender_plugin = __import__(xx.name)
143
+ except Exception as e:
144
+ raise ImportError (f"Can't import SMS/MMS message handler <{msg_handler}>\n {e}")
145
+ logging.debug (f"Imported message sender plugin <{msg_handler}>, version <{sender_plugin.__version__}>")
146
+ else: # package.module case
147
+ try:
148
+ sender_plugin = importlib.import_module(msg_handler)
149
+ except Exception as e:
150
+ raise ImportError (f"Can't import SMS/MMS message handler <{msg_handler}>\n {e}")
151
+ logging.debug (f"Imported message sender plugin <{sender_plugin.__name__}>, version <{sender_plugin.__version__}>")
152
+
153
+ package = {'subj': subj,
154
+ 'msg': msg,
155
+ 'urls': urls_list,
156
+ 'to': list_to(to, 'numbers', subj=subj, smtp_config=smtp_config) }
157
+
158
+ sender_plugin.sender(package, smtp_config)
159
+
160
+ else:
104
161
  snd_email (subj=subj, body=msg, to=to, smtp_config=smtp_config)
105
- if log:
106
- logging.warning (f"Notification sent <{subj}> <{msg}>")
107
- else:
108
- logging.debug (f"Notification sent <{subj}> <{msg}>")
109
- except Exception as e:
110
- logging.warning (f"Notification send failed <{subj}> <{msg}>")
111
- raise e
162
+
163
+
164
+ if log:
165
+ logging.warning (f"Notification sent <{subj}> <{msg}>")
166
+ else:
167
+ logging.debug (f"Notification sent <{subj}> <{msg}>")
112
168
 
113
169
 
114
170
  #=====================================================================================
@@ -161,7 +217,7 @@ The `subj` field is part of the log message.
161
217
  - config_item class instance containing the [SMTP] section and related params
162
218
 
163
219
 
164
- ### cfg dictionary params in the [SMTP] section
220
+ ### config dictionary params in the [SMTP] section
165
221
  `EmailFrom`
166
222
  - An email address, such as `me@myserver.com`
167
223
 
@@ -260,27 +316,7 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
260
316
  m_text += f"\n(sent {time.asctime(time.localtime())})"
261
317
 
262
318
  # Deal with 'to'
263
- def extract_email_addresses(addresses):
264
- """Return list of email addresses from comma or whitespace separated string 'addresses'.
265
- """
266
- if ',' in addresses:
267
- tmp = addresses.split(',')
268
- addrs = []
269
- for addr in tmp:
270
- addrs.append(addr.strip())
271
- else:
272
- addrs = addresses.split()
273
- return addrs
274
-
275
- if '@' in to:
276
- To = extract_email_addresses(to)
277
- else:
278
- To = extract_email_addresses(smtp_config.getcfg(to, "", section='SMTP'))
279
- if len(To) == 0:
280
- raise SndEmailError (f"snd_email - Message subject <{subj}>: 'to' list must not be empty.")
281
- for address in To:
282
- if '@' not in address:
283
- raise SndEmailError (f"snd_email - Message subject <{subj}>: address in 'to' list is invalid: <{address}>.")
319
+ To = list_to(to, 'emails', subj, smtp_config=smtp_config)
284
320
 
285
321
  # Gather, check remaining config params
286
322
  ntries = smtp_config.getcfg('EmailNTries', SND_EMAIL_NTRIES, types=int, section='SMTP')
@@ -305,22 +341,23 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
305
341
  if not dkim_selector:
306
342
  raise SndEmailError (f"snd_email - Config <EmailDKIMSelector> is required for SMTP DKIM signing")
307
343
 
308
- if smtp_config.getcfg('DontEmail', fallback=False, types=bool, section='SMTP'):
309
- if log:
310
- logging.warning (f"Email NOT sent <{subj}>")
311
- else:
312
- logging.debug (f"Email NOT sent <{subj}>")
313
- return
314
-
315
-
316
344
  # Send the message, with retries
317
345
  for trynum in range(ntries):
318
346
  try:
319
347
  msg = MIMEText(m_text, msg_type)
320
348
  msg['Subject'] = subj
321
- msg['From'] = email_from
322
- msg['To'] = ", ".join(To)
323
- msg["Date"] = formatdate(localtime=True)
349
+ msg['From'] = email_from
350
+ msg['To'] = ", ".join(To)
351
+ msg["Date"] = formatdate(localtime=True)
352
+
353
+ # logging.debug (msg)
354
+
355
+ if smtp_config.getcfg('DontEmail', fallback=False, types=bool, section='SMTP'):
356
+ if log:
357
+ logging.warning (f"Email NOT sent <{subj}>")
358
+ else:
359
+ logging.debug (f"Email NOT sent <{subj}>")
360
+ return
324
361
 
325
362
  # Add DKIM signature if EmailDKIMDomain is specified
326
363
  if dkim_domain:
@@ -366,11 +403,100 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
366
403
 
367
404
  except Exception as e:
368
405
  last_error = e
369
- # if logging.getLogger().level == logging.DEBUG:
370
- # logging.exception(f"Email send try {trynum} failed:")
371
406
  if trynum < ntries -1:
372
407
  logging.debug(f"Email send try {trynum} failed. Retry in <{retry_wait} sec>:\n <{e}>")
373
408
  time.sleep(retry_wait)
374
409
  continue
375
410
 
376
411
  raise SndEmailError (f"snd_email: Send failed for <{subj}>:\n <{last_error}>")
412
+
413
+
414
+ #=====================================================================================
415
+ #=====================================================================================
416
+ # l i s t _ t o
417
+ #=====================================================================================
418
+ #=====================================================================================
419
+
420
+ def list_to(raw_in, get_type, subj, smtp_config):
421
+ """
422
+ ### list_to(raw_in, get_type, subj, smtp_config) - Build list of phone numbers or email addresses from raw_in
423
+
424
+ `list_to` handles several translations, controlled by `get_type` ('numbers' or 'emails'), including dereferencing through
425
+ config param, extracting and constructing a proper phone number list for messaging services (eg, Twilio), and constructing an
426
+ email address list.
427
+
428
+ ### Parameters
429
+ `raw_in` (str or int (in the case of a single phone number))
430
+ - A string list of phone numbers or email addresses, separated by either whitespace or ','
431
+ - If the value is the name of a param in the smtp_config [SMTP] section then that param's value is used, else `raw_in` is directly parsed
432
+ - Phone numbers may optionally include '+<country_code>', eg +14325551212
433
+
434
+ `get_type` (str)
435
+ - 'numbers' - a list of 1 or more phone numbers will be returned
436
+ - '+<country_code>', eg '+1' is prepended to each number, if not provided
437
+ - If the `raw_in` is one or more email-to-SMS gateway addresses (eg, 4805551212@vzwpix.com), then the local-part (the part before '@') is extracted as a phone number.
438
+ This feature enables a config parameter containing a list of carrier email-to-SMS gateway addresses to be directly used with a SMS/MMS messaging service such as Twilio.
439
+ - 'emails' - a list of 1 or more email addresses will be returned
440
+ - Address validity checking is minimal: Email addresses must contain an '@'.
441
+
442
+ `subj` (str)
443
+ - The notification or email subject field - used only for raised errors to aid debug tracing
444
+
445
+ `smtp_config` (config_item class instance)
446
+ - config_item class instance containing the [SMTP] section and related params
447
+
448
+
449
+ ### config dictionary params in the [SMTP] section
450
+ `country_code` (int or str, default 1 (US/Canada), required only if `get_type='numbers'`)
451
+ - Number without a preceding '+', eg '1' for US/Canada phone numbers
452
+ - If `get_type='numbers'` then each phone number is prepended with `+` plus `country_code` (eg, '+1'), but only if the number does not already have a country code.
453
+ - If a `raw_in` phone number has a different country code, it is retained.
454
+
455
+ `number_length` (int, default 10 (US/Canada), required only if `get_type= 'numbers'`)
456
+ - The number of digits in a valid phone number (not including the country code) for the given `country_code`, eg 10 for US/Canada phone numbers
457
+
458
+ ### Returns
459
+ - Either a list of phone numbers or a list of email addresses, eg:
460
+ - ['+14325551212']
461
+ - ['+14325551212', '+14802345678']
462
+ - ['4325551212@txt.att.net', '4802345678@vxwpix.com', 'myemail@tmomail.net']
463
+ - Raises SndEmailError on any errors
464
+ """
465
+
466
+ xx = smtp_config.getcfg(raw_in, fallback=None, section='SMTP')
467
+ if xx: # raw_in is a config-defined param (of 1 or more phone numbers)
468
+ raw_in = xx
469
+
470
+ items = re.split(r'[,\s]+', str(raw_in))
471
+ cc = None # Force load once per call
472
+ to_list = []
473
+
474
+ for item in items:
475
+ if get_type == 'numbers':
476
+ if not cc:
477
+ cc = '+' + str(smtp_config.getcfg('country_code', COUNTRY_CODE, section='SMTP')) # '+1'
478
+ num_len = smtp_config.getcfg('number_length', PHONE_NUM_LENGTH, section='SMTP') # 10
479
+ if '@' in item:
480
+ num_part = item.split('@')[0]
481
+ else:
482
+ num_part = item
483
+
484
+ if num_part.startswith(cc): # Strip optional default country code prefix
485
+ num_part = num_part.replace(cc,'')
486
+
487
+ if num_part.startswith('+') and num_part[1:].isdigit(): # Non-default country code
488
+ to_list.append(num_part)
489
+ elif num_part.isdigit() and len(num_part) == num_len: # No country code prefix remaining
490
+ to_list.append(cc + num_part)
491
+ else:
492
+ raise SndEmailError (f"Message subject <{subj}>: <{num_part}> is not a valid phone number")
493
+
494
+ elif get_type == 'emails':
495
+ if '@' not in item:
496
+ raise SndEmailError (f"Message subject <{subj}>: <{item}> is not a valid email address")
497
+ to_list.append(item)
498
+
499
+ else:
500
+ raise SndEmailError (f"Message subject <{subj}>: <{get_type}> is not a valid get_type for list_to()")
501
+
502
+ return (to_list)
@@ -203,7 +203,7 @@ output:
203
203
 
204
204
  def clear(self, section=''):
205
205
  """
206
- ## clear (section=' ') - Purge a portion of the cfg dictionary
206
+ ## clear (section='') - Purge a portion of the cfg dictionary
207
207
 
208
208
  ***config_item() class member function***
209
209
 
@@ -627,7 +627,7 @@ flush_on_reload, force_flush_reload, and tolerate_missing.
627
627
 
628
628
  def read_dict(self, param_dict, section_name=''):
629
629
  """
630
- ## read_dict (param_dict, section_name=' ') - Load the content of a dictionary into the cfg dictionary
630
+ ## read_dict (param_dict, section_name='') - Load the content of a dictionary into the cfg dictionary
631
631
 
632
632
  ***config_item() class member function***
633
633
 
@@ -699,7 +699,7 @@ Loaded content is added to and/or modifies any previously loaded content.
699
699
 
700
700
  def getcfg(self, param, fallback='_nofallback', types=[], section=''):
701
701
  """
702
- ## getcfg (param, fallback=None, types=[ ], section=' ') - Get a param's value from the cfg dictionary
702
+ ## getcfg (param, fallback=None, types=[ ], section='') - Get a param's value from the cfg dictionary
703
703
 
704
704
  ***config_item() class member function***
705
705
 
@@ -787,7 +787,7 @@ This can lead to cleaner tool script code. Either access method may be used, al
787
787
  # TODO Add section select parameter for selective changes. Also all mode
788
788
  # TODO Add a section label
789
789
  """
790
- ## modify_configfile (param=' ', value=' ', remove=False, add_if_not_existing=False, save=False) - Make edits to the config file
790
+ ## modify_configfile (param='', value='', remove=False, add_if_not_existing=False, save=False) - Make edits to the config file
791
791
 
792
792
  ***config_item() class member function***
793
793
 
@@ -810,10 +810,10 @@ reload call to avoid multiple config reloads.
810
810
 
811
811
 
812
812
  ### Parameters
813
- `param` (str, default ' ')
813
+ `param` (str, default '')
814
814
  - The param name, if modifying an existing param or adding a new param
815
815
 
816
- `value` (as-expected type, default ' ')
816
+ `value` (as-expected type, default '')
817
817
  - The new value to be applied to an existing param, or an added param
818
818
  - Any comment text (after a '#') in the new value will be prepended to any existing comment text
819
819
 
@@ -191,7 +191,7 @@ also to the `.site_data_dir`.
191
191
 
192
192
  def setuplogging(call_logfile=None, call_logfile_wins=False, config_logfile=None, ConsoleLogFormat=None, FileLogFormat=None):
193
193
  """
194
- ## setuplogging (call_logfile=None, call_logfile_wins=False, config_logfile=None) - Set up the root logger
194
+ ## setuplogging (call_logfile=None, call_logfile_wins=False, config_logfile=None, ConsoleLogFormat=None, FileLogFormat=None) - Set up the root logger
195
195
 
196
196
  Logging may be directed to the console (stdout), or to a file. Each time setuplogging()
197
197
  is called the current/active log file (or console) may be reassigned.
@@ -10,7 +10,8 @@
10
10
 
11
11
  import os.path
12
12
  from pathlib import Path, PurePath
13
- from concurrent.futures import ThreadPoolExecutor, TimeoutError
13
+ from concurrent.futures import ThreadPoolExecutor #, TimeoutError
14
+ from cjnfuncs.core import logging
14
15
 
15
16
 
16
17
  #=====================================================================================
@@ -22,7 +23,7 @@ from concurrent.futures import ThreadPoolExecutor, TimeoutError
22
23
  class mungePath():
23
24
  def __init__(self, in_path='', base_path='', mkdir=False):
24
25
  """
25
- ## Class mungePath (in_path=' ', base_path=' ', mkdir=False) - A clean interface for dealing with filesystem paths
26
+ ## Class mungePath (in_path='', base_path='', mkdir=False) - A clean interface for dealing with filesystem paths
26
27
 
27
28
  `mungePath()` is based on pathlib, producing Path type attributes and status booleans which may be used with all
28
29
  pathlib.Path methods, such as .open(). `mungePath()` accepts paths in two parts - the tool script specific
@@ -203,5 +204,6 @@ Implementation stolen from https://stackoverflow.com/questions/67819869/how-to-e
203
204
  future = executor.submit(_path.exists)
204
205
  try:
205
206
  return future.result(timeout)
206
- except TimeoutError:
207
+ except Exception as e: #TimeoutError:
208
+ logging.debug(f"Exception - {e}")
207
209
  return False
@@ -11,6 +11,10 @@
11
11
  import signal
12
12
  import sys
13
13
  import posix_ipc
14
+ import mmap
15
+ import os
16
+ import datetime
17
+ # from pathlib import Path
14
18
  from .core import logging
15
19
 
16
20
  try:
@@ -42,9 +46,11 @@ process completes its work, and then acquire the I2C bus lock so that other proc
42
46
  - Resource locks are on the honor system. Any process can unget a lock, but should not if it didn't get the lock.
43
47
  - This lock mechanism is just as effective across threads within a process.
44
48
  - As many different/independent locks as needed may be created.
45
- - There is no need to dispose of a lock. While posix-ipc.Semaphore has an unlink() method, resource_lock does
46
- not call it. Lock flags are persistent until the system is rebooted.
47
- - Lock names in the posix_ipc module have `/` prefixes. resource_lock() prepends the `/` if `lockname`
49
+ - It is recommended (in order to avoid a minor memory leak) to `close()` the lock in the tool script cleanup code.
50
+ Calling `close()` sets the `closed` attribute to True so that any following code can detect and re-instantiate the
51
+ lock if needed.
52
+ - Semaphores (lock names) and shared memory segments (used for the `lock_info` string) in the posix_ipc module
53
+ must have `/` prefixes. resource_lock() prepends the `/` if `lockname`
48
54
  doesn't start with a `/`, and hides the `/` prefix.
49
55
 
50
56
  resource_lock() requires the `posix_ipc` module (installed with cjnfuncs) from PyPI.
@@ -59,18 +65,37 @@ counter (non-zero is unlocked). `unget_lock()` wont increment the counter unless
59
65
  currently 0 (indicating locked), so it is ***recommended*** to have (possibly extraneous) `unget_lock()` calls,
60
66
  such as in your interrupt-trapped cleanup code.
61
67
 
68
+
62
69
  ### Parameters
63
70
  `lockname` (str)
64
71
  - All processes sharing a given resource must use the same lockname.
72
+
73
+ ### Class attributes
74
+ `lockname` (str)
75
+ - As specified when the resource_lock was instantiated
76
+
77
+ `I_have_the_lock` (bool)
78
+ - True if the current process has set the lock. Useful for conditionally ungetting the lock in cleanup code.
79
+
80
+ `closed` (bool)
81
+ - False once instantiated and set True if `close()` is called in script cleanup code, so that the lock can
82
+ checked and re-instantiate if needed.
65
83
  """
66
84
 
67
85
  def __init__ (self, lockname):
68
86
  if not lockname.startswith('/'):
69
87
  lockname = '/'+lockname # lockname is required to start with '/'
70
- self.lockname = lockname
71
- self.I_have_the_lock = False
88
+ self.lockname = lockname
89
+ self.closed = False
90
+ self.I_have_the_lock = False
72
91
  self.lock = posix_ipc.Semaphore(self.lockname, flags=posix_ipc.O_CREAT, mode=0o0600, initial_value=1)
73
92
 
93
+ memory = posix_ipc.SharedMemory(self.lockname, flags=posix_ipc.O_CREAT, mode=0o0600, size=4096)
94
+ self.mapfile = mmap.mmap(memory.fd, memory.size)
95
+ os.close(memory.fd)
96
+ if not self.is_locked():
97
+ self._set_lock_info('')
98
+
74
99
 
75
100
  #=====================================================================================
76
101
  #=====================================================================================
@@ -78,9 +103,9 @@ such as in your interrupt-trapped cleanup code.
78
103
  #=====================================================================================
79
104
  #=====================================================================================
80
105
 
81
- def get_lock(self, timeout=1, same_process_ok=False):
106
+ def get_lock(self, timeout=1, same_process_ok=False, lock_info=''):
82
107
  """
83
- ## get_lock (timeout=1, same_process_ok=False) - Request the resource lock
108
+ ## get_lock (timeout=1, same_process_ok=False, lock_info='') - Request the resource lock
84
109
 
85
110
  ***resource_lock() class member function***
86
111
 
@@ -103,20 +128,30 @@ decide if the lock has previously been acquired before calling get_lock() again,
103
128
  - If False, then if the lock is currently set by the same process or another process then get_lock() blocks
104
129
  with timeout.
105
130
 
131
+ `lock_info` (str, default '')
132
+ - Optional debugging info string for indicating when and by whom the lock was set. Logged at the debug level.
133
+ - The datetime is prepended to lock_info.
134
+ - A useful lock_info string format might be `<module_name>.<function_name> <get_lock_call_instance_number>`, eg,
135
+ `tempmon.measure_loop #3`.
136
+ - This string remains in place after an unget() call (`is_locked() == False`) for lock history purposes while debugging.
137
+
106
138
  ### Returns
107
139
  - True: Lock successfully acquired, timeout time not exceeded
108
140
  - False: Lock request failed, timed out
109
141
  """
110
142
  if same_process_ok and self.I_have_the_lock == True:
143
+ logging.debug (f"<{self.lockname[1:]}> lock already acquired - Prior grant <{self.get_lock_info()}>")
111
144
  return True
112
145
 
113
146
  try:
114
147
  self.lock.acquire(timeout)
148
+ lock_text = f"{datetime.datetime.now()} - {lock_info}"
149
+ self._set_lock_info(lock_text)
115
150
  self.I_have_the_lock = True
116
- logging.debug (f"<{self.lockname[1:]}> lock request successful (Semaphore = {self.lock.value})")
151
+ logging.debug (f"<{self.lockname[1:]}> lock request successful - Granted <{lock_text}>")
117
152
  return True
118
153
  except posix_ipc.BusyError:
119
- logging.debug (f"<{self.lockname[1:]}> lock request timed out (Semaphore = {self.lock.value})")
154
+ logging.debug (f"<{self.lockname[1:]}> lock request timed out - Current owner <{self.get_lock_info()}>")
120
155
  return False
121
156
 
122
157
 
@@ -126,9 +161,9 @@ with timeout.
126
161
  #=====================================================================================
127
162
  #=====================================================================================
128
163
 
129
- def unget_lock(self, force=False):
164
+ def unget_lock(self, force=False, where_called=''):
130
165
  """
131
- ## unget_lock (force=False) - Release the resource lock
166
+ ## unget_lock (force=False, where_called='') - Release the resource lock
132
167
 
133
168
  ***resource_lock() class member function***
134
169
 
@@ -144,6 +179,9 @@ unless `force=True`.
144
179
  - Useful for forced cleanup, for example, by the CLI interface.
145
180
  - Dangerous if another process had acquired the lock. Be careful.
146
181
 
182
+ `where_called` (str, default '')
183
+ - Debugging aid string for indicating what code released the lock. Logged at the debug level.
184
+
147
185
  ### Returns
148
186
  - True: Lock successfully released
149
187
  - False: Lock not currently set (redundant unget_lock() call), or lock was not acquired by the current process
@@ -152,18 +190,18 @@ unless `force=True`.
152
190
  if self.I_have_the_lock:
153
191
  self.lock.release()
154
192
  self.I_have_the_lock = False
155
- logging.debug (f"<{self.lockname[1:]}> lock released (Semaphore = {self.lock.value})")
193
+ logging.debug (f"<{self.lockname[1:]}> lock released <{where_called}>")
156
194
  return True
157
195
  else:
158
196
  if force:
159
197
  self.lock.release()
160
- logging.debug (f"<{self.lockname[1:]}> lock force released (Semaphore = {self.lock.value})")
198
+ logging.debug (f"<{self.lockname[1:]}> lock force released <{where_called}>")
161
199
  return True
162
200
  else:
163
- logging.debug (f"<{self.lockname[1:]}> lock unget request ignored - lock not owned by current process (Semaphore = {self.lock.value})")
201
+ logging.debug (f"<{self.lockname[1:]}> lock unget request ignored - lock not owned by current process <{where_called}>")
164
202
  return False
165
203
  else:
166
- logging.debug (f"<{self.lockname[1:]}> Extraneous lock unget request ignored (Semaphore = {self.lock.value})")
204
+ logging.debug (f"<{self.lockname[1:]}> Extraneous lock unget request ignored <{where_called}>")
167
205
  return False
168
206
 
169
207
 
@@ -182,8 +220,8 @@ unless `force=True`.
182
220
  ### Returns
183
221
  - True if currently locked, else False
184
222
  """
185
- locked = True if self.lock.value == 0 else False
186
- logging.debug (f"<{self.lockname[1:]}> is currently locked? {locked}")
223
+ locked = True if self.lock.value == 0 else False
224
+ logging.debug (f"<{self.lockname[1:]}> is currently locked? <{locked}> Prior info <{self.get_lock_info()}>")
187
225
  return locked
188
226
 
189
227
 
@@ -207,6 +245,69 @@ unless `force=True`.
207
245
  return _value
208
246
 
209
247
 
248
+ #=====================================================================================
249
+ #=====================================================================================
250
+ # c l o s e
251
+ #=====================================================================================
252
+ #=====================================================================================
253
+
254
+ def close(self):
255
+ """
256
+ ## close () - Release this process' access to the semaphore and the memory-mapped shared memory segment
257
+
258
+ ***resource_lock() class member function***
259
+
260
+ ### Returns
261
+ - None
262
+ """
263
+ self.lock.close()
264
+ self.mapfile.close()
265
+ self.closed = True
266
+ logging.debug (f"<{self.lockname[1:]}> semaphore closed")
267
+
268
+
269
+ #=====================================================================================
270
+ #=====================================================================================
271
+ # g e t _ l o c k _ i n f o
272
+ #=====================================================================================
273
+ #=====================================================================================
274
+
275
+ def get_lock_info(self):
276
+ """
277
+ ## get_lock_info () - Returns the lock_info string from previous get_lock call
278
+
279
+ ***resource_lock() class member function***
280
+
281
+ ### Returns
282
+ - lock_info string
283
+ """
284
+ self.mapfile.seek(0)
285
+ s = []
286
+ c = self.mapfile.read_byte()
287
+ while c != 0: # NULL_CHAR
288
+ s.append(c)
289
+ c = self.mapfile.read_byte()
290
+
291
+ s = ''.join([chr(c) for c in s])
292
+
293
+ return s
294
+
295
+
296
+ #=====================================================================================
297
+ #=====================================================================================
298
+ # _ s e t _ l o c k _ i n f o (private function)
299
+ #=====================================================================================
300
+ #=====================================================================================
301
+
302
+ def _set_lock_info(self, desc):
303
+ # While the shared memory segment and memory mapped block are 4k bytes log, the actual
304
+ # lock_info description is terminated by a null character (0x00)
305
+ self.mapfile.seek(0)
306
+ desc += '\0'
307
+ self.mapfile.write(desc.encode())
308
+
309
+
310
+
210
311
  #=====================================================================================
211
312
  #=====================================================================================
212
313
  # c l i
@@ -243,6 +344,8 @@ def cli():
243
344
  help="Command choices")
244
345
  parser.add_argument('-t', '--get-timeout', type=float, default=GET_TIMEOUT,
245
346
  help=f"Timeout value for a get call (default {GET_TIMEOUT} sec, -1 for no timeout)")
347
+ parser.add_argument('-m', '--message', default='cli',
348
+ help=f"Lock get/unget debug message text (default 'cli')")
246
349
  parser.add_argument('-a', '--auto-unget', type=float,
247
350
  help="After a successful get, unget the lock in (float) sec")
248
351
  parser.add_argument('-u', '--update', type=float, default=TRACE_INTERVAL,
@@ -257,14 +360,14 @@ def cli():
257
360
  _timeout = args.get_timeout
258
361
  if _timeout == -1:
259
362
  _timeout = None
260
- get_status = lock.get_lock(timeout=_timeout)
363
+ get_status = lock.get_lock(timeout=_timeout, lock_info=args.message)
261
364
  if get_status and args.auto_unget:
262
365
  print (f"Release lock after <{args.auto_unget}> sec delay")
263
366
  sleep(args.auto_unget)
264
- lock.unget_lock()
367
+ lock.unget_lock(where_called=f'{args.message} - auto unget')
265
368
 
266
369
  elif args.Cmd == "unget":
267
- lock.unget_lock(force=True)
370
+ lock.unget_lock(force=True, where_called=args.message)
268
371
 
269
372
  elif args.Cmd == "state":
270
373
  lock.is_locked()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cjnfuncs
3
- Version: 2.3
3
+ Version: 2.4
4
4
  Summary: A collection of core functions for tool script writing
5
5
  Author-email: Chris Nelson <github@cjnaz.com>
6
6
  License: MIT License
@@ -75,6 +75,7 @@ Project repo: https://github.com/cjnaz/cjnfuncs
75
75
  <br/>
76
76
 
77
77
  ## Revision history
78
+ - 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
78
79
  - 2.3 240821 - Added mungePath ./ support.
79
80
  Resolved check_path_exists() memory leak.
80
81
  Added `same_process_ok` to resourcelock.getlock()
File without changes
File without changes
File without changes
File without changes