alienpy 1.6.3__tar.gz → 1.6.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.
Files changed (29) hide show
  1. {alienpy-1.6.3 → alienpy-1.6.4}/PKG-INFO +14 -2
  2. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/alien.py +2 -1
  3. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/connect_ssl.py +123 -76
  4. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/global_vars.py +3 -0
  5. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/tools_nowb.py +22 -3
  6. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/tools_shell.py +2 -1
  7. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/version.py +3 -3
  8. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/wb_api.py +50 -22
  9. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/wb_async.py +35 -20
  10. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/xrd_core.py +259 -139
  11. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy.egg-info/PKG-INFO +14 -2
  12. {alienpy-1.6.3 → alienpy-1.6.4}/setup.py +3 -0
  13. {alienpy-1.6.3 → alienpy-1.6.4}/LICENSE +0 -0
  14. {alienpy-1.6.3 → alienpy-1.6.4}/README.md +0 -0
  15. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/__init__.py +0 -0
  16. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/async_tools.py +0 -0
  17. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/data_structs.py +0 -0
  18. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/setup_cwd.py +0 -0
  19. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/setup_logging.py +0 -0
  20. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/tools_history.py +0 -0
  21. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/tools_stackcmd.py +0 -0
  22. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy/xrd_tools.py +0 -0
  23. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy.egg-info/SOURCES.txt +0 -0
  24. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy.egg-info/dependency_links.txt +0 -0
  25. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy.egg-info/entry_points.txt +0 -0
  26. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy.egg-info/requires.txt +0 -0
  27. {alienpy-1.6.3 → alienpy-1.6.4}/alienpy.egg-info/top_level.txt +0 -0
  28. {alienpy-1.6.3 → alienpy-1.6.4}/examples/alien_wbtime +0 -0
  29. {alienpy-1.6.3 → alienpy-1.6.4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: alienpy
3
- Version: 1.6.3
3
+ Version: 1.6.4
4
4
  Summary: Websocket based cli interface for ALICE experiment GRID infrastructure
5
5
  Home-page: https://gitlab.cern.ch/jalien/xjalienfs
6
6
  Author: Adrian Sevcenco
@@ -23,6 +23,18 @@ Requires-Dist: rich
23
23
  Requires-Dist: requests
24
24
  Requires-Dist: websockets
25
25
  Requires-Dist: xrootd
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: description-content-type
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license-file
34
+ Dynamic: project-url
35
+ Dynamic: requires-dist
36
+ Dynamic: requires-python
37
+ Dynamic: summary
26
38
 
27
39
  ![PyPI](https://img.shields.io/pypi/v/alienpy?style=plastic)
28
40
 
@@ -84,6 +84,8 @@ if HAS_XROOTD:
84
84
 
85
85
  session_id = None # variable used to keep a session ID
86
86
 
87
+ os.setpgrp() # https://linux.die.net/man/2/setpgrp
88
+
87
89
  ##################################
88
90
  # START FUNCTIONS DEFINITIONS
89
91
  ##################################
@@ -195,7 +197,6 @@ def DO_path_stack(wb: WebSocketClientProtocol, cmd: str = '', args: Union[str, l
195
197
 
196
198
  def DO_version(args: Optional[list] = None) -> RET: # pylint: disable=unused-argument
197
199
  """Print version information"""
198
- del args
199
200
  stdout = (f'alien.py version: {ALIENPY_VERSION_STR}\n'
200
201
  f'alien.py version date: {ALIENPY_VERSION_DATE}\n'
201
202
  f'alien.py version hash: {ALIENPY_VERSION_HASH}\n'
@@ -1,25 +1,20 @@
1
1
  """alienpy:: SSL and certificate tooling"""
2
2
 
3
+ import datetime
3
4
  import sys
4
5
  import os
5
6
  import logging
6
7
  import uuid
7
- import traceback
8
- import datetime
9
8
  import tempfile
10
- import warnings
11
- with warnings.catch_warnings():
12
- warnings.simplefilter("ignore")
13
- try:
14
- import cryptography # noqa: F401
15
- except Exception:
16
- print("cryptography module could not be imported! Make sure you can do:\npython3 -c 'import cryptography'", file = sys.stderr, flush = True)
17
- sys.exit(1)
9
+ # import glob
10
+ import ssl
11
+
18
12
  try:
19
- import ssl
13
+ from cryptography import x509
20
14
  except Exception:
21
- print("Python ssl module could not be imported! Make sure you can do:\npython3 -c 'import ssl'", file = sys.stderr, flush = True)
15
+ print("cryptography module could not be imported! Make sure you can do:\npython3 -c 'import cryptography'", file = sys.stderr, flush = True)
22
16
  sys.exit(1)
17
+
23
18
  try:
24
19
  import OpenSSL
25
20
  except Exception:
@@ -109,27 +104,28 @@ def get_ca_path() -> str:
109
104
 
110
105
  def IsValidCert(fname: str) -> bool:
111
106
  """Check if the certificate file (argument) is present and valid. It will return false also for less than 5min of validity"""
107
+ cert_bytes = None
112
108
  try:
113
- with open(fname, encoding="ascii", errors="replace") as f:
114
- cert_bytes = f.read()
115
- except Exception:
109
+ with open(fname, "rb") as f: cert_bytes = f.read()
110
+ except Exception as e:
111
+ logging.exception(e)
116
112
  logging.error('IsValidCert:: Unable to open certificate file %s', fname)
117
113
  return False
118
114
 
119
115
  try:
120
- x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_bytes) # type: ignore[attr-defined]
121
- except Exception:
116
+ x509cert = x509.load_pem_x509_certificate(cert_bytes)
117
+ except Exception as e:
118
+ logging.exception(e)
122
119
  logging.error('IsValidCert:: Unable to load certificate %s', fname)
123
120
  return False
124
121
 
125
- x509_notafter = x509.get_notAfter()
126
- utc_time = datetime.datetime.strptime(x509_notafter.decode("utf-8"), "%Y%m%d%H%M%SZ")
127
- time_notafter = int((utc_time - datetime.datetime(1970, 1, 1)).total_seconds())
128
- time_current = int(datetime.datetime.now().timestamp())
129
- time_remaining = time_notafter - time_current
130
- if time_remaining < 1:
131
- logging.error('IsValidCert:: Expired certificate %s', fname)
132
- return time_remaining > 300
122
+ time_remaining = int(x509cert.not_valid_after_utc.timestamp()) - int(datetime.datetime.now(datetime.timezone.utc).timestamp())
123
+
124
+ if time_remaining < 600:
125
+ msg = f'IsValidCert:: Expired certificate {fname}'
126
+ if DEBUG: print_err(msg)
127
+ logging.error(msg)
128
+ return time_remaining >= 600
133
129
 
134
130
 
135
131
  def get_valid_certs() -> tuple:
@@ -192,10 +188,6 @@ def renewCredFilesInfo() -> CertsInfo:
192
188
  return CertsInfo(user_cert, user_key, token_cert, token_key)
193
189
 
194
190
 
195
- # Populate information in AlienSessionInfo
196
- _ = renewCredFilesInfo()
197
-
198
-
199
191
  def create_ssl_context(use_usercert: bool = False, user_cert: str = '', user_key: str = '', token_cert: str = '', token_key: str = '') -> ssl.SSLContext:
200
192
  """Create SSL context using either the default names for user certificate and token certificate or X509_USER_{CERT,KEY} JALIEN_TOKEN_{CERT,KEY} environment variables"""
201
193
  if use_usercert or not token_cert:
@@ -215,26 +207,28 @@ def create_ssl_context(use_usercert: bool = False, user_cert: str = '', user_key
215
207
  ctx.verify_mode = ssl.CERT_REQUIRED # CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
216
208
  ctx.check_hostname = False
217
209
 
218
- ca_verify_location = get_ca_path()
210
+ # ca_verify_location = get_ca_path()
219
211
  cafile = capath = None
220
- if os.path.isfile(ca_verify_location):
221
- cafile = ca_verify_location
212
+ if os.path.isfile(CA_PATH):
213
+ cafile = CA_PATH
222
214
  else:
223
- capath = ca_verify_location
215
+ capath = CA_PATH
224
216
 
225
- if DEBUG: logging.debug('SSL context:: Loading verify location:\n%s', ca_verify_location)
217
+ if DEBUG: logging.debug('SSL context:: Loading verify location:\n%s', CA_PATH)
226
218
  try:
227
219
  ctx.load_verify_locations(cafile = cafile, capath = capath)
228
- except Exception:
220
+ except Exception as e:
229
221
  logging.exception('Could not load verify location!!!\n')
230
- print_err(f'Verify location could not be loaded!!! check content of >>> {ca_verify_location} <<< and the log')
222
+ logging.exception(e)
223
+ print_err(f'Verify location could not be loaded!!! check content of >>> {CA_PATH} <<< and the log')
231
224
  return None # EIO /* I/O error */
232
225
 
233
226
  if DEBUG: logging.debug('SSL context:: Loading cert,key pair:\n%s\n%s', cert, key)
234
227
  try:
235
228
  ctx.load_cert_chain(certfile = cert, keyfile = key)
236
- except Exception:
229
+ except Exception as e:
237
230
  logging.exception('Could not load certificates!!!\n')
231
+ logging.exception(e)
238
232
  print_err(f'Error loading certificate pair!! Check the content of {DEBUG_FILE}')
239
233
  return None # EIO /* I/O error */
240
234
 
@@ -244,78 +238,122 @@ def create_ssl_context(use_usercert: bool = False, user_cert: str = '', user_key
244
238
 
245
239
  def CertInfo(fname: str) -> RET:
246
240
  """Print certificate information (subject, issuer, notbefore, notafter)"""
241
+ cert_bytes = None
247
242
  try:
248
- with open(fname, encoding = "ascii", errors = "replace") as f:
249
- cert_bytes = f.read()
250
- except Exception:
243
+ with open(fname, "rb") as f: cert_bytes = f.read()
244
+ except Exception as e:
245
+ logging.exception(e)
251
246
  return RET(2, '', f'File >>>{fname}<<< not found') # ENOENT /* No such file or directory */
252
247
 
253
248
  try:
254
- x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_bytes)
255
- except Exception:
249
+ x509cert = x509.load_pem_x509_certificate(cert_bytes)
250
+ except Exception as e:
251
+ logging.exception(e)
256
252
  return RET(5, '', f'Could not load certificate >>>{fname}<<<') # EIO /* I/O error */
257
253
 
258
- utc_time_notafter = datetime.datetime.strptime(x509.get_notAfter().decode("utf-8"), "%Y%m%d%H%M%SZ")
259
- utc_time_notbefore = datetime.datetime.strptime(x509.get_notBefore().decode("utf-8"), "%Y%m%d%H%M%SZ")
260
- issuer = '/'.join([f'{k.decode("utf-8")}={v.decode("utf-8")}' for k, v in x509.get_issuer().get_components()])
261
- subject = '/'.join([f'{k.decode("utf-8")}={v.decode("utf-8")}' for k, v in x509.get_subject().get_components()])
254
+ utc_time_notafter = x509cert.not_valid_after_utc.strftime("%Y-%m-%d %H:%M:%S")
255
+ utc_time_notbefore = x509cert.not_valid_before_utc.strftime("%Y-%m-%d %H:%M:%S")
256
+
257
+ issuer_comp_list = x509cert.issuer.rfc4514_string().split(',')
258
+ issuer_comp_list.reverse()
259
+ issuer = '/'.join(issuer_comp_list)
260
+
261
+ subject_comp_list = x509cert.subject.rfc4514_string().split(',')
262
+ subject_comp_list.reverse()
263
+ subject = '/'.join(subject_comp_list)
264
+
262
265
  info = f'DN >>> {subject}\nISSUER >>> {issuer}\nBEGIN >>> {utc_time_notbefore}\nEXPIRE >>> {utc_time_notafter}'
263
266
  return RET(0, info)
264
267
 
265
268
 
269
+ ##############################################################################################
270
+ # def CertVerify_v2(fname: str) -> RET:
271
+ # """Print certificate information (subject, issuer, notbefore, notafter)"""
272
+ # cert_bytes = None
273
+ # try:
274
+ # with open(fname, "rb") as f: cert_bytes = f.read()
275
+ # except Exception:
276
+ # return RET(2, "", f"File >>>{fname}<<< not found") # ENOENT /* No such file or directory */
277
+ #
278
+ # try:
279
+ # x509cert = x509.load_pem_x509_certificate(cert_bytes)
280
+ # except Exception:
281
+ # logging.debug(traceback.format_exc())
282
+ # return RET(5, "", f"Could not load certificate >>>{fname}<<<") # EIO /* I/O error */
283
+ #
284
+ # ca_pem_list = glob.glob(f'{CA_PATH}/*.pem')
285
+ # ca_list_bytes = bytearray()
286
+ # for ca in ca_pem_list:
287
+ # try:
288
+ # with open(ca, "rb") as f: ca_list_bytes += f.read()
289
+ # except Exception:
290
+ # pass
291
+ # ca_list_x509 = x509.load_pem_x509_certificates(bytes(ca_list_bytes))
292
+ #
293
+ # ca_store = x509.verification.Store(ca_list_x509)
294
+ # builder = x509.verification.PolicyBuilder().store(ca_store).time(datetime.datetime.now())
295
+ # verifier = builder.build_client_verifier()
296
+ # verified_client = verifier.verify(x509cert, ca_list_x509)
297
+ #
298
+ # from rich.pretty import pprint
299
+ # pprint(verified_client)
300
+ ##############################################################################################
301
+
302
+
266
303
  def CertVerify(fname: str) -> RET:
267
304
  """Print certificate information (subject, issuer, notbefore, notafter)"""
268
305
  try:
269
- with open(fname, encoding="ascii", errors="replace") as f:
270
- cert_bytes = f.read()
271
- except Exception:
306
+ with open(fname, "rb") as f: cert_bytes = f.read()
307
+ except Exception as e:
308
+ logging.exception(e)
272
309
  return RET(2, "", f"File >>>{fname}<<< not found") # ENOENT /* No such file or directory */
273
310
 
274
311
  try:
275
- x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_bytes)
276
- except Exception:
277
- logging.debug(traceback.format_exc())
312
+ x509cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_bytes)
313
+ except Exception as e:
314
+ logging.exception(e)
278
315
  return RET(5, "", f"Could not load certificate >>>{fname}<<<") # EIO /* I/O error */
279
316
 
280
317
  x509store = OpenSSL.crypto.X509Store()
281
318
  x509store.set_flags(OpenSSL.crypto.X509StoreFlags.ALLOW_PROXY_CERTS)
282
319
 
283
- ca_verify_location = get_ca_path()
284
320
  cafile = capath = None
285
- if os.path.isfile(ca_verify_location):
286
- cafile = ca_verify_location
321
+ if os.path.isfile(CA_PATH):
322
+ cafile = CA_PATH
287
323
  else:
288
- capath = ca_verify_location
324
+ capath = CA_PATH
289
325
 
290
326
  try:
291
327
  x509store.load_locations(cafile = cafile, capath = capath)
292
- except Exception:
293
- logging.debug(traceback.format_exc())
294
- return RET(5, "", f"Could not load verify location >>>{ca_verify_location}<<<") # EIO /* I/O error */
328
+ except Exception as e:
329
+ logging.exception(e)
330
+ return RET(5, "", f"Could not load verify location >>>{CA_PATH}<<<") # EIO /* I/O error */
295
331
 
296
- store_ctx = OpenSSL.crypto.X509StoreContext(x509store, x509)
332
+ store_ctx = OpenSSL.crypto.X509StoreContext(x509store, x509cert)
297
333
  try:
298
334
  store_ctx.verify_certificate()
299
335
  return RET(0, f'SSL Verification {PrintColor(COLORS.BIGreen)}succesful{PrintColor(COLORS.ColorReset)} for {fname}')
300
- except Exception:
301
- logging.debug(traceback.format_exc())
336
+ except Exception as e:
337
+ logging.exception(e)
302
338
  return RET(1, '', f'SSL Verification {PrintColor(COLORS.BIRed)}failed{PrintColor(COLORS.ColorReset)} for {fname}')
303
339
 
304
340
 
305
341
  def CertKeyMatch(cert_fname: str, key_fname: str) -> RET:
306
342
  """Check if Certificate and key match"""
343
+ cert_bytes = None
307
344
  try:
308
- with open(cert_fname, encoding="ascii", errors="replace") as f: cert_bytes = f.read()
345
+ with open(cert_fname, "rb") as f: cert_bytes = f.read()
309
346
  x509cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_bytes)
310
- except Exception:
311
- logging.debug(traceback.format_exc())
347
+ except Exception as e:
348
+ logging.exception(e)
312
349
  return RET(5, "", f'Could not load certificate >>>{cert_fname}<<<') # EIO /* I/O error */
313
350
 
351
+ key_bytes = None
314
352
  try:
315
- with open(key_fname, encoding="ascii", errors="replace") as g: key_bytes = g.read()
353
+ with open(key_fname, "rb") as g: key_bytes = g.read()
316
354
  x509key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, key_bytes)
317
- except Exception:
318
- logging.debug(traceback.format_exc())
355
+ except Exception as e:
356
+ logging.exception(e)
319
357
  return RET(5, "", f'Could not load key >>>{key_fname}<<<') # EIO /* I/O error */
320
358
 
321
359
  ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD) # skipcq: PTC-W6001
