cjnfuncs 2.3__tar.gz → 2.4.1__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.1
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,20 @@
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.1"
9
+ # 2.4.1 - resource_lock only init lock_info if not existing
10
+ # 2.4.1b1 - resource_lock only init lock_info if not existing
11
+ # 2.4 - release
12
+ # 2.4rc2 - check_path_exists() exception fix for unmounted network path (OSError: [Errno 19] No such device)
13
+ # 2.4rc1 - doc fix on setuplogging()
14
+ # 2.4b4 - resourcelock closed attribute
15
+ # 2.4b3 - Added lock_info to resource_lock
16
+ # 2.4b2 - Added where_called to resource_lock unget for debugging aid
17
+ # 2.4b1 - Added Twilio support to snd_notif
9
18
  description = "A collection of core functions for tool script writing"
10
19
  readme = "README.md"
11
20
  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,13 @@ 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
+ - The first time a lock is created (on the current computer since reboot) the lock info string (accessible via `get_lock_info()`)
50
+ is set to '', else it retains the value set by the most recent get_lock() call.
51
+ - It is recommended (in order to avoid a minor memory leak) to `close()` the lock in the tool script cleanup code.
52
+ Calling `close()` sets the `closed` attribute to True so that any following code can detect and re-instantiate the
53
+ lock if needed.
54
+ - Semaphores (lock names) and shared memory segments (used for the `lock_info` string) in the posix_ipc module
55
+ must have `/` prefixes. resource_lock() prepends the `/` if `lockname`
48
56
  doesn't start with a `/`, and hides the `/` prefix.
49
57
 
50
58
  resource_lock() requires the `posix_ipc` module (installed with cjnfuncs) from PyPI.
@@ -59,18 +67,43 @@ counter (non-zero is unlocked). `unget_lock()` wont increment the counter unless
59
67
  currently 0 (indicating locked), so it is ***recommended*** to have (possibly extraneous) `unget_lock()` calls,
60
68
  such as in your interrupt-trapped cleanup code.
61
69
 
70
+
62
71
  ### Parameters
63
72
  `lockname` (str)
64
73
  - All processes sharing a given resource must use the same lockname.
74
+
75
+ ### Class attributes
76
+ `lockname` (str)
77
+ - As specified when the resource_lock was instantiated
78
+
79
+ `I_have_the_lock` (bool)
80
+ - True if the current process has set the lock. Useful for conditionally ungetting the lock in cleanup code.
81
+
82
+ `closed` (bool)
83
+ - False once instantiated and set True if `close()` is called in script cleanup code, so that the lock can
84
+ checked and re-instantiate if needed.
65
85
  """
66
86
 
67
87
  def __init__ (self, lockname):
68
88
  if not lockname.startswith('/'):
69
89
  lockname = '/'+lockname # lockname is required to start with '/'
70
- self.lockname = lockname
71
- self.I_have_the_lock = False
90
+ self.lockname = lockname
91
+ self.closed = False
92
+ self.I_have_the_lock = False
72
93
  self.lock = posix_ipc.Semaphore(self.lockname, flags=posix_ipc.O_CREAT, mode=0o0600, initial_value=1)
73
94
 
95
+ preexisting = False
96
+ try:
97
+ memory = posix_ipc.SharedMemory(self.lockname, flags=0)
98
+ preexisting = True
99
+ except posix_ipc.ExistentialError:
100
+ memory = posix_ipc.SharedMemory(self.lockname, flags=posix_ipc.O_CREAT, mode=0o0600, size=4096)
101
+
102
+ self.mapfile = mmap.mmap(memory.fd, memory.size)
103
+ os.close(memory.fd)
104
+ if not preexisting:
105
+ self._set_lock_info('')
106
+
74
107
 
75
108
  #=====================================================================================
76
109
  #=====================================================================================
@@ -78,9 +111,9 @@ such as in your interrupt-trapped cleanup code.
78
111
  #=====================================================================================
79
112
  #=====================================================================================
80
113
 
81
- def get_lock(self, timeout=1, same_process_ok=False):
114
+ def get_lock(self, timeout=1, same_process_ok=False, lock_info=''):
82
115
  """
83
- ## get_lock (timeout=1, same_process_ok=False) - Request the resource lock
116
+ ## get_lock (timeout=1, same_process_ok=False, lock_info='') - Request the resource lock
84
117
 
