cjnfuncs 2.1__tar.gz → 2.3__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.1
3
+ Version: 2.3
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
@@ -31,12 +31,13 @@ Description-Content-Type: text/markdown
31
31
  License-File: LICENSE.txt
32
32
  Requires-Dist: requests
33
33
  Requires-Dist: appdirs>=1.4
34
+ Requires-Dist: dkimpy
34
35
  Requires-Dist: importlib_resources
35
36
  Requires-Dist: posix-ipc>=1.1.1
36
37
 
37
38
  # cjnfuncs - A framework and collection of utility functions for script writing
38
39
 
39
- ## cjnfuncs is comprised of several modules (links to respective documentation)
40
+ ## cjnfuncs is comprised of several modules (follow links to respective documentation)
40
41
 
41
42
  NOTE: Since relative links to other .md files do not work on PyPI, please go to the [cjnfuncs GitHub repo](https://github.com/cjnaz/cjnfuncs) to read the documentation.
42
43
 
@@ -45,13 +46,13 @@ module | Description/Purpose
45
46
  [core](core.md) | Set up the base environment
46
47
  [configman](configman.md) | Feature-rich configuration file toolset
47
48
  [timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes)
48
- [mungePath](mungePath.md) | Ease-of-use pathlib extenstion for constructing and manipulating file paths
49
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
49
50
  [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
50
51
  [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
51
52
  [SMTP](SMTP.md) | Send notification and email messages
52
53
 
53
54
  Developed and tested on Python 3.6.8, and supported on all higher Python versions.
54
- Developed on Linux, supported also on Windows (tested on Windows 10).
55
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
55
56
 
56
57
  In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
57
58
 
@@ -74,6 +75,11 @@ Project repo: https://github.com/cjnaz/cjnfuncs
74
75
  <br/>
75
76
 
76
77
  ## Revision history
78
+ - 2.3 240821 - Added mungePath ./ support.
79
+ Resolved check_path_exists() memory leak.
80
+ Added `same_process_ok` to resourcelock.getlock()
81
+ Added prereload_callback to config_item.loadconfig()
82
+ - 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
77
83
  - 2.1 240104 - Partitioned to separate modules.
78
84
  Added modify_configfile.
79
85
  Added native support for float, list, tuple, and dict in loadconfig().
@@ -1,6 +1,6 @@
1
1
  # cjnfuncs - A framework and collection of utility functions for script writing
2
2
 
3
- ## cjnfuncs is comprised of several modules (links to respective documentation)
3
+ ## cjnfuncs is comprised of several modules (follow links to respective documentation)
4
4
 
5
5
  NOTE: Since relative links to other .md files do not work on PyPI, please go to the [cjnfuncs GitHub repo](https://github.com/cjnaz/cjnfuncs) to read the documentation.
6
6
 
@@ -9,13 +9,13 @@ module | Description/Purpose
9
9
  [core](core.md) | Set up the base environment
10
10
  [configman](configman.md) | Feature-rich configuration file toolset
11
11
  [timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes)
12
- [mungePath](mungePath.md) | Ease-of-use pathlib extenstion for constructing and manipulating file paths
12
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
13
13
  [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
14
14
  [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
15
15
  [SMTP](SMTP.md) | Send notification and email messages
16
16
 
17
17
  Developed and tested on Python 3.6.8, and supported on all higher Python versions.
18
- Developed on Linux, supported also on Windows (tested on Windows 10).
18
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
19
19
 
20
20
  In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
21
21
 
@@ -38,6 +38,11 @@ Project repo: https://github.com/cjnaz/cjnfuncs
38
38
  <br/>
39
39
 
40
40
  ## Revision history
41
+ - 2.3 240821 - Added mungePath ./ support.
42
+ Resolved check_path_exists() memory leak.
43
+ Added `same_process_ok` to resourcelock.getlock()
44
+ Added prereload_callback to config_item.loadconfig()
45
+ - 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
41
46
  - 2.1 240104 - Partitioned to separate modules.
42
47
  Added modify_configfile.
43
48
  Added native support for float, list, tuple, and dict in loadconfig().
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "cjnfuncs"
8
- version = "2.1"
8
+ version = "2.3"
9
9
  description = "A collection of core functions for tool script writing"
10
10
  readme = "README.md"
11
11
  requires-python = ">=3.6" # Centos 7 uses 3.6.8
@@ -14,6 +14,7 @@ license = {file = "LICENSE.txt"}
14
14
  dependencies = [
15
15
  'requests',
16
16
  'appdirs >= 1.4',
17
+ 'dkimpy',
17
18
  'importlib_resources', #; python_version < "3.9"', # in 2.0.1, used for all python versions
18
19
  'posix-ipc >= 1.1.1'
19
20
  ]
@@ -4,14 +4,16 @@
4
4
 
5
5
  #==========================================================
6
6
  #
7
- # Chris Nelson, 2018-2023
7
+ # Chris Nelson, 2018-2024
8
8
  #
9
9
  #==========================================================
10
10
 
11
11
  import time
12
12
  import smtplib
13
13
  from email.mime.text import MIMEText
14
+ from email.utils import formatdate
14
15
  from pathlib import Path
16
+ import dkim
15
17
 
16
18
  from .core import logging, SndEmailError
17
19
  from .mungePath import mungePath
@@ -20,7 +22,8 @@ import cjnfuncs.core as core
20
22
 
21
23
  # Configs / Constants
22
24
  SND_EMAIL_NTRIES = 3 # Number of tries to send email before aborting
23
- SND_EMAIL_WAIT = '5s' # seconds between retries
25
+ RETRY_WAIT = '2s' # seconds between retries
26
+ SERVER_TIMEOUT = '2s' # server connection timeout
24
27
 
25
28
 
26
29
  #=====================================================================================
@@ -45,30 +48,30 @@ Three attempts are made to send the message.
45
48
 
46
49
 
47
50
  ### Parameters
48
- `subj` (default 'Notification message')
51
+ `subj` (str, default 'Notification message')
49
52
  - Text message subject field
50
53
  - Some SMS/MMS apps display the subj field in bold, some in raw form, and some not at all.
51
54
 
52
- `msg` (default ' ')
55
+ `msg` (str, default ' ')
53
56
  - Text message body
54
57
 
55
- `to` (default 'NotifList')
58
+ `to` (str, default 'NotifList')
56
59
  - To whom to send the message. `to` may be either an explicit string list of email addresses
57
60
  (whitespace or comma separated) or a config param name (also listing one
58
61
  or more whitespace or comma separated email addresses). If the `to` parameter does not
59
62
  contain an '@' it is assumed to be a config param.
60
63
  - Define `NotifList` in the config file to use the default `to` value.
61
64
 
62
- `log` (default False)
65
+ `log` (bool, default False)
63
66
  - If True, logs that the message was sent at the WARNING level. If False, logs
64
67
  at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
65
68
  The `subj` field is part of the log message.
66
69
 
67
- `smtp_config` (required)
70
+ `smtp_config` (config_item class instance)
68
71
  - config_item class instance containing the [SMTP] section and related params
69
72
 
70
73
 
71
- ### cfg dictionary params in the [SMTP] section
74
+ ### cfg dictionary params in the [SMTP] section, in addition to the cfg dictionary params required for snd_email
72
75
  `NotifList` (optional)
73
76
  - string list of email addresses (whitespace or comma separated).
74
77
  - Defining `NotifList` in the config is only required if any call to `snd_notif()` uses this
@@ -79,6 +82,8 @@ default `to` parameter value.
79
82
  messages are also blocked if `DontEmail` is True.
80
83
 
81
84
 
85
+
86
+
82
87
  ### Returns
83
88
  - NoneType
84
89
  - Raises `SndEmailError` on error
@@ -121,36 +126,38 @@ or a string with one or more email addresses. Using a config param name allows f
121
126
  `to` addresses without having to edit the code.
122
127
 
123
128
  What to send may be a `body` string, the text contents of `filename`, or the HTML-formatted contents
124
- of `htmlfile`, in this order of precedent.
129
+ of `htmlfile`, in this order of precedent. MIME multi-part is not supported.
130
+
131
+ DKIM signing is optionally supported.
125
132
 
126
133
  Three attempts are made to send the message (see `EmailNTries`, below).
127
134
 
128
135
 
129
136
  ### Parameters
130
- `subj`
137
+ `subj` (str)
131
138
  - Email subject text
132
139
 
133
- `to`
140
+ `to` (str)
134
141
  - To whom to send the message. `to` may be either an explicit string list of email addresses
135
142
  (whitespace or comma separated) or a config param name in the [SMTP] section (also listing one
136
143
  or more whitespace or comma separated email addresses). If the `to` parameter does not
137
144
  contain an '@' it is assumed to be a config param.
138
145
 
139
- `body` (default None)
146
+ `body` (str, default None)
140
147
  - A string message to be sent
141
148
 
142
- `filename` (default None)
149
+ `filename` (str, default None)
143
150
  - A str or Path to the file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
144
151
 
145
- `htmlfile` (default None)
152
+ `htmlfile` (str, default None)
146
153
  - A str or Path to the html formatted file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
147
154
 
148
- `log` (default False)
155
+ `log` (bool, default False)
149
156
  - If True, logs that the message was sent at the WARNING level. If False, logs
150
157
  at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
151
158
  The `subj` field is part of the log message.
152
159
 
153
- `smtp_config` (required)
160
+ `smtp_config` (config_item class instance)
154
161
  - config_item class instance containing the [SMTP] section and related params
155
162
 
156
163
 
@@ -179,9 +186,24 @@ The `subj` field is part of the log message.
179
186
  `EmailNTries` (type int, default 3)
180
187
  - Number of tries to send email before aborting
181
188
 
182
- `EmailRetryWait` (seconds, type int, float, or timevalue, default 5s)
189
+ `EmailRetryWait` (seconds, type int, float, or timevalue, default 2s)
183
190
  - Number of seconds to wait between retry attempts
184
191
 
192
+ `EmailServerTimeout` (seconds, type int, float, or timevalue, default 2s)
193
+ - Server connection timeout
194
+
195
+ `EmailDKIMDomain` (required if using DKIM email signing)
196
+ - The domain of the public-facing SMTP server, eg `mydomain.com`
197
+ - Defining `EmailDKIMDomain` enables DKIM signing, and also requires `EmailDKIMPem` and `EmailDKIMSelector`
198
+
199
+ `EmailDKIMPem` (required if using DKIM email signing)
200
+ - Full path to the private key file of the public-facing SMTP server at the `EmailDomain`, eg `/home/me/creds_mydomain.com.pem`
201
+ - Make sure this file is readable only to the user
202
+ - You may be able to obtain this key in cPanel for your shared-hosting service
203
+
204
+ `EmailDKIMSelector` (required if using DKIM email signing)
205
+ - The DKIM selector string, eg 'default'
206
+
185
207
 
186
208
  ### Returns
187
209
  - NoneType
@@ -202,6 +224,7 @@ Some email servers require that the `EmailFrom` address be of the same domain as
202
224
  so it may be practical to bundle `EmailFrom` with the server specifics. Place all of these in
203
225
  `~/creds_SMTP`:
204
226
  - `EmailFrom`, `EmailServer`, `EmailServerPort`, `EmailUser`, and `EmailPass`
227
+ - If DKIM signing is used, also include `EmailDKIMDomain`, `EmailDKIMPem`, and `EmailDKIMSelector`
205
228
  - `snd_email()` does not support multi-part MIME (an html send wont have a plain text part).
206
229
  - Checking the validity of email addresses is very basic... an email address must contain an '@'.
207
230
  """
@@ -260,16 +283,27 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
260
283
  raise SndEmailError (f"snd_email - Message subject <{subj}>: address in 'to' list is invalid: <{address}>.")
261
284
 
262
285
  # Gather, check remaining config params
263
- ntries = smtp_config.getcfg('EmailNTries', SND_EMAIL_NTRIES, types=int, section='SMTP')
264
- retry_wait = timevalue(smtp_config.getcfg('EmailRetryWait', SND_EMAIL_WAIT, types=[int, float, str], section='SMTP')).seconds
265
- email_from = smtp_config.getcfg('EmailFrom', types=str, section='SMTP')
266
- cfg_server = smtp_config.getcfg('EmailServer', types=str, section='SMTP')
267
- cfg_port = smtp_config.getcfg('EmailServerPort', types=str, section='SMTP').lower()
286
+ ntries = smtp_config.getcfg('EmailNTries', SND_EMAIL_NTRIES, types=int, section='SMTP')
287
+ retry_wait = timevalue(smtp_config.getcfg('EmailRetryWait', RETRY_WAIT, types=[int, float, str], section='SMTP')).seconds
288
+ server_timeout = timevalue(smtp_config.getcfg('EmailServerTimeout', SERVER_TIMEOUT, types=[int, float, str], section='SMTP')).seconds
289
+ email_from = smtp_config.getcfg('EmailFrom', types=str, section='SMTP')
290
+ cfg_server = smtp_config.getcfg('EmailServer', types=str, section='SMTP')
291
+ cfg_port = smtp_config.getcfg('EmailServerPort', types=str, section='SMTP').lower()
268
292
  if cfg_port not in ['p25', 'p465', 'p587', 'p587tls']:
269
- raise SndEmailError (f"snd_email - Config EmailServerPort <{smtp_config.getcfg('EmailServerPort', fallback='', section='SMTP')}> is invalid")
270
- email_user = str(smtp_config.getcfg('EmailUser', None, types=[str, int, float], section='SMTP')) # username may be numeric
293
+ raise SndEmailError (f"snd_email - Config EmailServerPort <{cfg_port}> is invalid")
294
+
295
+ email_user = str(smtp_config.getcfg('EmailUser', None, types=[str, int, float], section='SMTP')) # username may be numeric - optional
271
296
  if email_user:
272
- email_pass = str(smtp_config.getcfg('EmailPass', types=[str, int, float], section='SMTP')) # password may be numeric
297
+ email_pass = str(smtp_config.getcfg('EmailPass', types=[str, int, float], section='SMTP')) # password may be numeric - required if EmailUser provided
298
+
299
+ dkim_domain = smtp_config.getcfg('EmailDKIMDomain', None, types=str, section='SMTP')
300
+ if dkim_domain:
301
+ dkim_pem = smtp_config.getcfg('EmailDKIMPem', None, types=str, section='SMTP')
302
+ if not dkim_pem:
303
+ raise SndEmailError (f"snd_email - Config <EmailDKIMPem> is required for SMTP DKIM signing")
304
+ dkim_selector = smtp_config.getcfg('EmailDKIMSelector', None, types=str, section='SMTP')
305
+ if not dkim_selector:
306
+ raise SndEmailError (f"snd_email - Config <EmailDKIMSelector> is required for SMTP DKIM signing")
273
307
 
274
308
  if smtp_config.getcfg('DontEmail', fallback=False, types=bool, section='SMTP'):
275
309
  if log:
@@ -278,6 +312,7 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
278
312
  logging.debug (f"Email NOT sent <{subj}>")
279
313
  return
280
314
 
315
+
281
316
  # Send the message, with retries
282
317
  for trynum in range(ntries):
283
318
  try:
@@ -285,21 +320,41 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
285
320
  msg['Subject'] = subj
286
321
  msg['From'] = email_from
287
322
  msg['To'] = ", ".join(To)
288
-
323
+ msg["Date"] = formatdate(localtime=True)
324
+
325
+ # Add DKIM signature if EmailDKIMDomain is specified
326
+ if dkim_domain:
327
+ privateKey = Path(dkim_pem).read_text()
328
+ sig = dkim.sign(message=msg.as_bytes(),
329
+ selector= bytes(dkim_selector, 'UTF8'),
330
+ domain= bytes(dkim_domain, 'UTF8'),
331
+ privkey= bytes(privateKey, 'UTF8'),
332
+ include_headers= ['from', 'to', 'subject', 'date'])
333
+ sig = sig.decode()
334
+ msg['DKIM-Signature'] = sig[len("DKIM-Signature: "):]
335
+
336
+ logging.debug (f"Initialize the SMTP server connection for port <{cfg_port}>")
289
337
  if cfg_port == "p25":
290
- server = smtplib.SMTP(cfg_server, 25)
338
+ server = smtplib.SMTP(cfg_server, 25, timeout=server_timeout)
291
339
  elif cfg_port == "p465":
292
- server = smtplib.SMTP_SSL(cfg_server, 465)
293
- elif cfg_port == "p587":
294
- server = smtplib.SMTP(cfg_server, 587)
295
- else: # cfg_port == "P587TLS":
296
- server = smtplib.SMTP(cfg_server, 587)
297
- server.starttls()
340
+ server = smtplib.SMTP_SSL(cfg_server, 465, timeout=server_timeout)
341
+ else: # cfg_port == "p587" or "p587tls"
342
+ server = smtplib.SMTP(cfg_server, 587, timeout=server_timeout)
298
343
 
299
- if email_user:
300
- server.login (email_user, email_pass)
301
344
  if smtp_config.getcfg("EmailVerbose", False, types=[bool], section='SMTP'):
345
+ logging.debug ("Set SMTP connection debuglevel(1)")
302
346
  server.set_debuglevel(1)
347
+
348
+ if cfg_port == "p587tls":
349
+ logging.debug ("Start TLS")
350
+ server.starttls()
351
+
352
+ # if email_user:
353
+ if cfg_port.startswith('p587'):
354
+ logging.debug (f"Logging into SMTP server")
355
+ server.login (email_user, email_pass)
356
+
357
+ logging.debug (f"Sending message <{subj}>")
303
358
  server.sendmail(email_from, To, msg.as_string())
304
359
  server.quit()
305
360
 
@@ -311,8 +366,10 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
311
366
 
312
367
  except Exception as e:
313
368
  last_error = e
314
- logging.debug(f"Email send try {trynum} failed:\n <{e}>")
369
+ # if logging.getLogger().level == logging.DEBUG:
370
+ # logging.exception(f"Email send try {trynum} failed:")
315
371
  if trynum < ntries -1:
372
+ logging.debug(f"Email send try {trynum} failed. Retry in <{retry_wait} sec>:\n <{e}>")
316
373
  time.sleep(retry_wait)
317
374
  continue
318
375
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  #==========================================================
6
6
  #
7
- # Chris Nelson, 2018-2023
7
+ # Chris Nelson, 2018-2024
8
8
  #
9
9
  #==========================================================
10
10
 
@@ -46,18 +46,18 @@ The config_item() class provides handling of one or more config file instances.
46
46
 
47
47
 
48
48
  ### Instantiation parameters
49
- `config_file` (default None)
49
+ `config_file` (str, default None)
50
50
  - Path to the configuration file, relative to the `core.tool.config_dir` directory, or an absolute path.
51
51
  - `None` may be used if the config will be loaded programmatically via `read_string()` or `read_dict()`.
52
52
 
53
- `remap_logdirbase` (default True)
53
+ `remap_logdirbase` (bool, default True)
54
54
  - If `remap_logdirbase=True` and the tool script is running in _user_ mode (not site mode)
55
55
  then the `core.tool.log_dir_base` will be set to `core.tool.config_dir`.
56
56
 
57
- `force_str` (default False)
57
+ `force_str` (bool, default False)
58
58
  - Causes all params to be loaded as type `str`, overriding the default type identification.
59
59
 
60
- `secondary_config` (default False)
60
+ `secondary_config` (bool, default False)
61
61
  - Set to `True` when loading additional config files. Disables logging setup related changes.
62
62
  - The primary config file should be loaded first before any secondary_config loads, so that logging
63
63
  is properly set up.
@@ -208,7 +208,7 @@ output:
208
208
  ***config_item() class member function***
209
209
 
210
210
  ### Parameters
211
- `section` (default '')
211
+ `section` (str, default '')
212
212
  - `section = ''` clears the entire cfg dictionary, including all sections and DEFAULT
213
213
  - `section = '<section_name>'` clears just that section
214
214
  - `section = 'DEFAULT'` clears just the DEFAULT section
@@ -290,7 +290,8 @@ output:
290
290
  flush_on_reload = False,
291
291
  force_flush_reload = False,
292
292
  isimport = False,
293
- tolerate_missing = False):
293
+ tolerate_missing = False,
294
+ prereload_callback = None):
294
295
  """
295
296
  ## loadconfig () - Load a configuration file into the cfg dictionary
296
297
  ```
@@ -301,7 +302,8 @@ loadconfig(
301
302
  flush_on_reload = False,
302
303
  force_flush_reload = False,
303
304
  isimport = False,
304
- tolerate_missing = False)
305
+ tolerate_missing = False,
306
+ prereload_callback = None)
305
307
  ```
306
308
  ***config_item() class member function***
307
309
 
@@ -315,29 +317,31 @@ feature, and intermittent loss of access to the config file.
315
317
 
316
318
 
317
319
  ### Parameters
318
- `ldcfg_ll` (default 30/WARNING)
320
+ `ldcfg_ll` (int, default 30 (WARNING))
319
321
  - Logging level used within `loadconfig()` code for debugging loadconfig() itself
320
322
 
321
- `call_logfile` (default None)
323
+ `call_logfile` (str, default None)
322
324
  - An absolute path or relative to the `core.tool.log_dir_base` directory
323
325
 
324
- `call_logfile_wins` (default False)
326
+ `call_logfile_wins` (bool, default False)
325
327
  - If True, the `call_logfile` overrides any `LogFile` in the config file
326
328
 
327
- `flush_on_reload` (default False)
329
+ `flush_on_reload` (bool, default False)
328
330
  - If the config file will be reloaded (due to a changed timestamp) then clean out the
329
331
  `cfg` dictionary first
330
332
 
331
- `force_flush_reload` (default False)
333
+ `force_flush_reload` (bool, default False)
332
334
  - Forces the `cfg` dictionary to be cleaned out and the config file to be reloaded,
333
335
  regardless of whether the config file timestamp has changed
334
336
 
335
- `isimport` (default False)
337
+ `isimport` (bool, default False)
336
338
  - Internally set True when handling imports. Not used by tool script calls.
337
339
 
338
- `tolerate_missing` (default False)
340
+ `tolerate_missing` (bool, default False)
339
341
  - Used in a tool script service loop, return `-1` rather than raising `ConfigError` if the config file is inaccessible
340
342
 
343
+ `prereload_callback` (function, default None)
344
+ - Allows user services to be managed (paused/terminated) before the config is reloaded and logging is reset.
341
345
 
342
346
  ### Returns
343
347
  - `1` if the config files WAS reloaded
@@ -470,9 +474,12 @@ a ConfigError if the config file cannot be accessed.
470
474
  if self.config_timestamp == current_timestamp:
471
475
  return 0 # 0 indicates that the config file was NOT (re)loaded
472
476
 
473
- # It's an initial load call, or config file has changed. Do (re)load.
477
+ # It's an initial load call, or config file has changed, or force_flush_reload... Do (re)load
474
478
  self.config_timestamp = current_timestamp
475
479
  logging.getLogger().setLevel(ldcfg_ll) # Set logging level for remainder of loadconfig call
480
+ if prereload_callback:
481
+ logging.debug("Pre-reload callback user function called")
482
+ prereload_callback()
476
483
  logging.info (f"Config <{self.config_file}> file timestamp: {current_timestamp}")
477
484
 
478
485
  if flush_on_reload:
@@ -541,13 +548,13 @@ flush_on_reload, force_flush_reload, and tolerate_missing.
541
548
 
542
549
 
543
550
  ### Parameters
544
- `str_blob`
551
+ `str_blob` (str)
545
552
  - String containing the lines of config data
546
553
 
547
- `ldcfg_ll` (default 30/WARNING)
554
+ `ldcfg_ll` (int, default 30 (WARNING))
548
555
  - Logging level used within `read_string()` code for debugging read_string() itself
549
556
 
550
- `isimport` (default False)
557
+ `isimport` (bool, default False)
551
558
  - Internally set True when handling imports. Not used by tool script calls.
552
559
 
553
560
 
@@ -627,10 +634,10 @@ flush_on_reload, force_flush_reload, and tolerate_missing.
627
634
  Loaded content is added to and/or modifies any previously loaded content.
628
635
 
629
636
  ### Parameters
630
- `param_dict`
637
+ `param_dict` (dict)
631
638
  - dictionary to be loaded
632
639
 
633
- `section_name` (default '' - top level)
640
+ `section_name` (str, default '' (top level))
634
641
  - section to load the param_dict into.
635
642
  - The section will be created if not yet existing.
636
643
  - Content can only be loaded into one section per call to read_dict().
@@ -713,18 +720,18 @@ This can lead to cleaner tool script code. Either access method may be used, al
713
720
 
714
721
 
715
722
  ### Parameters
716
- `param`
723
+ `param` (str)
717
724
  - String name of param to be fetched from cfg
718
725
 
719
- `fallback` (default None)
726
+ `fallback` (as-expected type, default None)
720
727
  - if provided, is returned if `param` does not exist in cfg
721
728
 
722
- `types` (default '[]' empty list)
729
+ `types` (single or list of as-expected types, default '[]' (any type accepted))
723
730
  - if provided, a ConfigError is raised if the param's value type is not in the list of expected types
724
731
  - `types` may be a single type (eg, `types=int`) or a list of types (eg, `types=[int, float]`)
725
732
  - Supported types: [str, int, float, bool, list, tuple, dict]
726
733
 
727
- `section` (default '' - top-level)
734
+ `section` (str, default '' (top-level))
728
735
  - Select the section from which to get the param value.
729
736
 
730
737
 
@@ -803,22 +810,22 @@ reload call to avoid multiple config reloads.
803
810
 
804
811
 
805
812
  ### Parameters
806
- `param` (default ' ')
813
+ `param` (str, default ' ')
807
814
  - The param name, if modifying an existing param or adding a new param
808
815
 
809
- `value` (default ' ')
816
+ `value` (as-expected type, default ' ')
810
817
  - The new value to be applied to an existing param, or an added param
811
818
  - Any comment text (after a '#') in the new value will be prepended to any existing comment text
812
819
 
813
- `remove` (default False)
820
+ `remove` (bool, default False)
814
821
  - If True, the `param` config file line is removed from the config file
815
822
 
816
- `add_if_not_existing` (default False)
823
+ `add_if_not_existing` (bool, default False)
817
824
  - Modify an existing param line, or add at the bottom of the config file if it is not existing
818
825
  - To add a blank line leave out both `param` and `value`, or set both the `""`
819
826
  - To add a comment line specify the comment in the `param` field (eg, `my_config.modify_configfile("# My comment")`)
820
827
 
821
- `save` (default False)
828
+ `save` (bool, default False)
822
829
  - Write the modified config file content back to the file
823
830
  - `save=True` may be specified on the last modification call or an a standalone call.
824
831
 
@@ -893,8 +900,8 @@ reload call to avoid multiple config reloads.
893
900
 
894
901
  ### Parameter
895
902
 
896
- `savefile`
897
- - Path to the output file. Path or str type.
903
+ `savefile` (Path or str)
904
+ - Path to the output file.
898
905
  - The config data will be written to an absolute path, or relative to the `core.tool.config_dir`
899
906
 
900
907
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  #==========================================================
6
6
  #
7
- # Chris Nelson, 2018-2023
7
+ # Chris Nelson, 2018-2024
8
8
  #
9
9
  # TODO Identification of the main module / tool script file may be wrong if a script imports a script that then imports cjnfuncs.
10
10
  #==========================================================
@@ -87,8 +87,8 @@ found then user-specific is assumed. No directories are created.
87
87
 
88
88
 
89
89
  ### Parameter
90
- `toolname`
91
- - Name of the tool, type str
90
+ `toolname` (str)
91
+ - Name of the tool
92
92
 
93
93
 
94
94
  ### Returns
@@ -208,25 +208,25 @@ the log file declared in the config file:
208
208
 
209
209
 
210
210
  ### Parameters
211
- `call_logfile` (default None)
211
+ `call_logfile` (str, default None)
212
212
  - Potential log file passed typically from the tool script. Selected by `call_logfile_wins = True`.
213
213
  call_logfile may be an absolute path or relative to the `core.tool.log_dir_base` directory.
214
214
  - `None` specifies the console.
215
215
 
216
- `call_logfile_wins` (default False)
216
+ `call_logfile_wins` (bool, default False)
217
217
  - If True, the `call_logfile` is selected. If False, the `config_logfile` is selected.
218
218
 
219
- `config_logfile` (default None)
219
+ `config_logfile` (str, default None)
220
220
  - Potential log file passed typically from loadconfig() if there is a `LogFile` param in the
221
221
  loaded config. Selected by `call_logfile_wins = False`.
222
222
  config_logfile may be an absolute path or relative to the `core.tool.log_dir_base` directory.
223
223
  - `None` specifies the console.
224
224
 
225
- `ConsoleLogFormat` (default None)
225
+ `ConsoleLogFormat` (str, default None)
226
226
  - Overrides the default console logging format: `{module:>15}.{funcName:20} - {levelname:>8}: {message}`.
227
227
  - loadconfig() passes `ConsoleLogFormat` from the primary config file, if defined.
228
228
 
229
- `FileLogFormat` (default None)
229
+ `FileLogFormat` (str, default None)
230
230
  - Overrides the default file logging format: `{asctime} {module:>15}.{funcName:20} {levelname:>8}: {message}`.
231
231
  - loadconfig() passes `FileLogFormat` from the primary config file, if defined.
232
232
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  #==========================================================
6
6
  #
7
- # Chris Nelson, 2018-2023
7
+ # Chris Nelson, 2018-2024
8
8
  #
9
9
  #==========================================================
10
10
 
@@ -44,7 +44,7 @@ Distribution files and directory trees are hosted in `<module_root>/deployment_f
44
44
 
45
45
 
46
46
  ### Parameters
47
- `files_list`
47
+ `files_list` (list of dictionaries)
48
48
  - A list of dictionaries, each specifying a `source` file or directory tree to be copied to a `target_dir`.
49
49
  - `source` - Either an individual file or directory tree within and relative to `<module_root>/deployment_files/`.
50
50
  No wildcard support.
@@ -56,11 +56,11 @@ Distribution files and directory trees are hosted in `<module_root>/deployment_f
56
56
  - `file_stat` - Permissions set on each created file (default 0o664)
57
57
  - `dir_stat` - Permissions set on each created directory (if not already existing, default 0o775)
58
58
 
59
- `overwrite`
59
+ `overwrite` (bool, default False)
60
60
  - If overwrite=False (default) then only missing files will be copied. If overwrite=True then all files will be overwritten
61
61
  if they exist - data may be lost!
62
62
 
63
- `missing_ok`
63
+ `missing_ok` (bool, default False)
64
64
  - If missing_ok=True then a missing source file or directory is tolerated (non-fatal). This feature is used for testing.
65
65
 
66
66
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  #==========================================================
6
6
  #
7
- # Chris Nelson, 2018-2023
7
+ # Chris Nelson, 2018-2024
8
8
  #
9
9
  #==========================================================
10
10
 
@@ -32,19 +32,21 @@ User (`~user/`) and environment vars (`$HOME/`) are supported and expanded.
32
32
 
33
33
 
34
34
  ### Parameters
35
- `in_path` (default '')
35
+ `in_path` (Path or str, default '')
36
36
  - An absolute or relative path to a file or directory, such as `mydir/myfile.txt`
37
- - If `in_path` is an absolute path then `base_path` is disregarded.
37
+ - If `in_path` is an absolute path then the `base_path` is disregarded.
38
+ - If `in_path` starts with `./` then the absolute path to the current working directory (cwd) is prepended
39
+ to `in_path`, and the `base_path` is disregarded. See Special handling note, below.
38
40
 
39
- `base_path` (default '')
41
+ `base_path` (Path or str, default '')
40
42
  - An absolute or relative path to a directory, such as `~/.config/mytool`
41
43
  - `base_path` is prepended to `in_path` if `in_path` is a relative path
42
44
  - `base_path = ''` (the default) results in a relative path based on the shell current working directory (cwd)
43
45
  - `base_path = '.'` results in an absolute path based on the shell cwd
44
46
  - `base_path = core.tool.main_dir` results in an absolute path based on the tool script directory
45
47
 
46
- `mkdir`
47
- - Force-make a full directory path. `in_path` / `base_path` is understood to be to a directory.
48
+ `mkdir` (bool, default False)
49
+ - Force-make a full directory path. `base_path` / `in_path` is understood to be to a directory.
48
50
 
49
51
 
50
52
  ### Returns
@@ -69,21 +71,40 @@ Attribute | Type | Description
69
71
  - If `in_path` is a relative path (eg, `mydir/myfile.txt`) portion then the `base_path` is prepended.
70
72
  - If both `in_path` and `base_path` are relative then the combined path will also be relative, usually to
71
73
  the shell cwd.
72
- - If `in_path` is an absolute path (eg, `/tmp/mydir/myfile.txt`) then the `base_path` is ignored.
74
+ - If `in_path` is an absolute path (eg, `/tmp/mydir/myfile.txt`) then the `base_path` is disregarded.
75
+ - **Special handling for `in_path` starting with `./`:** Normally, paths starting with `.` are relative paths.
76
+ mungePath interprets `in_path` starting with `./` as an absolute path reference to the shell current working
77
+ directory (cwd).
78
+ Often in a tool script a user path input is passed to the `in_path` parameter. Using the `./` prefix, a file in
79
+ the shell cwd may be
80
+ referenced, eg `./myfile`. _Covering the cases, assuming the shell cwd is `/home/me`:_
81
+
82
+ in_path | base_path | .full_path resolves to
83
+ -- | -- | --
84
+ myfile | /tmp | /tmp/myfile
85
+ ./myfile | /tmp | /home/me/myfile
86
+ ../myfile | /tmp | /tmp/../myfile
87
+ ./../myfile | /tmp | /home/me/../myfile
88
+ xyz/myfile | /tmp | /tmp/xyz/myfile
89
+ ./xyz/myfile | /tmp | /home/me/xyz/myfile
90
+
73
91
  - `in_path` and `base_path` may be type str(), Path(), or PurePath().
74
92
  - Symlinks are followed (not resolved).
75
93
  - User and environment vars are expanded, eg `~/.config` >> `/home/me/.config`, as does `$HOME/.config`.
76
94
  - The `.parent` is the directory containing (above) the `.full_path`. If the object `.is_file` then `.parent` is the
77
95
  directory containing the file. If the object `.is_dir` then the `.full_path` includes the end-point directory, and
78
96
  `.parent` is the directory above the end-point directory.
79
- - When using `mkdir=True` the combined `in_path` / `base_path` is understood to be a directory path (not
97
+ - When using `mkdir=True` the combined `base_path` / `in_path` is understood to be a directory path (not
80
98
  to a file), and will be created if it does not already exist. (Uses `pathlib.Path.mkdir()`). A FileExistsError
81
99
  is raised if you attempt to mkdir on top of an existing file.
82
100
  - See [GitHub repo](https://github.com/cjnaz/cjnfuncs) tests/demo-mungePath.py for numerous application examples.
83
101
  """
84
102
 
85
- self.in_path = str(in_path)
86
- self.base_path = str(base_path)
103
+ in_path = str(in_path)
104
+ base_path = str(base_path)
105
+
106
+ if in_path.startswith('./'):
107
+ in_path = Path.cwd() / in_path
87
108
 
88
109
  in_path_pp = PurePath(os.path.expandvars(os.path.expanduser(str(in_path))))
89
110
 
@@ -96,24 +117,12 @@ is raised if you attempt to mkdir on top of an existing file.
96
117
 
97
118
  if mkdir:
98
119
  Path(in_path_pp).mkdir(parents=True, exist_ok=True)
99
- # try:
100
- # Path(in_path_pp).mkdir(parents=True, exist_ok=True)
101
- # except Exception as e:
102
- # raise FileExistsError (e)
103
120
 
104
121
  self.parent = Path(in_path_pp.parent)
105
122
  self.full_path = Path(in_path_pp)
106
123
 
107
124
  self.name = self.full_path.name
108
- self.exists = check_path_exists(self.full_path)
109
- self.is_absolute = self.full_path.is_absolute()
110
- self.is_relative = not self.is_absolute
111
- try:
112
- self.is_dir = self.full_path.is_dir()
113
- self.is_file = self.full_path.is_file()
114
- except: # Trap if the path does not exist
115
- self.is_dir = False
116
- self.is_file = False
125
+ self.refresh_stats()
117
126
 
118
127
 
119
128
  #=====================================================================================
@@ -166,7 +175,7 @@ happen on the filesystem. Call refresh_stats() as needed.
166
175
  #=====================================================================================
167
176
  #=====================================================================================
168
177
 
169
- def check_path_exists(path, timeout=1):
178
+ def check_path_exists(inpath, timeout=1):
170
179
  """
171
180
  ## check_path_exists (path, timeout=1) - With enforced timeout (no hang)
172
181
 
@@ -177,10 +186,10 @@ Implementation stolen from https://stackoverflow.com/questions/67819869/how-to-e
177
186
 
178
187
 
179
188
  ### Parameters
180
- `path`
181
- - A pathlib.Path or str type
189
+ `path` (Path or str)
190
+ - Path to a file or directory
182
191
 
183
- `timeout` (default 1 second)
192
+ `timeout` (int or float, default 1 second)
184
193
  - resolution seconds
185
194
 
186
195
 
@@ -188,12 +197,11 @@ Implementation stolen from https://stackoverflow.com/questions/67819869/how-to-e
188
197
  - True if the path exists
189
198
  - False if the path does not exist or the timeout is reached
190
199
  """
191
- path = Path(path)
192
- executor = ThreadPoolExecutor(max_workers=1)
193
- future = executor.submit(path.exists)
194
- try:
195
- return future.result(timeout)
196
- except TimeoutError:
197
- return False
198
-
199
200
 
201
+ _path = Path(inpath)
202
+ with ThreadPoolExecutor(max_workers=1) as executor:
203
+ future = executor.submit(_path.exists)
204
+ try:
205
+ return future.result(timeout)
206
+ except TimeoutError:
207
+ return False
@@ -4,7 +4,7 @@
4
4
 
5
5
  #==========================================================
6
6
  #
7
- # Chris Nelson, Copyright 2023
7
+ # Chris Nelson, Copyright 2024
8
8
  #
9
9
  #==========================================================
10
10
 
@@ -60,8 +60,8 @@ currently 0 (indicating locked), so it is ***recommended*** to have (possibly ex
60
60
  such as in your interrupt-trapped cleanup code.
61
61
 
62
62
  ### Parameters
63
- `lockname`
64
- - All processes sharing the given resource must use the same lockname.
63
+ `lockname` (str)
64
+ - All processes sharing a given resource must use the same lockname.
65
65
  """
66
66
 
67
67
  def __init__ (self, lockname):
@@ -78,28 +78,36 @@ such as in your interrupt-trapped cleanup code.
78
78
  #=====================================================================================
79
79
  #=====================================================================================
80
80
 
81
- def get_lock(self, timeout=1):
81
+ def get_lock(self, timeout=1, same_process_ok=False):
82
82
  """
83
- ## get_lock (timeout=1) - Request the resource lock
83
+ ## get_lock (timeout=1, same_process_ok=False) - Request the resource lock
84
84
 
85
85
  ***resource_lock() class member function***
86
86
 
87
87
  Attempt to acquire/get the lock while waiting up to `timeout` time.
88
88
 
89
- If the lock was previously acquired by this script (process) then get_lock() immediately returns True.
90
- This allows the script code to not have to track state to decide if the lock has
91
- previously been acquired before calling get_lock() again, leading to cleaner code.
89
+ By default, get_lock() waits for the lock if it is currently set, whether the lock was set by this
90
+ or another script/job/process.
91
+
92
+ By setting `same_process_ok=True`, then if the lock was previously acquired by this same script/process
93
+ then get_lock() immediately returns True. This allows the script code to not have to track state to
94
+ decide if the lock has previously been acquired before calling get_lock() again, leading to cleaner code.
92
95
 
93
96
  ### Parameters
94
- `timeout` (default 1 second)
97
+ `timeout` (int or float, default 1 second)
95
98
  - The max time, in seconds, to wait to acquire the lock
96
99
  - None is no timeout - wait forever (Hang forever. Unwise.)
97
100
 
101
+ `same_process_ok` (bool, default False)
102
+ - If True, then if the current process currently has the lock then get_lock() immediately returns True.
103
+ - If False, then if the lock is currently set by the same process or another process then get_lock() blocks
104
+ with timeout.
105
+
98
106
  ### Returns
99
107
  - True: Lock successfully acquired, timeout time not exceeded
100
108
  - False: Lock request failed, timed out
101
109
  """
102
- if self.I_have_the_lock == True:
110
+ if same_process_ok and self.I_have_the_lock == True:
103
111
  return True
104
112
 
105
113
  try:
@@ -131,7 +139,7 @@ in the same unset state.
131
139
  unless `force=True`.
132
140
 
133
141
  ### Parameter
134
- `force` (default False)
142
+ `force` (bool, default False)
135
143
  - Release the lock regardless of whether or not this process acquired it.
136
144
  - Useful for forced cleanup, for example, by the CLI interface.
137
145
  - Dangerous if another process had acquired the lock. Be careful.
@@ -4,7 +4,7 @@
4
4
 
5
5
  #==========================================================
6
6
  #
7
- # Chris Nelson, 2018-2023
7
+ # Chris Nelson, 2018-2024
8
8
  #
9
9
  #==========================================================
10
10
 
@@ -27,8 +27,8 @@ Supported timevalue units are 's'econds, 'm'inutes, 'h'ours, 'd'ays, and 'w'eeks
27
27
 
28
28
 
29
29
  ### Parameters
30
- `orig_val`
31
- - The original, passed-in value of type str, int, or float
30
+ `orig_val` (str, int, or float)
31
+ - The original, passed-in value
32
32
 
33
33
 
34
34
  ### Returns
@@ -101,10 +101,10 @@ def retime(time_sec, unitC):
101
101
 
102
102
 
103
103
  ### Parameters
104
- `time_sec`
105
- - Time value in resolution seconds, type int or float.
104
+ `time_sec` (int or float)
105
+ - The time value in resolution seconds to be converted
106
106
 
107
- `unitC`
107
+ `unitC` (str)
108
108
  - Target time resolution: "s", "m", "h", "d", or "w" (case insensitive)
109
109
 
110
110
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cjnfuncs
3
- Version: 2.1
3
+ Version: 2.3
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
@@ -31,12 +31,13 @@ Description-Content-Type: text/markdown
31
31
  License-File: LICENSE.txt
32
32
  Requires-Dist: requests
33
33
  Requires-Dist: appdirs>=1.4
34
+ Requires-Dist: dkimpy
34
35
  Requires-Dist: importlib_resources
35
36
  Requires-Dist: posix-ipc>=1.1.1
36
37
 
37
38
  # cjnfuncs - A framework and collection of utility functions for script writing
38
39
 
39
- ## cjnfuncs is comprised of several modules (links to respective documentation)
40
+ ## cjnfuncs is comprised of several modules (follow links to respective documentation)
40
41
 
41
42
  NOTE: Since relative links to other .md files do not work on PyPI, please go to the [cjnfuncs GitHub repo](https://github.com/cjnaz/cjnfuncs) to read the documentation.
42
43
 
@@ -45,13 +46,13 @@ module | Description/Purpose
45
46
  [core](core.md) | Set up the base environment
46
47
  [configman](configman.md) | Feature-rich configuration file toolset
47
48
  [timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes)
48
- [mungePath](mungePath.md) | Ease-of-use pathlib extenstion for constructing and manipulating file paths
49
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
49
50
  [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
50
51
  [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
51
52
  [SMTP](SMTP.md) | Send notification and email messages
52
53
 
53
54
  Developed and tested on Python 3.6.8, and supported on all higher Python versions.
54
- Developed on Linux, supported also on Windows (tested on Windows 10).
55
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
55
56
 
56
57
  In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
57
58
 
@@ -74,6 +75,11 @@ Project repo: https://github.com/cjnaz/cjnfuncs
74
75
  <br/>
75
76
 
76
77
  ## Revision history
78
+ - 2.3 240821 - Added mungePath ./ support.
79
+ Resolved check_path_exists() memory leak.
80
+ Added `same_process_ok` to resourcelock.getlock()
81
+ Added prereload_callback to config_item.loadconfig()
82
+ - 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
77
83
  - 2.1 240104 - Partitioned to separate modules.
78
84
  Added modify_configfile.
79
85
  Added native support for float, list, tuple, and dict in loadconfig().
@@ -1,4 +1,5 @@
1
1
  requests
2
2
  appdirs>=1.4
3
+ dkimpy
3
4
  importlib_resources
4
5
  posix-ipc>=1.1.1
File without changes
File without changes
File without changes