@@ -323,24 +361,33 @@ def CertKeyMatch(cert_fname: str, key_fname: str) -> RET:
323
361
  ctx.use_privatekey(x509key)
324
362
  ctx.use_certificate(x509cert)
325
363
 
326
- ca_verify_location = get_ca_path()
327
364
  cafile = capath = None
328
- if os.path.isfile(ca_verify_location):
329
- cafile = ca_verify_location
365
+ if os.path.isfile(CA_PATH):
366
+ cafile = CA_PATH
330
367
  else:
331
- capath = ca_verify_location
368
+ capath = CA_PATH
332
369
 
333
370
  try:
334
371
  ctx.load_verify_locations(cafile = cafile, capath = capath)
335
- except Exception:
336
- logging.debug(traceback.format_exc())
337
- return RET(5, "", f"Could not load verify location >>>{ca_verify_location}<<<") # EIO /* I/O error */
372
+ except Exception as e:
373
+ logging.exception(e)
374
+ return RET(5, "", f"Could not load verify location >>>{CA_PATH}<<<") # EIO /* I/O error */
338
375
 
339
376
  try:
340
377
  ctx.check_privatekey()
341
378
  return RET(0, f'Cert/key {PrintColor(COLORS.BIGreen)}match{PrintColor(COLORS.ColorReset)}')