85
118
  ***resource_lock() class member function***
86
119
 
@@ -103,20 +136,30 @@ decide if the lock has previously been acquired before calling get_lock() again,
103
136
  - If False, then if the lock is currently set by the same process or another process then get_lock() blocks
104
137
  with timeout.
105
138
 
139
+ `lock_info` (str, default '')
140
+ - Optional debugging info string for indicating when and by whom the lock was set. Logged at the debug level.
141
+ - The datetime is prepended to lock_info.
142
+ - A useful lock_info string format might be `<module_name>.<function_name> <get_lock_call_instance_number>`, eg,
143
+ `tempmon.measure_loop #3`.
144
+ - This string remains in place after an unget() call (`is_locked() == False`) for lock history purposes while debugging.
145
+
106
146
  ### Returns
107
147
  - True: Lock successfully acquired, timeout time not exceeded
108
148
  - False: Lock request failed, timed out
109
149
  """
110
150
  if same_process_ok and self.I_have_the_lock == True:
151
+ logging.debug (f"<{self.lockname[1:]}> lock already acquired - Prior grant <{self.get_lock_info()}>")
111
152
  return True
112
153
 
113
154
  try:
114
155
  self.lock.acquire(timeout)
156
+ lock_text = f"{datetime.datetime.now()} - {lock_info}"
157
+ self._set_lock_info(lock_text)
115
158
  self.I_have_the_lock = True
116
- logging.debug (f"<{self.lockname[1:]}> lock request successful (Semaphore = {self.lock.value})")
159
+ logging.debug (f"<{self.lockname[1:]}> lock request successful - Granted <{lock_text}>")
117
160
  return True
118
161
  except posix_ipc.BusyError:
119
- logging.debug (f"<{self.lockname[1:]}> lock request timed out (Semaphore = {self.lock.value})")
162
+ logging.debug (f"<{self.lockname[1:]}> lock request timed out - Current owner <{self.get_lock_info()}>")
120
163
  return False
121
164
 
122
165
 
@@ -126,9 +169,9 @@ with timeout.
126
169
  #=====================================================================================
127
170
  #=====================================================================================
128
171
 
129
- def unget_lock(self, force=False):
172
+ def unget_lock(self, force=False, where_called=''):
130
173
  """
131
- ## unget_lock (force=False) - Release the resource lock
174
+ ## unget_lock (force=False, where_called='') - Release the resource lock
132
175
 
133
176
  ***resource_lock() class member function***
134
177
 
@@ -144,6 +187,9 @@ unless `force=True`.
144
187
  - Useful for forced cleanup, for example, by the CLI interface.
145
188
  - Dangerous if another process had acquired the lock. Be careful.
146
189
 
190
+ `where_called` (str, default '')
191
+ - Debugging aid string for indicating what code released the lock. Logged at the debug level.
192
+
147
193
  ### Returns
148
194
  - True: Lock successfully released
149
195
  - False: Lock not currently set (redundant unget_lock() call), or lock was not acquired by the current process
@@ -152,18 +198,18 @@ unless `force=True`.
152
198
  if self.I_have_the_lock:
153
199
  self.lock.release()
154
200
  self.I_have_the_lock = False
155
- logging.debug (f"<{self.lockname[1:]}> lock released (Semaphore = {self.lock.value})")
201
+ logging.debug (f"<{self.lockname[1:]}> lock released <{where_called}>")
156
202
  return True
157
203
  else:
158
204
  if force:
159
205
  self.lock.release()
160
- logging.debug (f"<{self.lockname[1:]}> lock force released (Semaphore = {self.lock.value})")
206
+ logging.debug (f"<{self.lockname[1:]}> lock force released <{where_called}>")
161
207
  return True
162
208
  else:
163
- logging.debug (f"<{self.lockname[1:]}> lock unget request ignored - lock not owned by current process (Semaphore = {self.lock.value})")
209
+ logging.debug (f"<{self.lockname[1:]}> lock unget request ignored - lock not owned by current process <{where_called}>")
164
210
  return False
165
211
  else:
166
- logging.debug (f"<{self.lockname[1:]}> Extraneous lock unget request ignored (Semaphore = {self.lock.value})")
212
+ logging.debug (f"<{self.lockname[1:]}> Extraneous lock unget request ignored <{where_called}>")
167
213
  return False
