Debian Codegraph @

futurist/_utils.py

raw
1 # Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import contextlib
16 import inspect
17 import multiprocessing
18 import sys
19 import threading
20 from time import monotonic
21 import traceback
22
23 now = monotonic
24
25 try:
26 import eventlet as _eventlet # noqa
27 EVENTLET_AVAILABLE = True
28 except ImportError:
29 EVENTLET_AVAILABLE = False
30
31
32 class WorkItem:
33 """A thing to be executed by a executor."""
34
35 def __init__(self, future, fn, args, kwargs):
36 self.future = future
37 self.fn = fn
38 self.args = args
39 self.kwargs = kwargs
40
41 def run(self):
42 if not self.future.set_running_or_notify_cancel():
43 return
44 try:
45 result = self.fn(*self.args, **self.kwargs)
46 except SystemExit as e:
47 try:
48 self.fail()
49 finally:
50 raise e
51 except BaseException:
52 self.fail()
53 else:
54 self.future.set_result(result)
55
56 def fail(self, exc_info=None):
57 exc_type, exc_value, exc_tb = exc_info or sys.exc_info()
58 try:
59 self.future.set_exception(exc_value)
60 finally:
61 if exc_info is None:
62 del exc_type, exc_value, exc_tb
63
64
65 class Failure:
66 """Object that captures a exception (and its associated information)."""
67
68 def __init__(self, retain_tb):
69 exc_info = sys.exc_info()
70 if not any(exc_info):
71 raise RuntimeError("No active exception being handled, can"
72 " not create a failure which represents"
73 " nothing")
74 try:
75 if retain_tb:
76 self.exc_info = tuple(exc_info)
77 self.traceback = None
78 else:
79 self.exc_info = (exc_info[0], exc_info[1], None)
80 self.traceback = "".join(traceback.format_exception(*exc_info))
81 finally:
82 del exc_info
83
84 @property
85 def exc_type(self):
86 return self.exc_info[0]
87
88 @property
89 def exc_value(self):
90 return self.exc_info[1]
91
92
93 def get_callback_name(cb):
94 """Tries to get a callbacks fully-qualified name.
95
96 If no name can be produced ``repr(cb)`` is called and returned.
97 """
98 segments = []
99 try:
100 segments.append(cb.__qualname__)
101 except AttributeError:
102 try:
103 segments.append(cb.__name__)
104 if inspect.ismethod(cb):
105 try:
106 # This attribute doesn't exist on py3.x or newer, so
107 # we optionally ignore it... (on those versions of
108 # python `__qualname__` should have been found anyway).
109 segments.insert(0, cb.im_class.__name__)
110 except AttributeError:
111 pass
112 except AttributeError:
113 pass
114 if not segments:
115 return repr(cb)
116 else:
117 try:
118 # When running under sphinx it appears this can be none?
119 if cb.__module__:
120 segments.insert(0, cb.__module__)
121 except AttributeError:
122 pass
123 return ".".join(segments)
124
125
126 def get_optimal_thread_count(default=5):
127 """Try to guess optimal thread count for current system."""
128 try:
129 return multiprocessing.cpu_count() * 5
130 except NotImplementedError:
131 return default
132
133
134 def get_optimal_process_count(default=1):
135 """Try to guess optimal process count for current system."""
136 try:
137 return multiprocessing.cpu_count()
138 except NotImplementedError:
139 return default
140
141
142 class Barrier:
143 """A class that ensures active <= 0 occur before unblocking."""
144
145 def __init__(self, cond_cls=threading.Condition):
146 self._active = 0
147 self._cond = cond_cls()
148
149 @property
150 def active(self):
151 return self._active
152
153 def incr(self):
154 with self._cond:
155 self._active += 1
156 self._cond.notify_all()
157
158 @contextlib.contextmanager
159 def decr_cm(self):
160 with self._cond:
161 self._active -= 1
162 try:
163 yield self._active
164 finally:
165 self._cond.notify_all()
166
167 def decr(self):
168 with self._cond:
169 self._active -= 1
170 self._cond.notify_all()
171
172 def wait(self):
173 with self._cond:
174 while self._active > 0:
175 self._cond.wait()