342
379
  except OpenSSL.SSL.Error:
343
- return RET(0, '', f'Cert/key {PrintColor(COLORS.BIRed)}DO NOT match{PrintColor(COLORS.ColorReset)}')
380
+ return RET(42, '', f'Cert/key {PrintColor(COLORS.BIRed)}DO NOT match{PrintColor(COLORS.ColorReset)}')
381
+ except Exception as e:
382
+ logging.exception(e)
383
+ return RET(1, '', 'Cert/key match :: unknown error')
384
+
385
+
386
+ # HAVE A GLOBAL CA_PATH
387
+ CA_PATH = get_ca_path()
388
+
389
+ # Populate information in AlienSessionInfo
390
+ _ = renewCredFilesInfo()
344
391
 
345
392
 
346
393
  if __name__ == '__main__':
@@ -1,6 +1,7 @@
1
1
  """alienpy:: GLOBALS"""
2
2
 
3
3
  import os
4
+ import platform
4
5
  import re
5
6
  import sys
6
7
  from socket import gethostname
@@ -42,6 +43,8 @@ USER_HOME = Path.home().as_posix()
42
43
 
43
44
  HOSTNAME = gethostname()
44
45
 
46
+ UNAME = platform.uname()
47
+ PLATFORM_ID = f'{UNAME.machine}/{UNAME.system}/{UNAME.release}'
45
48
 