168
214
 
169
215
 
@@ -182,8 +228,8 @@ unless `force=True`.
182
228
  ### Returns
183
229
  - True if currently locked, else False
184
230
  """
185
- locked = True if self.lock.value == 0 else False
186
- logging.debug (f"<{self.lockname[1:]}> is currently locked? {locked}")
231
+ locked = True if self.lock.value == 0 else False
232
+ logging.debug (f"<{self.lockname[1:]}> is currently locked? <{locked}> Prior info <{self.get_lock_info()}>")
187
233
  return locked
188
234
 
189
235
 
@@ -207,6 +253,69 @@ unless `force=True`.
207
253
  return _value
208
254
 
209
255
 
256
+ #=====================================================================================
257
+ #=====================================================================================
258
+ # c l o s e
259
+ #=====================================================================================
260
+ #=====================================================================================
261
+
262
+ def close(self):
263
+ """
264
+ ## close () - Release this process' access to the semaphore and the memory-mapped shared memory segment
265
+
266
+ ***resource_lock() class member function***
267
+
268
+ ### Returns
269
+ - None
270
+ """
271
+ self.lock.close()
272
+ self.mapfile.close()
273
+ self.closed = True
274
+ logging.debug (f"<{self.lockname[1:]}> semaphore closed")
275
+
276
+
277
+ #=====================================================================================
278
+ #=====================================================================================
279
+ # g e t _ l o c k _ i n f o
280
+ #=====================================================================================
281
+ #=====================================================================================
282
+
283
+ def get_lock_info(self):
284
+ """
285
+ ## get_lock_info () - Returns the lock_info string from previous get_lock call
286
+
287
+ ***resource_lock() class member function***
288
+
289
+ ### Returns
290
+ - lock_info string
291
+ """
292
+ self.mapfile.seek(0)
293
+ s = []
294
+ c = self.mapfile.read_byte()
295
+ while c != 0: # NULL_CHAR
296
+ s.append(c)
297
+ c = self.mapfile.read_byte()
298
+
299
+ s = ''.join([chr(c) for c in s])
300
+
301
+ return s
302
+
303
+
304
+ #=====================================================================================
305
+ #=====================================================================================
306
+ # _ s e t _ l o c k _ i n f o (private function)
307
+ #=====================================================================================
308
+ #=====================================================================================
309
+
310
+ def _set_lock_info(self, desc):
311
+ # While the shared memory segment and memory mapped block are 4k bytes log, the actual
312
+ # lock_info description is terminated by a null character (0x00)
313
+ self.mapfile.seek(0)
314
+ desc += '\0'
315
+ self.mapfile.write(desc.encode())
316
+
317
+
318
+
210
319
  #=====================================================================================
211
320
  #=====================================================================================
212
321
  # c l i
@@ -243,6 +352,8 @@ def cli():
243
352
  help="Command choices")
244
353
  parser.add_argument('-t', '--get-timeout', type=float, default=GET_TIMEOUT,
245
354
  help=f"Timeout value for a get call (default {GET_TIMEOUT} sec, -1 for no timeout)")
355
+ parser.add_argument('-m', '--message', default='cli',
356
+ help=f"Lock get/unget debug message text (default 'cli')")
246
357
  parser.add_argument('-a', '--auto-unget', type=float,
247
358
  help="After a successful get, unget the lock in (float) sec")
248
359
  parser.add_argument('-u', '--update', type=float, default=TRACE_INTERVAL,
@@ -257,14 +368,14 @@ def cli():
257
368
  _timeout = args.get_timeout
258
369
  if _timeout == -1:
259
370
  _timeout = None
260
- get_status = lock.get_lock(timeout=_timeout)
371
+ get_status = lock.get_lock(timeout=_timeout, lock_info=args.message)
261
372
  if get_status and args.auto_unget:
262
373
  print (f"Release lock after <{args.auto_unget}> sec delay")
263
374
  sleep(args.auto_unget)
264
- lock.unget_lock()
375
+ lock.unget_lock(where_called=f'{args.message} - auto unget')
265
376
 
266
377
  elif args.Cmd == "unget":
267
- lock.unget_lock(force=True)
378
+ lock.unget_lock(force=True, where_called=args.message)
268
379
 
269
380
  elif args.Cmd == "state":
270
381
  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.1
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