-
-
Notifications
You must be signed in to change notification settings - Fork 710
/
utils.py
1964 lines (1589 loc) · 56.3 KB
/
utils.py
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
from __future__ import annotations
import asyncio
import contextlib
import contextvars
import functools
import importlib
import inspect
import json
import logging
import multiprocessing
import os
import pkgutil
import re
import socket
import sys
import tempfile
import threading
import warnings
import weakref
import xml.etree.ElementTree
from asyncio import TimeoutError
from collections import deque
from collections.abc import (
Awaitable,
Callable,
Collection,
Container,
Generator,
Iterator,
KeysView,
ValuesView,
)
from concurrent.futures import ( # noqa: F401
CancelledError,
Executor,
ThreadPoolExecutor,
)
from contextvars import ContextVar
from datetime import timedelta
from functools import wraps
from hashlib import md5
from importlib.util import cache_from_source
from pickle import PickleBuffer
from time import sleep
from types import ModuleType
from typing import TYPE_CHECKING
from typing import Any as AnyType
from typing import ClassVar, TypeVar, overload
import click
import psutil
import tblib.pickling_support
from distributed.compatibility import asyncio_run
from distributed.config import get_loop_factory
try:
import resource
except ImportError:
resource = None # type: ignore
import tlz as toolz
from tornado import gen
from tornado.ioloop import IOLoop
import dask
from dask import istask
from dask.utils import ensure_bytes as _ensure_bytes
from dask.utils import key_split
from dask.utils import parse_timedelta as _parse_timedelta
from dask.widgets import get_template
from distributed.compatibility import WINDOWS
from distributed.metrics import context_meter, monotonic, time
try:
from dask.context import thread_state
except ImportError:
thread_state = threading.local()
# For some reason this is required in python >= 3.9
if WINDOWS:
import multiprocessing.popen_spawn_win32
else:
import multiprocessing.popen_spawn_posix
logger = _logger = logging.getLogger(__name__)
if TYPE_CHECKING:
# TODO: import from typing (requires Python >=3.10)
from typing_extensions import ParamSpec
P = ParamSpec("P")
T = TypeVar("T")
no_default = "__no_default__"
_forkserver_preload_set = False
def get_mp_context():
"""Create a multiprocessing context
The context type is controlled by the
``distributed.worker.multiprocessing-method`` configuration key.
Returns
-------
multiprocessing.BaseContext
The multiprocessing context
Notes
-----
Repeated calls with the same method will return the same object
(since multiprocessing.get_context returns singleton instances).
"""
global _forkserver_preload_set
method = dask.config.get("distributed.worker.multiprocessing-method")
ctx = multiprocessing.get_context(method)
if method == "forkserver" and not _forkserver_preload_set:
# Makes the test suite much faster
preload = ["distributed"]
from distributed.versions import optional_packages, required_packages
for pkg, _ in required_packages + optional_packages:
try:
importlib.import_module(pkg)
except ImportError:
pass
else:
preload.append(pkg)
ctx.set_forkserver_preload(preload)
_forkserver_preload_set = True
return ctx
def has_arg(func, argname):
"""
Whether the function takes an argument with the given name.
"""
while True:
try:
argspec = inspect.getfullargspec(func)
if argname in set(argspec.args) | set(argspec.kwonlyargs):
return True
except TypeError:
break
try:
# For Tornado coroutines and other decorated functions
func = func.__wrapped__
except AttributeError:
break
return False
def get_fileno_limit():
"""
Get the maximum number of open files per process.
"""
if resource is not None:
return resource.getrlimit(resource.RLIMIT_NOFILE)[0]
else:
# Default ceiling for Windows when using the CRT, though it
# is settable using _setmaxstdio().
return 512
@toolz.memoize
def _get_ip(host, port, family):
# By using a UDP socket, we don't actually try to connect but
# simply select the local address through which *host* is reachable.
sock = socket.socket(family, socket.SOCK_DGRAM)
try:
sock.connect((host, port))
ip = sock.getsockname()[0]
return ip
except OSError as e:
warnings.warn(
"Couldn't detect a suitable IP address for "
"reaching %r, defaulting to hostname: %s" % (host, e),
RuntimeWarning,
)
addr_info = socket.getaddrinfo(
socket.gethostname(), port, family, socket.SOCK_DGRAM, socket.IPPROTO_UDP
)[0]
return addr_info[4][0]
finally:
sock.close()
def get_ip(host="8.8.8.8", port=80):
"""
Get the local IP address through which the *host* is reachable.
*host* defaults to a well-known Internet host (one of Google's public
DNS servers).
"""
return _get_ip(host, port, family=socket.AF_INET)
def get_ipv6(host="2001:4860:4860::8888", port=80):
"""
The same as get_ip(), but for IPv6.
"""
return _get_ip(host, port, family=socket.AF_INET6)
def get_ip_interface(ifname):
"""
Get the local IPv4 address of a network interface.
KeyError is raised if the interface doesn't exist.
ValueError is raised if the interface does no have an IPv4 address
associated with it.
"""
net_if_addrs = psutil.net_if_addrs()
if ifname not in net_if_addrs:
allowed_ifnames = list(net_if_addrs.keys())
raise ValueError(
"{!r} is not a valid network interface. "
"Valid network interfaces are: {}".format(ifname, allowed_ifnames)
)
for info in net_if_addrs[ifname]:
if info.family == socket.AF_INET:
return info.address
raise ValueError(f"interface {ifname!r} doesn't have an IPv4 address")
async def All(args, quiet_exceptions=()):
"""Wait on many tasks at the same time
Err once any of the tasks err.
See https://github.com/tornadoweb/tornado/issues/1546
Parameters
----------
args: futures to wait for
quiet_exceptions: tuple, Exception
Exception types to avoid logging if they fail
"""
tasks = gen.WaitIterator(*map(asyncio.ensure_future, args))
results = [None for _ in args]
while not tasks.done():
try:
result = await tasks.next()
except Exception:
@gen.coroutine
def quiet():
"""Watch unfinished tasks
Otherwise if they err they get logged in a way that is hard to
control. They need some other task to watch them so that they
are not orphaned
"""
for task in list(tasks._unfinished):
try:
yield task
except quiet_exceptions:
pass
quiet()
raise
results[tasks.current_index] = result
return results
async def Any(args, quiet_exceptions=()):
"""Wait on many tasks at the same time and return when any is finished
Err once any of the tasks err.
Parameters
----------
args: futures to wait for
quiet_exceptions: tuple, Exception
Exception types to avoid logging if they fail
"""
tasks = gen.WaitIterator(*map(asyncio.ensure_future, args))
results = [None for _ in args]
while not tasks.done():
try:
result = await tasks.next()
except Exception:
@gen.coroutine
def quiet():
"""Watch unfinished tasks
Otherwise if they err they get logged in a way that is hard to
control. They need some other task to watch them so that they
are not orphaned
"""
for task in list(tasks._unfinished):
try:
yield task
except quiet_exceptions:
pass
quiet()
raise
results[tasks.current_index] = result
break
return results
class NoOpAwaitable:
"""An awaitable object that always returns None.
Useful to return from a method that can be called in both asynchronous and
synchronous contexts"""
def __await__(self):
async def f():
return None
return f().__await__()
class SyncMethodMixin:
"""
A mixin for adding an `asynchronous` attribute and `sync` method to a class.
Subclasses must define a `loop` attribute for an associated
`tornado.IOLoop`, and may also add a `_asynchronous` attribute indicating
whether the class should default to asynchronous behavior.
"""
@property
def asynchronous(self):
"""Are we running in the event loop?"""
try:
return in_async_call(
self.loop, default=getattr(self, "_asynchronous", False)
)
except RuntimeError:
return False
def sync(self, func, *args, asynchronous=None, callback_timeout=None, **kwargs):
"""Call `func` with `args` synchronously or asynchronously depending on
the calling context"""
callback_timeout = _parse_timedelta(callback_timeout)
if asynchronous is None:
asynchronous = self.asynchronous
if asynchronous:
future = func(*args, **kwargs)
if callback_timeout is not None:
future = wait_for(future, callback_timeout)
return future
else:
return sync(
self.loop, func, *args, callback_timeout=callback_timeout, **kwargs
)
def in_async_call(loop, default=False):
"""Whether this call is currently within an async call"""
try:
return loop.asyncio_loop is asyncio.get_running_loop()
except RuntimeError:
# No *running* loop in thread. If the event loop isn't running, it
# _could_ be started later in this thread though. Return the default.
if not loop.asyncio_loop.is_running():
return default
return False
def sync(loop, func, *args, callback_timeout=None, **kwargs):
"""
Run coroutine in loop running in separate thread.
"""
callback_timeout = _parse_timedelta(callback_timeout, "s")
if loop.asyncio_loop.is_closed():
raise RuntimeError("IOLoop is closed")
e = threading.Event()
main_tid = threading.get_ident()
result = error = future = None # set up non-locals
@gen.coroutine
def f():
nonlocal result, error, future
try:
if main_tid == threading.get_ident():
raise RuntimeError("sync() called from thread of running loop")
yield gen.moment
future = func(*args, **kwargs)
if callback_timeout is not None:
future = wait_for(future, callback_timeout)
future = asyncio.ensure_future(future)
result = yield future
except Exception:
error = sys.exc_info()
finally:
e.set()
def cancel():
if future is not None:
future.cancel()
def wait(timeout):
try:
return e.wait(timeout)
except KeyboardInterrupt:
loop.add_callback(cancel)
raise
loop.add_callback(f)
if callback_timeout is not None:
if not wait(callback_timeout):
raise TimeoutError(f"timed out after {callback_timeout} s.")
else:
while not e.is_set():
wait(10)
if error:
typ, exc, tb = error
raise exc.with_traceback(tb)
else:
return result
if sys.version_info >= (3, 10):
from asyncio import Event as LateLoopEvent
else:
# In python 3.10 asyncio.Lock and other primitives no longer support
# passing a loop kwarg to bind to a loop running in another thread
# e.g. calling from Client(asynchronous=False). Instead the loop is bound
# as late as possible: when calling any methods that wait on or wake
# Future instances. See: https://bugs.python.org/issue42392
class LateLoopEvent:
_event: asyncio.Event | None
def __init__(self) -> None:
self._event = None
def set(self) -> None:
if self._event is None:
self._event = asyncio.Event()
self._event.set()
def is_set(self) -> bool:
return self._event is not None and self._event.is_set()
async def wait(self) -> bool:
if self._event is None:
self._event = asyncio.Event()
return await self._event.wait()
class _CollectErrorThread:
def __init__(self, target: Callable[[], None], daemon: bool, name: str):
self._exception: BaseException | None = None
def wrapper() -> None:
try:
target()
except BaseException as e:
self._exception = e
self._thread = thread = threading.Thread(
target=wrapper, daemon=daemon, name=name
)
thread.start()
def join(self, timeout: float | None = None) -> None:
thread = self._thread
thread.join(timeout=timeout)
if thread.is_alive():
raise TimeoutError("join timed out")
if self._exception is not None:
try:
raise self._exception
finally: # remove a reference cycle
del self._exception
class LoopRunner:
"""
A helper to start and stop an IO loop in a controlled way.
Several loop runners can associate safely to the same IO loop.
Parameters
----------
loop: IOLoop (optional)
If given, this loop will be re-used, otherwise an appropriate one
will be looked up or created.
asynchronous: boolean (optional, default False)
If false (the default), the loop is meant to run in a separate
thread and will be started if necessary.
If true, the loop is meant to run in the thread this
object is instantiated from, and will not be started automatically.
"""
# All loops currently associated to loop runners
_all_loops: ClassVar[
weakref.WeakKeyDictionary[IOLoop, tuple[int, LoopRunner | None]]
] = weakref.WeakKeyDictionary()
_lock = threading.Lock()
_loop_thread: _CollectErrorThread | None
def __init__(self, loop: IOLoop | None = None, asynchronous: bool = False):
if loop is None:
if asynchronous:
# raises RuntimeError if there's no running loop
try:
asyncio.get_running_loop()
except RuntimeError as e:
raise RuntimeError(
"Constructing LoopRunner(asynchronous=True) without a running loop is not supported"
) from e
loop = IOLoop.current()
elif not loop.asyncio_loop.is_running(): # type: ignore[attr-defined]
# LoopRunner is not responsible for starting a foreign IOLoop
raise RuntimeError(
"Constructing LoopRunner(loop=loop) without a running loop is not supported"
)
self._loop = loop
self._asynchronous = asynchronous
self._loop_thread = None
self._started = False
self._stop_event = LateLoopEvent()
def start(self):
"""
Start the IO loop if required. The loop is run in a dedicated
thread.
If the loop is already running, this method does nothing.
"""
with self._lock:
self._start_unlocked()
def _start_unlocked(self) -> None:
assert not self._started
if self._loop is not None:
try:
count, real_runner = self._all_loops[self._loop]
except KeyError:
assert self._loop.asyncio_loop.is_running() # type: ignore[attr-defined]
self._started = True
return
self._all_loops[self._loop] = count + 1, real_runner
self._started = True
return
assert self._loop_thread is None
start_evt = threading.Event()
start_exc = None
loop = None
async def amain() -> None:
nonlocal loop
loop = IOLoop.current()
start_evt.set()
await self._stop_event.wait()
def run_loop() -> None:
nonlocal start_exc
try:
asyncio_run(amain(), loop_factory=get_loop_factory())
except BaseException as e:
if start_evt.is_set():
raise
start_exc = e
start_evt.set()
self._loop_thread = _CollectErrorThread(
target=run_loop, daemon=True, name="IO loop"
)
start_evt.wait(timeout=10)
if start_exc is not None:
raise start_exc
assert loop is not None
self._loop = loop
self._started = True
self._all_loops[loop] = (1, self)
def stop(self, timeout=10):
"""
Stop and close the loop if it was created by us.
Otherwise, just mark this object "stopped".
"""
with self._lock:
self._stop_unlocked(timeout)
def _stop_unlocked(self, timeout):
if not self._started:
return
self._started = False
try:
count, real_runner = self._all_loops[self._loop]
except KeyError:
return
if count > 1:
self._all_loops[self._loop] = count - 1, real_runner
return
assert count == 1
del self._all_loops[self._loop]
real_runner._real_stop(timeout)
def _real_stop(self, timeout):
assert self._loop_thread is not None
try:
self._loop.add_callback(self._stop_event.set)
self._loop_thread.join(timeout=timeout)
finally:
self._loop_thread = None
def is_started(self):
"""
Return True between start() and stop() calls, False otherwise.
"""
return self._started
def run_sync(self, func, *args, **kwargs):
"""
Convenience helper: start the loop if needed,
run sync(func, *args, **kwargs), then stop the loop again.
"""
if self._started:
return sync(self.loop, func, *args, **kwargs)
else:
self.start()
try:
return sync(self.loop, func, *args, **kwargs)
finally:
self.stop()
@property
def loop(self):
loop = self._loop
if loop is None or not loop.asyncio_loop.is_running():
raise RuntimeError(
"Accessing the loop property while the loop is not running is not supported"
)
return self._loop
@contextlib.contextmanager
def set_thread_state(**kwargs):
old = {}
for k in kwargs:
try:
old[k] = getattr(thread_state, k)
except AttributeError:
pass
for k, v in kwargs.items():
setattr(thread_state, k, v)
try:
yield
finally:
for k in kwargs:
try:
v = old[k]
except KeyError:
delattr(thread_state, k)
else:
setattr(thread_state, k, v)
@contextlib.contextmanager
def tmp_text(filename, text):
fn = os.path.join(tempfile.gettempdir(), filename)
with open(fn, "w") as f:
f.write(text)
try:
yield fn
finally:
if os.path.exists(fn):
os.remove(fn)
def is_kernel():
"""Determine if we're running within an IPython kernel
>>> is_kernel()
False
"""
# http://stackoverflow.com/questions/34091701/determine-if-were-in-an-ipython-notebook-session
if "IPython" not in sys.modules: # IPython hasn't been imported
return False
from IPython import get_ipython
# check for `kernel` attribute on the IPython instance
return getattr(get_ipython(), "kernel", None) is not None
def key_split_group(x: object) -> str:
"""A more fine-grained version of key_split.
>>> key_split_group(('x-2', 1))
'x-2'
>>> key_split_group("('x-2', 1)")
'x-2'
>>> key_split_group('ae05086432ca935f6eba409a8ecd4896')
'data'
>>> key_split_group('<module.submodule.myclass object at 0xdaf372')
'myclass'
>>> key_split_group('x')
'x'
>>> key_split_group('x-1')
'x'
"""
if isinstance(x, tuple):
return x[0]
elif isinstance(x, str):
if x[0] == "(":
return x.split(",", 1)[0].strip("()\"'")
elif len(x) == 32 and re.match(r"[a-f0-9]{32}", x):
return "data"
elif x[0] == "<":
return x.strip("<>").split()[0].split(".")[-1]
else:
return key_split(x)
elif isinstance(x, bytes):
return key_split_group(x.decode())
else:
return "Other"
@overload
def log_errors(func: Callable[P, T], /) -> Callable[P, T]:
...
@overload
def log_errors(*, pdb: bool = False, unroll_stack: int = 1) -> _LogErrors:
...
def log_errors(func=None, /, *, pdb=False, unroll_stack=1):
"""Log any errors and then reraise them.
This can be used:
- As a context manager::
with log_errors(...):
...
- As a bare function decorator::
@log_errors
def func(...):
...
- As a function decorator with parameters::
@log_errors(...)
def func(...):
...
Parameters
----------
pdb: bool, optional
Set to True to break into the debugger in case of exception
unroll_stack: int, optional
Number of levels of stack to unroll when determining the module's name for the
purpose of logging. Normally you should omit this. Set to 2 if you are writing a
helper function, context manager, or decorator.
"""
le = _LogErrors(pdb=pdb, unroll_stack=unroll_stack)
return le(func) if func else le
class _LogErrors:
__slots__ = ("pdb", "unroll_stack")
pdb: bool
unroll_stack: int
def __init__(self, pdb: bool, unroll_stack: int):
self.pdb = pdb
self.unroll_stack = unroll_stack
def __call__(self, func: Callable[P, T], /) -> Callable[P, T]:
self.unroll_stack += 1
if inspect.iscoroutinefunction(func):
async def wrapper(*args, **kwargs):
with self:
return await func(*args, **kwargs)
else:
def wrapper(*args, **kwargs):
with self:
return func(*args, **kwargs)
return wraps(func)(wrapper)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
from distributed.comm import CommClosedError
if not exc_type or issubclass(exc_type, (CommClosedError, gen.Return)):
return
stack = inspect.stack()
frame = stack[self.unroll_stack]
mod = inspect.getmodule(frame[0])
modname = mod.__name__
try:
logger = logging.getLogger(modname)
logger.exception(exc_value)
except Exception: # Interpreter teardown
pass # pragma: nocover
if self.pdb:
import pdb # pragma: nocover
pdb.set_trace() # pragma: nocover
def silence_logging(level, root="distributed"):
"""
Change all StreamHandlers for the given logger to the given level
"""
warnings.warn(
"silence_logging is deprecated, call silence_logging_cmgr",
DeprecationWarning,
stacklevel=2,
)
if isinstance(level, str):
level = getattr(logging, level.upper())
old = None
logger = logging.getLogger(root)
for handler in logger.handlers:
if isinstance(handler, logging.StreamHandler):
old = handler.level
handler.setLevel(level)
return old
@contextlib.contextmanager
def silence_logging_cmgr(
level: str | int, root: str = "distributed"
) -> Generator[None, None, None]:
"""
Temporarily change all StreamHandlers for the given logger to the given level
"""
if isinstance(level, str):
level = getattr(logging, level.upper())
logger = logging.getLogger(root)
with contextlib.ExitStack() as stack:
for handler in logger.handlers:
if isinstance(handler, logging.StreamHandler):
old = handler.level
if old != level:
handler.setLevel(level)
stack.callback(handler.setLevel, old)
yield
@toolz.memoize
def ensure_ip(hostname):
"""Ensure that address is an IP address
Examples
--------
>>> ensure_ip('localhost')
'127.0.0.1'
>>> ensure_ip('') # Maps as localhost for binding e.g. 'tcp://:8811'
'127.0.0.1'
>>> ensure_ip('123.123.123.123') # pass through IP addresses
'123.123.123.123'
"""
if not hostname:
hostname = "localhost"
# Prefer IPv4 over IPv6, for compatibility
families = [socket.AF_INET, socket.AF_INET6]
for fam in families:
try:
results = socket.getaddrinfo(
hostname, 1234, fam, socket.SOCK_STREAM # dummy port number
)
except socket.gaierror as e:
exc = e
else:
return results[0][4][0]
raise exc
tblib.pickling_support.install()
def get_traceback():
exc_type, exc_value, exc_traceback = sys.exc_info()
bad = [
os.path.join("distributed", "worker"),
os.path.join("distributed", "scheduler"),
os.path.join("tornado", "gen.py"),
os.path.join("concurrent", "futures"),
]
while exc_traceback and any(
b in exc_traceback.tb_frame.f_code.co_filename for b in bad
):
exc_traceback = exc_traceback.tb_next
return exc_traceback
def truncate_exception(e, n=10000):
"""Truncate exception to be about a certain length"""
if len(str(e)) > n:
try:
return type(e)("Long error message", str(e)[:n])
except Exception:
return Exception("Long error message", type(e), str(e)[:n])
else:
return e
def validate_key(k):
"""Validate a key as received on a stream."""
if isinstance(k, tuple):
for e in k:
validate_key(e)
elif not isinstance(k, (bytes, int, float, str)):
raise TypeError(f"Unexpected key type {type(k)} (value: {k!r})")
def _maybe_complex(task):
"""Possibly contains a nested task"""
return (
istask(task)
or type(task) is list
and any(map(_maybe_complex, task))
or type(task) is dict
and any(map(_maybe_complex, task.values()))
)
def seek_delimiter(file, delimiter, blocksize):
"""Seek current file to next byte after a delimiter bytestring
This seeks the file to the next byte following the delimiter. It does
not return anything. Use ``file.tell()`` to see location afterwards.
Parameters
----------
file: a file
delimiter: bytes
a delimiter like ``b'\n'`` or message sentinel
blocksize: int
Number of bytes to read from the file at once.
"""
if file.tell() == 0:
return
last = b""
while True:
current = file.read(blocksize)
if not current:
return
full = last + current
try:
i = full.index(delimiter)
file.seek(file.tell() - (len(full) - i) + len(delimiter))
return
except ValueError:
pass
last = full[-len(delimiter) :]
def read_block(f, offset, length, delimiter=None):
"""Read a block of bytes from a file
Parameters
----------
f: file