46
49
  def get_certs_names() -> CertsInfo:
47
50
  """Provide the standard file names for used certificates"""
@@ -20,6 +20,7 @@ import urllib.request as urlreq
20
20
  import shutil
21
21
  import shlex
22
22
  import sys
23
+ import signal
23
24
  import xml.etree.ElementTree as ET # noqa: N817
24
25
  import xml.dom.minidom as MD # noqa: N812
25
26
 
@@ -45,8 +46,14 @@ def exit_message(code: int = 0, msg: str = '') -> None:
45
46
 
46
47
  def signal_handler(sig, frame) -> None: # pylint: disable=unused-argument
47
48
  """Generig signal handler: just print the signal and exit"""
48
- print_out(f"\nCought signal {sig}, let\'s exit")
49
- exit_message(int(AlienSessionInfo['exitcode']))
49
+ # https://stackoverflow.com/a/79497818/624734
50
+ signal.signal(signalnum = sig, handler = signal.SIG_IGN)
51
+
52
+ print_out(f"\nCaught signal {sig}, let\'s exit")
53
+
54
+ # Send signal to all processes in the group
55
+ os.killpg(0, sig)
56
+ os._exit(int(AlienSessionInfo['exitcode']))
50
57
 
51
58
 
52
59
  def is_float(arg: Union[str, float, None]) -> bool:
