forked from localstack/localstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
2138 lines (1697 loc) · 68.4 KB
/
common.py
File metadata and controls
2138 lines (1697 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import binascii
import decimal
import functools
import glob
import hashlib
import inspect
import io
import itertools
import json
import logging
import os
import platform
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import uuid
import zipfile
from datetime import date, datetime, timezone, tzinfo
from json import JSONDecodeError
from multiprocessing.dummy import Pool
from queue import Queue
from typing import Any, Callable, Dict, List, Optional, Sized, Tuple, Type, Union
from urllib.parse import parse_qs, urlparse
import cachetools
import requests
from requests import Response
from requests.models import CaseInsensitiveDict
import localstack.utils.run
from localstack import config
from localstack.config import DEFAULT_ENCODING
from localstack.constants import ENV_DEV
from localstack.utils.generic.number_utils import format_number, is_number
# TODO: remove imports from here (need to update any client code that imports these from utils.common)
from localstack.utils.generic.wait_utils import poll_condition, retry # noqa
# TODO: remove imports from here (need to update any client code that imports these from utils.common)
from localstack.utils.net_utils import ( # noqa
get_free_tcp_port,
is_ip_address,
is_ipv4_address,
is_port_open,
port_can_be_bound,
resolve_hostname,
wait_for_port_closed,
wait_for_port_open,
wait_for_port_status,
)
from localstack.utils.run import FuncThread
# set up logger
LOG = logging.getLogger(__name__)
# arrays for temporary files and resources
TMP_FILES = []
TMP_THREADS = []
TMP_PROCESSES = []
# cache clean variables
CACHE_CLEAN_TIMEOUT = 60 * 5
CACHE_MAX_AGE = 60 * 60
CACHE_FILE_PATTERN = os.path.join(tempfile.gettempdir(), "_random_dir_", "cache.*.json")
last_cache_clean_time = {"time": 0}
MUTEX_CLEAN = threading.Lock()
# misc. constants
TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S"
TIMESTAMP_FORMAT_TZ = "%Y-%m-%dT%H:%M:%SZ"
TIMESTAMP_FORMAT_MICROS = "%Y-%m-%dT%H:%M:%S.%fZ"
CODEC_HANDLER_UNDERSCORE = "underscore"
# chunk size for file downloads
DOWNLOAD_CHUNK_SIZE = 1024 * 1024
# flag to indicate whether we've received and processed the stop signal
INFRA_STOPPED = False
# generic cache object
CACHE = {}
# lock for creating certificate files
SSL_CERT_LOCK = threading.RLock()
# markers that indicate the start/end of sections in PEM cert files
PEM_CERT_START = "-----BEGIN CERTIFICATE-----"
PEM_CERT_END = "-----END CERTIFICATE-----"
PEM_KEY_START_REGEX = r"-----BEGIN(.*)PRIVATE KEY-----"
PEM_KEY_END_REGEX = r"-----END(.*)PRIVATE KEY-----"
# regular expression for unprintable characters
# Based on https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html
# #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF
_unprintables = (
range(0x00, 0x09),
range(0x0A, 0x0A),
range(0x0B, 0x0D),
range(0x0E, 0x20),
range(0xD800, 0xE000),
range(0xFFFE, 0x10000),
)
REGEX_UNPRINTABLE_CHARS = re.compile(
f"[{re.escape(''.join(map(chr, itertools.chain(*_unprintables))))}]"
)
# user of the currently running process
CACHED_USER = None
# type definitions for JSON-serializable objects
JsonComplexType = Union[Dict, List]
JsonType = Union[JsonComplexType, str, int, float, bool, None]
SerializableObj = JsonType
class Mock(object):
"""Dummy class that can be used for mocking custom attributes."""
pass
class CustomEncoder(json.JSONEncoder):
"""Helper class to convert JSON documents with datetime, decimals, or bytes."""
def default(self, o):
import yaml # leave import here, to avoid breaking our Lambda tests!
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
if isinstance(o, (datetime, date)):
return timestamp_millis(o)
if isinstance(o, yaml.ScalarNode):
if o.tag == "tag:yaml.org,2002:int":
return int(o.value)
if o.tag == "tag:yaml.org,2002:float":
return float(o.value)
if o.tag == "tag:yaml.org,2002:bool":
return bool(o.value)
return str(o.value)
try:
if isinstance(o, bytes):
return to_str(o)
return super(CustomEncoder, self).default(o)
except Exception:
return None
class ShellCommandThread(FuncThread):
"""Helper class to run a shell command in a background thread."""
def __init__(
self,
cmd: Union[str, List[str]],
params: Any = None,
outfile: Union[str, int] = None,
env_vars: Dict[str, str] = None,
stdin: bool = False,
auto_restart: bool = False,
quiet: bool = True,
inherit_cwd: bool = False,
inherit_env: bool = True,
log_listener: Callable = None,
stop_listener: Callable = None,
strip_color: bool = False,
):
params = not_none_or(params, {})
env_vars = not_none_or(env_vars, {})
self.stopped = False
self.cmd = cmd
self.process = None
self.outfile = outfile
self.stdin = stdin
self.env_vars = env_vars
self.inherit_cwd = inherit_cwd
self.inherit_env = inherit_env
self.auto_restart = auto_restart
self.log_listener = log_listener
self.stop_listener = stop_listener
self.strip_color = strip_color
self.started = threading.Event()
FuncThread.__init__(self, self.run_cmd, params, quiet=quiet)
def run_cmd(self, params):
while True:
self.do_run_cmd()
if (
INFRA_STOPPED
or not self.auto_restart
or not self.process
or self.process.returncode == 0
):
return self.process.returncode if self.process else None
LOG.info(
"Restarting process (received exit code %s): %s", self.process.returncode, self.cmd
)
def do_run_cmd(self):
def convert_line(line):
line = to_str(line or "")
if self.strip_color:
# strip color codes
line = re.sub(r"\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))", "", line)
return "%s\r\n" % line.strip()
def filter_line(line):
"""Return True if this line should be filtered, i.e., not printed"""
return "(Press CTRL+C to quit)" in line
outfile = self.outfile or os.devnull
if self.log_listener and outfile == os.devnull:
outfile = subprocess.PIPE
try:
self.process = run(
self.cmd,
asynchronous=True,
stdin=self.stdin,
outfile=outfile,
env_vars=self.env_vars,
inherit_cwd=self.inherit_cwd,
inherit_env=self.inherit_env,
)
self.started.set()
if outfile:
if outfile == subprocess.PIPE:
# get stdout/stderr from child process and write to parent output
streams = (
(self.process.stdout, sys.stdout),
(self.process.stderr, sys.stderr),
)
for instream, outstream in streams:
if not instream:
continue
for line in iter(instream.readline, None):
# `line` should contain a newline at the end as we're iterating,
# hence we can safely break the loop if `line` is None or empty string
if line in [None, "", b""]:
break
if not (line and line.strip()) and self.is_killed():
break
line = convert_line(line)
if filter_line(line):
continue
if self.log_listener:
self.log_listener(line, stream=instream)
if self.outfile not in [None, os.devnull]:
outstream.write(line)
outstream.flush()
if self.process:
self.process.wait()
else:
self.process.communicate()
except Exception as e:
self.result_future.set_exception(e)
if self.process and not self.quiet:
LOG.warning('Shell command error "%s": %s', e, self.cmd)
if self.process and not self.quiet and self.process.returncode != 0:
LOG.warning('Shell command exit code "%s": %s', self.process.returncode, self.cmd)
def is_killed(self):
if not self.process:
return True
if INFRA_STOPPED:
return True
# Note: Do NOT import "psutil" at the root scope, as this leads
# to problems when importing this file from our test Lambdas in Docker
# (Error: libc.musl-x86_64.so.1: cannot open shared object file)
import psutil
return not psutil.pid_exists(self.process.pid)
def stop(self, quiet=False):
if self.stopped:
return
if not self.process:
LOG.warning("No process found for command '%s'", self.cmd)
return
parent_pid = self.process.pid
try:
kill_process_tree(parent_pid)
self.process = None
except Exception as e:
if not quiet:
LOG.warning("Unable to kill process with pid %s: %s", parent_pid, e)
try:
self.stop_listener and self.stop_listener(self)
except Exception as e:
if not quiet:
LOG.warning("Unable to run stop handler for shell command thread %s: %s", self, e)
self.stopped = True
class JsonObject(object):
"""Generic JSON serializable object for simplified subclassing"""
def to_json(self, indent=None):
return json.dumps(
self,
default=lambda o: (
(float(o) if o % 1 > 0 else int(o))
if isinstance(o, decimal.Decimal)
else o.__dict__
),
sort_keys=True,
indent=indent,
)
def apply_json(self, j):
if isinstance(j, str):
j = json.loads(j)
self.__dict__.update(j)
def to_dict(self):
return json.loads(self.to_json())
@classmethod
def from_json(cls, j):
j = JsonObject.as_dict(j)
result = cls()
result.apply_json(j)
return result
@classmethod
def from_json_list(cls, json_list):
return [cls.from_json(j) for j in json_list]
@classmethod
def as_dict(cls, obj):
if isinstance(obj, dict):
return obj
return obj.to_dict()
def __str__(self):
return self.to_json()
def __repr__(self):
return self.__str__()
class DelSafeDict(dict):
"""Useful when applying jsonpatch. Use it as follows:
obj.__dict__ = DelSafeDict(obj.__dict__)
apply_patch(obj.__dict__, patch)
"""
def __delitem__(self, key, *args, **kwargs):
self[key] = None
class CaptureOutput(object):
"""A context manager that captures stdout/stderr of the current thread. Use it as follows:
with CaptureOutput() as c:
...
print(c.stdout(), c.stderr())
"""
orig_stdout = sys.stdout
orig_stderr = sys.stderr
orig___stdout = sys.__stdout__
orig___stderr = sys.__stderr__
CONTEXTS_BY_THREAD = {}
class LogStreamIO(io.StringIO):
def write(self, s):
if isinstance(s, str) and hasattr(s, "decode"):
s = s.decode("unicode-escape")
return super(CaptureOutput.LogStreamIO, self).write(s)
def __init__(self):
self._stdout = self.LogStreamIO()
self._stderr = self.LogStreamIO()
def __enter__(self):
# Note: import werkzeug here (not at top of file) to allow dependency pruning
from werkzeug.local import LocalProxy
ident = self._ident()
if ident not in self.CONTEXTS_BY_THREAD:
self.CONTEXTS_BY_THREAD[ident] = self
self._set(
LocalProxy(self._proxy(sys.stdout, "stdout")),
LocalProxy(self._proxy(sys.stderr, "stderr")),
LocalProxy(self._proxy(sys.__stdout__, "stdout")),
LocalProxy(self._proxy(sys.__stderr__, "stderr")),
)
return self
def __exit__(self, type, value, traceback):
ident = self._ident()
removed = self.CONTEXTS_BY_THREAD.pop(ident, None)
if not self.CONTEXTS_BY_THREAD:
# reset pointers
self._set(
self.orig_stdout,
self.orig_stderr,
self.orig___stdout,
self.orig___stderr,
)
# get value from streams
removed._stdout.flush()
removed._stderr.flush()
out = removed._stdout.getvalue()
err = removed._stderr.getvalue()
# close handles
removed._stdout.close()
removed._stderr.close()
removed._stdout = out
removed._stderr = err
def _set(self, out, err, __out, __err):
sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__ = (
out,
err,
__out,
__err,
)
def _proxy(self, original_stream, type):
def proxy():
ident = self._ident()
ctx = self.CONTEXTS_BY_THREAD.get(ident)
if ctx:
return ctx._stdout if type == "stdout" else ctx._stderr
return original_stream
return proxy
def _ident(self):
# TODO: On some systems we seem to be running into a stack overflow with LAMBDA_EXECUTOR=local here!
return threading.current_thread().ident
def stdout(self):
return self._stream_value(self._stdout)
def stderr(self):
return self._stream_value(self._stderr)
def _stream_value(self, stream):
return stream.getvalue() if hasattr(stream, "getvalue") else stream
class ObjectIdHashComparator:
"""Simple wrapper class that allows us to create a hashset using the object id(..) as the entries' hash value"""
def __init__(self, obj):
self.obj = obj
self._hash = id(obj)
def __hash__(self):
return self._hash
def __eq__(self, other):
# assumption here is that we're comparing only against ObjectIdHash instances!
return self.obj == other.obj
class ArbitraryAccessObj:
"""Dummy object that can be arbitrarily accessed - any attributes, as a callable, item assignment, ..."""
def __init__(self, name=None):
self.name = name
def __getattr__(self, name, *args, **kwargs):
return ArbitraryAccessObj(name)
def __call__(self, *args, **kwargs):
if self.name in ["items", "keys", "values"] and not args and not kwargs:
return []
return ArbitraryAccessObj()
def __getitem__(self, *args, **kwargs):
return ArbitraryAccessObj()
def __setitem__(self, *args, **kwargs):
return ArbitraryAccessObj()
class HashableList(list):
"""Hashable list class that can be used with dicts or hashsets."""
def __hash__(self):
result = 0
for i in self:
result += hash(i)
return result
class PaginatedList(list):
"""List which can be paginated and filtered. For usage in AWS APIs with paginated responses"""
DEFAULT_PAGE_SIZE = 50
def get_page(
self,
token_generator: Callable,
next_token: str = None,
page_size: int = None,
filter_function: Callable = None,
) -> (list, str):
if filter_function is not None:
result_list = list(filter(filter_function, self))
else:
result_list = self
if page_size is None:
page_size = self.DEFAULT_PAGE_SIZE
if len(result_list) <= page_size:
return result_list, None
start_idx = 0
try:
start_item = next(item for item in result_list if token_generator(item) == next_token)
start_idx = result_list.index(start_item)
except StopIteration:
pass
if start_idx + page_size <= len(result_list):
next_token = token_generator(result_list[start_idx + page_size])
else:
next_token = None
return result_list[start_idx : start_idx + page_size], next_token
class FileMappedDocument(dict):
"""A dictionary that is mapped to a json document on disk.
When the document is created, an attempt is made to load existing contents from disk. To load changes from
concurrent writes, run load(). To save and overwrite the current document on disk, run save().
"""
path: Union[str, os.PathLike]
def __init__(self, path: Union[str, os.PathLike], mode=0o664):
super().__init__()
self.path = path
self.mode = mode
self.load()
def load(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
raise IsADirectoryError
with open(self.path, "r") as fd:
self.update(json.load(fd))
def save(self):
if os.path.isdir(self.path):
raise IsADirectoryError
if not os.path.exists(self.path):
mkdir(os.path.dirname(self.path))
def opener(path, flags):
_fd = os.open(path, flags, self.mode)
os.chmod(path, mode=self.mode, follow_symlinks=True)
return _fd
with open(self.path, "w", opener=opener) as fd:
json.dump(self, fd)
class PortNotAvailableException(Exception):
"""Exception which indicates that the ExternalServicePortsManager could not reserve a port."""
pass
class ExternalServicePortsManager:
"""Manages the ports used for starting external services like ElasticSearch, OpenSearch,..."""
def __init__(self):
# cache for locally available ports (ports are reserved for a short period of a few seconds)
self._PORTS_CACHE = cachetools.TTLCache(maxsize=100, ttl=6)
self._PORTS_LOCK = threading.RLock()
def reserve_port(self, port: int = None) -> int:
"""
Reserves the given port (if it is still free). If the given port is None, it reserves a free port from the
configured port range for external services. If a port is given, it has to be within the configured
range of external services (i.e. in [config#EXTERNAL_SERVICE_PORTS_START, config#EXTERNAL_SERVICE_PORTS_END)).
:param port: explicit port to check or None if a random port from the configured range should be selected
:return: reserved, free port number (int)
:raises: PortNotAvailableException if the given port is outside the configured range, it is already bound or
reserved, or if the given port is none and there is no free port in the configured service range.
"""
ports_range = range(config.EXTERNAL_SERVICE_PORTS_START, config.EXTERNAL_SERVICE_PORTS_END)
if port is not None and port not in ports_range:
raise PortNotAvailableException(
f"The requested port ({port}) is not in the configured external "
f"service port range ({ports_range})."
)
with self._PORTS_LOCK:
if port is not None:
return self._check_port(port)
else:
for port_in_range in ports_range:
try:
return self._check_port(port_in_range)
except PortNotAvailableException:
# We ignore the fact that this single port is reserved, we just check the next one
pass
raise PortNotAvailableException(
"No free network ports available to start service instance (currently reserved: %s)",
list(self._PORTS_CACHE.keys()),
)
def _check_port(self, port: int) -> int:
"""Checks if the given port is currently not reserved and can be bound."""
if not self._PORTS_CACHE.get(port) and port_can_be_bound(port):
# reserve the port for a short period of time
self._PORTS_CACHE[port] = "__reserved__"
return port
else:
raise PortNotAvailableException(f"The given port ({port}) is already reserved.")
external_service_ports = ExternalServicePortsManager()
# ----------------
# UTILITY METHODS
# ----------------
def start_thread(method, *args, **kwargs) -> FuncThread:
"""Start the given method in a background thread, and add the thread to the TMP_THREADS shutdown hook"""
_shutdown_hook = kwargs.pop("_shutdown_hook", True)
thread = FuncThread(method, *args, **kwargs)
thread.start()
if _shutdown_hook:
TMP_THREADS.append(thread)
return thread
def start_worker_thread(method, *args, **kwargs):
return start_thread(method, *args, _shutdown_hook=False, **kwargs)
def empty_context_manager():
import contextlib
return contextlib.nullcontext()
def synchronized(lock=None):
"""
Synchronization decorator as described in
http://blog.dscpl.com.au/2014/01/the-missing-synchronized-decorator.html.
"""
def _decorator(wrapped):
@functools.wraps(wrapped)
def _wrapper(*args, **kwargs):
with lock:
return wrapped(*args, **kwargs)
return _wrapper
return _decorator
def prevent_stack_overflow(match_parameters=False):
"""Function decorator to protect a function from stack overflows -
raises an exception if a (potential) infinite recursion is detected."""
def _decorator(wrapped):
@functools.wraps(wrapped)
def func(*args, **kwargs):
def _matches(frame):
if frame.function != wrapped.__name__:
return False
frame = frame.frame
if not match_parameters:
return False
# construct dict of arguments this stack frame has been called with
prev_call_args = {
frame.f_code.co_varnames[i]: frame.f_locals[frame.f_code.co_varnames[i]]
for i in range(frame.f_code.co_argcount)
}
# construct dict of arguments the original function has been called with
sig = inspect.signature(wrapped)
this_call_args = dict(zip(sig.parameters.keys(), args))
this_call_args.update(kwargs)
return prev_call_args == this_call_args
matching_frames = [frame[2] for frame in inspect.stack(context=1) if _matches(frame)]
if matching_frames:
raise RecursionError("(Potential) infinite recursion detected")
return wrapped(*args, **kwargs)
return func
return _decorator
def is_string(s, include_unicode=True, exclude_binary=False):
if isinstance(s, bytes) and exclude_binary:
return False
if isinstance(s, str):
return True
if include_unicode and isinstance(s, str):
return True
return False
def is_string_or_bytes(s):
return is_string(s) or isinstance(s, str) or isinstance(s, bytes)
def is_base64(s):
regex = r"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
return is_string(s) and re.match(regex, s)
def md5(string: Union[str, bytes]) -> str:
m = hashlib.md5()
m.update(to_bytes(string))
return m.hexdigest()
def select_attributes(obj: Dict, attributes: List[str]) -> Dict:
"""Select a subset of attributes from the given dict (returns a copy)"""
attributes = attributes if is_list_or_tuple(attributes) else [attributes]
return {k: v for k, v in obj.items() if k in attributes}
def remove_attributes(obj: Dict, attributes: List[str], recursive: bool = False) -> Dict:
"""Remove a set of attributes from the given dict (in-place)"""
if recursive:
def _remove(o, **kwargs):
if isinstance(o, dict):
remove_attributes(o, attributes)
return o
return recurse_object(obj, _remove)
attributes = attributes if is_list_or_tuple(attributes) else [attributes]
for attr in attributes:
obj.pop(attr, None)
return obj
def rename_attributes(
obj: Dict, old_to_new_attributes: Dict[str, str], in_place: bool = False
) -> Dict:
"""Rename a set of attributes in the given dict object. Second parameter is a dict that maps old to
new attribute names. Default is to return a copy, but can also pass in_place=True."""
if not in_place:
obj = dict(obj)
for old_name, new_name in old_to_new_attributes.items():
if old_name in obj:
obj[new_name] = obj.pop(old_name)
return obj
def is_list_or_tuple(obj) -> bool:
return isinstance(obj, (list, tuple))
def ensure_list(obj: Any, wrap_none=False) -> List:
"""Wrap the given object in a list, or return the object itself if it already is a list."""
if obj is None and not wrap_none:
return obj
return obj if isinstance(obj, list) else [obj]
def in_docker() -> bool:
return config.in_docker()
def path_from_url(url: str) -> str:
return "/%s" % str(url).partition("://")[2].partition("/")[2] if "://" in url else url
def sleep_forever():
while True:
time.sleep(1)
def get_service_protocol():
return "https" if config.USE_SSL else "http"
def edge_ports_info():
if config.EDGE_PORT_HTTP:
result = "ports %s/%s" % (config.EDGE_PORT, config.EDGE_PORT_HTTP)
else:
result = "port %s" % config.EDGE_PORT
result = "%s %s" % (get_service_protocol(), result)
return result
def to_unique_items_list(inputs, comparator=None):
"""Return a list of unique items from the given input iterable.
The comparator(item1, item2) returns True/False or an int for comparison."""
def contained(item):
for r in result:
if comparator:
cmp_res = comparator(item, r)
if cmp_res is True or str(cmp_res) == "0":
return True
elif item == r:
return True
result = []
for it in inputs:
if not contained(it):
result.append(it)
return result
def timestamp(time=None, format: str = TIMESTAMP_FORMAT) -> str:
if not time:
time = datetime.utcnow()
if isinstance(time, (int, float)):
time = datetime.fromtimestamp(time)
return time.strftime(format)
def timestamp_millis(time=None) -> str:
microsecond_time = timestamp(time=time, format=TIMESTAMP_FORMAT_MICROS)
# truncating microseconds to milliseconds, while leaving the "Z" indicator
return microsecond_time[:-4] + microsecond_time[-1]
def epoch_timestamp() -> float:
return time.time()
def parse_timestamp(ts_str: str) -> datetime:
for ts_format in [TIMESTAMP_FORMAT, TIMESTAMP_FORMAT_TZ, TIMESTAMP_FORMAT_MICROS]:
try:
return datetime.strptime(ts_str, ts_format)
except ValueError:
pass
raise Exception("Unable to parse timestamp string with any known formats: %s" % ts_str)
def merge_recursive(source, destination, none_values=None, overwrite=False):
if none_values is None:
none_values = [None]
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge_recursive(value, node, none_values=none_values, overwrite=overwrite)
else:
if not isinstance(destination, (dict, CaseInsensitiveDict)):
LOG.warning(
"Destination for merging %s=%s is not dict: %s (%s)",
key,
value,
destination,
type(destination),
)
if overwrite or destination.get(key) in none_values:
destination[key] = value
return destination
def merge_dicts(*dicts, **kwargs):
"""Merge all dicts in `*dicts` into a single dict, and return the result. If any of the entries
in `*dicts` is None, and `default` is specified as keyword argument, then return `default`."""
result = {}
for d in dicts:
if d is None and "default" in kwargs:
return kwargs["default"]
if d:
result.update(d)
return result
def remove_none_values_from_dict(dict: Dict) -> Dict:
return {k: v for (k, v) in dict.items() if v is not None}
def recurse_object(obj: JsonType, func: Callable, path: str = "") -> Any:
"""Recursively apply `func` to `obj` (may be a list, dict, or other object)."""
obj = func(obj, path=path)
if isinstance(obj, list):
for i in range(len(obj)):
tmp_path = "%s[%s]" % (path or ".", i)
obj[i] = recurse_object(obj[i], func, tmp_path)
elif isinstance(obj, dict):
for k, v in obj.items():
tmp_path = "%s%s" % ((path + ".") if path else "", k)
obj[k] = recurse_object(v, func, tmp_path)
return obj
def keys_to_lower(obj: JsonComplexType, skip_children_of: List[str] = None) -> JsonComplexType:
"""Recursively changes all dict keys to first character lowercase. Skip children
of any elements whose names are contained in skip_children_of (e.g., ['Tags'])"""
skip_children_of = ensure_list(skip_children_of or [])
def fix_keys(o, path="", **kwargs):
if any(re.match(r"(^|.*\.)%s($|[.\[].*)" % k, path) for k in skip_children_of):
return o
if isinstance(o, dict):
for k, v in dict(o).items():
o.pop(k)
o[first_char_to_lower(k)] = v
return o
result = recurse_object(obj, fix_keys)
return result
_camel_to_snake_case_sub = re.compile("((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))")
def camel_to_snake_case(string: str) -> str:
return _camel_to_snake_case_sub.sub(r"_\1", string).replace("__", "_").lower()
def snake_to_camel_case(string: str, capitalize_first: bool = True) -> str:
components = string.split("_")
start_idx = 0 if capitalize_first else 1
components = [x.title() for x in components[start_idx:]]
return "".join(components)
def base64_to_hex(b64_string: str) -> bytes:
return binascii.hexlify(base64.b64decode(b64_string))
def obj_to_xml(obj: SerializableObj) -> str:
"""Return an XML representation of the given object (dict, list, or primitive).
Does NOT add a common root element if the given obj is a list.
Does NOT work for nested dict structures."""
if isinstance(obj, list):
return "".join([obj_to_xml(o) for o in obj])
if isinstance(obj, dict):
return "".join(["<{k}>{v}</{k}>".format(k=k, v=obj_to_xml(v)) for (k, v) in obj.items()])
return str(obj)
def strip_xmlns(obj: Any) -> Any:
"""Strip xmlns attributes from a dict returned by xmltodict.parse."""
if isinstance(obj, list):
return [strip_xmlns(item) for item in obj]
if isinstance(obj, dict):
# Remove xmlns attribute.
obj.pop("@xmlns", None)
if len(obj) == 1 and "#text" in obj:
# If the only remaining key is the #text key, elide the dict
# entirely, to match the structure that xmltodict.parse would have
# returned if the xmlns namespace hadn't been present.
return obj["#text"]
return {k: strip_xmlns(v) for k, v in obj.items()}
return obj
def now(millis: bool = False, tz: Optional[tzinfo] = None) -> int:
return mktime(datetime.now(tz=tz), millis=millis)
def now_utc(millis: bool = False) -> int:
return now(millis, timezone.utc)
def mktime(ts: datetime, millis: bool = False) -> int:
if millis:
return int(ts.timestamp() * 1000)
return int(ts.timestamp())
def mkdir(folder: str):
if not os.path.exists(folder):
os.makedirs(folder, exist_ok=True)
def is_empty_dir(directory: str, ignore_hidden: bool = False) -> bool:
"""Return whether the given directory contains any entries (files/folders), including hidden
entries whose name starts with a dot (.), unless ignore_hidden=True is passed."""
if not os.path.isdir(directory):
raise Exception(f"Path is not a directory: {directory}")
entries = os.listdir(directory)