@@ -374,7 +381,11 @@ def get_arg_multiple(target: list, item: str) -> list:
374
381
 
375
382
  def uid2name(uid: Union[str, int]) -> str:
376
383
  """Convert numeric UID to username"""
377
- return pwd.getpwuid(int(uid)).pw_name
384
+ try:
385
+ user_info = pwd.getpwuid(int(uid))
386
+ return user_info.pw_name
387
+ except Exception:
388
+ return str(uid)
378
389
 
379
390
 
380
391
  def gid2name(gid: Union[str, int]) -> str:
@@ -628,6 +639,14 @@ def get_hash_meta(meta_fn: str) -> tuple:
628
639
  return (content.getAttribute('type'), content.firstChild.nodeValue) if content else (None, None)
629
640
 
630
641
 
642
+ def get_url_meta(meta_fn: str) -> list:
643
+ """Extract url list from metafile"""
644
+ if 'meta4?' in meta_fn: meta_fn, _, _ = meta_fn.partition('?')
645
+ if not os.path.isfile(meta_fn): return ('', '')
646
+ element_list = MD.parse(meta_fn).documentElement.getElementsByTagName('url')
647
+ return [item.firstChild.nodeValue for item in element_list if item]
648
+
649
+
631
650
  def md5(input_file: str) -> str:
632
651
  """Compute the md5 digest of the specified file"""
633
652
  if not path_readable(input_file): return '-1'
@@ -17,10 +17,11 @@ def runShellCMD(INPUT: str = '', captureout: bool = True, do_shell: bool = False
17
17
  sh_cmd = re.sub(r'^!', '', INPUT)
18
18
  args = sh_cmd if do_shell else shlex.split(sh_cmd)
19
19
  capture_args = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE} if captureout else {}
20
+ if timeout: timeout = int(timeout)
20
21
  status = exitcode = except_msg = None
21
22
  msg_out = msg_err = ''
22
23
  try:
23
- status = subprocess.run(args, encoding = 'utf-8', errors = 'replace', shell = do_shell, **capture_args) # pylint: disable=subprocess-run-check # nosec
24
+ status = subprocess.run(args, encoding = 'utf-8', errors = 'replace', shell = do_shell, timeout = timeout, **capture_args) # pylint: disable=subprocess-run-check # nosec
24
25
  except subprocess.TimeoutExpired:
25
26
  print_err(f"Expired timeout: {timeout} for: {sh_cmd}")
26
27
  exitcode = int(62)
@@ -2,9 +2,9 @@
2
2
 
3
3
  import sys
4
4
 
5
- ALIENPY_VERSION_HASH = '6ff8a18'
6
- ALIENPY_VERSION_DATE = '20240904_063643'
7
- ALIENPY_VERSION_STR = '1.6.3'
5
+ ALIENPY_VERSION_HASH = '4d25210'
6
+ ALIENPY_VERSION_DATE = '20250409_173142'
7
+ ALIENPY_VERSION_STR = '1.6.4'
8
8
 
9
9
  if __name__ == '__main__':
10
10
  print('This file should not be executed!', file = sys.stderr, flush = True)
@@ -31,18 +31,18 @@ def wb_create_tryout(host: str, port: Union[str, int], path: str = '/', use_user
31
31
  """WebSocket creation with tryouts (configurable by env ALIENPY_CONNECT_TRIES and ALIENPY_CONNECT_TRIES_INTERVAL)"""
32
32
  wb = None
33
33
  nr_tries = 0
34
- init_begin = None
35
-
36
- if TIME_CONNECT or DEBUG: init_begin = time.perf_counter()
37
34
  connect_tries = int(os.getenv('ALIENPY_CONNECT_TRIES', '3'))
38
35
  connect_tries_interval = float(os.getenv('ALIENPY_CONNECT_TRIES_INTERVAL', '0.5'))
39
36
 
37
+ init_begin = time.perf_counter() if (TIME_CONNECT or DEBUG) else None
40
38
  while wb is None:
41
39
  nr_tries += 1
40
+
42
41
  try:
43
- wb = wb_create(host, str(port), path, use_usercert, localConnect)
42
+ wb = wb_create(host, port, path, use_usercert, localConnect)
44
43
  except Exception:
45
44
  logging.exception('wb_create_tryout:: exception when wb_create')
45
+
46
46
  if not wb:
47
47
  if nr_tries >= connect_tries:
48
48
  logging.error('We tried on %s:%s%s %s times', host, port, path, nr_tries)
@@ -55,9 +55,9 @@ def wb_create_tryout(host: str, port: Union[str, int], path: str = '/', use_user
55
55
  if DEBUG: logging.debug(msg)
56
56
  if TIME_CONNECT: print_out(msg)
57
57
 
58
- if wb and localConnect:
59
- pid_filename = f'{TMPDIR}/jboxpy_{os.getuid()}.pid'
60
- writePidFile(pid_filename)
58
+ # if local proxy process (a la JBox - but WIP)
59
+ if localConnect and wb: writePidFile(f'{TMPDIR}/jboxpy_{os.getuid()}.pid')
60
+
61
61
  return wb
62
62
 
63
63
 
@@ -66,33 +66,61 @@ def AlienConnect(wb: Optional[WebSocketClientProtocol] = None, token_args: Optio
66
66
  if not token_args: token_args = []
67
67
  init_begin = time.perf_counter() if (TIME_CONNECT or DEBUG) else None
68
68
 
69
- jalien_server = os.getenv("ALIENPY_JCENTRAL", 'alice-jcentral.cern.ch') # default value for JCENTRAL
70
- jalien_websocket_port = os.getenv("ALIENPY_JCENTRAL_PORT", '8097') # websocket port
69
+ SRV_DEFAULT = 'alice-jcentral.cern.ch'
70
+ PORT_DEFAULT = '8097'
71
+
72
+ jalien_server = os.getenv('ALIENPY_JCENTRAL', SRV_DEFAULT) # default value for JCENTRAL
73
+ jalien_websocket_port = os.getenv('ALIENPY_JCENTRAL_PORT', PORT_DEFAULT) # websocket port
71
74
  jalien_websocket_path = '/websocket/json'
72
75
  jclient_env = f'{TMPDIR}/jclient_token_{str(os.getuid())}'
73
76
 
77
+ # Prepare usage of destination specified by JBox env vars instead of jclient_token_
78
+ JALIEN_HOST_ENV = os.getenv('JALIEN_HOST', 'localhost')
79
+ JALIEN_WSPORT_ENV = os.getenv('JALIEN_WSPORT', PORT_DEFAULT)
80
+
74
81
  # If presentent with existing socket, let's try to close it
75
- if wb: _ = wb_close(wb, code = 1000, reason = 'Close previous websocket')
82
+ if wb:
83
+ _ = wb_close(wb, code = 1000, reason = 'Close previous websocket')
84
+ wb = None
76
85
 
77
86
  # let's try to get a websocket
78
87
  if localConnect:
79
88
  wb = wb_create(localConnect = True)
80
89
  else:
81
- if not os.getenv("ALIENPY_JCENTRAL") and os.path.exists(jclient_env): # If user defined ALIENPY_JCENTRAL the intent is to set and use the endpoint
82
- # lets check JBOX availability
83
- jalien_info = read_conf_file(jclient_env)
84
- if jalien_info and 'JALIEN_PID' in jalien_info and is_my_pid(jalien_info['JALIEN_PID']):
85
- jbox_host = jalien_info.get('JALIEN_HOST', 'localhost')
86
- jbox_port = jalien_info.get('JALIEN_WSPORT', '8097')
87
- if isReachable(jbox_host, jbox_port):
88
- jalien_server, jalien_websocket_port = jbox_host, jbox_port
90
+ # First try the JBox connection details, first env vars then jclient_token_ file
91
+ # N.B.!! ALIENPY_JCENTRAL env var have exclusive priority !! is present then the intent is to use the _THIS_ endpoint
92
+ if not os.getenv("ALIENPY_JCENTRAL"):
93
+ # we found env var JALIEN_HOST
94
+ if JALIEN_HOST_ENV:
95
+ if isReachable(JALIEN_HOST_ENV, JALIEN_WSPORT_ENV):
96
+ jalien_server, jalien_websocket_port = JALIEN_HOST_ENV, JALIEN_WSPORT_ENV
89
97
  logging.warning('AlienConnect:: JBox connection to %s:%s', jalien_server, jalien_websocket_port)
98
+ wb = wb_create_tryout(jalien_server, jalien_websocket_port, jalien_websocket_path, use_usercert)
99
+
100
+ # if either no JBox env vars or the wb creation failed let's check jalien_token_ file
101
+ if wb is None and os.path.exists(jclient_env):
102
+ jalien_info = read_conf_file(jclient_env)
103
+ if jalien_info and 'JALIEN_PID' in jalien_info and is_my_pid(jalien_info['JALIEN_PID']):
104
+ jbox_host = jalien_info.get('JALIEN_HOST', 'localhost')
105
+ jbox_port = jalien_info.get('JALIEN_WSPORT', PORT_DEFAULT)
106
+ if isReachable(jbox_host, jbox_port):
107
+ jalien_server, jalien_websocket_port = jbox_host, jbox_port
108
+ logging.warning('AlienConnect:: JBox connection to %s:%s', jalien_server, jalien_websocket_port)
109
+ wb = wb_create_tryout(jalien_server, jalien_websocket_port, jalien_websocket_path, use_usercert)
110
+
111
+ if wb is None: # Either ALIENPY_JCENTRAL set or no wb so far
112
+ wb = wb_create_tryout(jalien_server, jalien_websocket_port, jalien_websocket_path, use_usercert)
90
113
 
91
- wb = wb_create_tryout(jalien_server, str(jalien_websocket_port), jalien_websocket_path, use_usercert)
114
+ # if ALIENPY_JCENTRAL is specified but no connection, treat this as hard error and exit
115
+ if wb is None and os.getenv("ALIENPY_JCENTRAL"):
116
+ msg = f'Check the logfile: {DEBUG_FILE}\nCould not connect to user specified ALIENPY_JCENTRAL: {jalien_server}:{jalien_websocket_port}\n'
117
+ logging.error(msg)
118
+ print_err(msg)
119
+ sys.exit(107) # ENOTCONN - Transport endpoint is not connected
92
120
 
93
- # if we stil do not have a socket, then try to fallback to jcentral if we did not had explicit endpoint and jcentral was not already tried
94
- if wb is None and not os.getenv("ALIENPY_JCENTRAL") and jalien_server != 'alice-jcentral.cern.ch':
95
- jalien_server, jalien_websocket_port = 'alice-jcentral.cern.ch', '8097'
121
+ # if we stil do not have a socket, then try to fallback to jcentral if not already tried
122
+ if wb is None and jalien_server != SRV_DEFAULT:
123
+ jalien_server, jalien_websocket_port = SRV_DEFAULT, PORT_DEFAULT
96
124
  wb = wb_create_tryout(jalien_server, jalien_websocket_port, jalien_websocket_path, use_usercert)
97
125
 
98
126
  if init_begin: