taskflow 5.12.0__py3-none-any.whl → 6.0.1__py3-none-any.whl

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 (204) hide show
  1. taskflow/atom.py +3 -5
  2. taskflow/conductors/backends/__init__.py +0 -2
  3. taskflow/conductors/backends/impl_blocking.py +1 -3
  4. taskflow/conductors/backends/impl_executor.py +3 -6
  5. taskflow/conductors/backends/impl_nonblocking.py +1 -3
  6. taskflow/conductors/base.py +1 -3
  7. taskflow/deciders.py +0 -2
  8. taskflow/engines/__init__.py +0 -2
  9. taskflow/engines/action_engine/actions/base.py +1 -3
  10. taskflow/engines/action_engine/actions/retry.py +1 -3
  11. taskflow/engines/action_engine/actions/task.py +1 -3
  12. taskflow/engines/action_engine/builder.py +2 -4
  13. taskflow/engines/action_engine/compiler.py +9 -11
  14. taskflow/engines/action_engine/completer.py +5 -7
  15. taskflow/engines/action_engine/deciders.py +1 -3
  16. taskflow/engines/action_engine/engine.py +4 -26
  17. taskflow/engines/action_engine/executor.py +2 -4
  18. taskflow/engines/action_engine/runtime.py +1 -3
  19. taskflow/engines/action_engine/scheduler.py +3 -5
  20. taskflow/engines/action_engine/scopes.py +3 -5
  21. taskflow/engines/action_engine/selector.py +1 -3
  22. taskflow/engines/action_engine/traversal.py +0 -2
  23. taskflow/engines/base.py +1 -3
  24. taskflow/engines/helpers.py +0 -2
  25. taskflow/engines/worker_based/dispatcher.py +2 -4
  26. taskflow/engines/worker_based/endpoint.py +1 -3
  27. taskflow/engines/worker_based/engine.py +1 -4
  28. taskflow/engines/worker_based/executor.py +0 -2
  29. taskflow/engines/worker_based/protocol.py +1 -3
  30. taskflow/engines/worker_based/proxy.py +2 -4
  31. taskflow/engines/worker_based/server.py +3 -5
  32. taskflow/engines/worker_based/types.py +6 -7
  33. taskflow/engines/worker_based/worker.py +4 -6
  34. taskflow/examples/99_bottles.py +0 -2
  35. taskflow/examples/alphabet_soup.py +0 -2
  36. taskflow/examples/build_a_car.py +1 -3
  37. taskflow/examples/buildsystem.py +1 -3
  38. taskflow/examples/calculate_in_parallel.py +1 -3
  39. taskflow/examples/calculate_linear.py +3 -5
  40. taskflow/examples/create_parallel_volume.py +2 -5
  41. taskflow/examples/delayed_return.py +1 -3
  42. taskflow/examples/distance_calculator.py +12 -24
  43. taskflow/examples/dump_memory_backend.py +1 -3
  44. taskflow/examples/echo_listener.py +0 -2
  45. taskflow/examples/example_utils.py +1 -3
  46. taskflow/examples/fake_billing.py +9 -11
  47. taskflow/examples/graph_flow.py +2 -4
  48. taskflow/examples/hello_world.py +2 -4
  49. taskflow/examples/jobboard_produce_consume_colors.py +3 -5
  50. taskflow/examples/parallel_table_multiply.py +1 -3
  51. taskflow/examples/persistence_example.py +1 -3
  52. taskflow/examples/pseudo_scoping.py +2 -4
  53. taskflow/examples/resume_from_backend.py +1 -3
  54. taskflow/examples/resume_many_flows/my_flows.py +0 -2
  55. taskflow/examples/resume_many_flows/resume_all.py +1 -3
  56. taskflow/examples/resume_many_flows/run_flow.py +2 -4
  57. taskflow/examples/resume_many_flows.py +0 -2
  58. taskflow/examples/resume_vm_boot.py +12 -15
  59. taskflow/examples/resume_volume_create.py +3 -5
  60. taskflow/examples/retry_flow.py +0 -2
  61. taskflow/examples/reverting_linear.py +1 -3
  62. taskflow/examples/run_by_iter.py +0 -2
  63. taskflow/examples/run_by_iter_enumerate.py +1 -3
  64. taskflow/examples/share_engine_thread.py +2 -4
  65. taskflow/examples/simple_linear.py +0 -2
  66. taskflow/examples/simple_linear_listening.py +1 -3
  67. taskflow/examples/simple_linear_pass.py +0 -2
  68. taskflow/examples/simple_map_reduce.py +0 -2
  69. taskflow/examples/switch_graph_flow.py +1 -3
  70. taskflow/examples/timing_listener.py +1 -3
  71. taskflow/examples/tox_conductor.py +3 -5
  72. taskflow/examples/wbe_event_sender.py +0 -2
  73. taskflow/examples/wbe_mandelbrot.py +0 -2
  74. taskflow/examples/wbe_simple_linear.py +0 -2
  75. taskflow/examples/wrapped_exception.py +0 -2
  76. taskflow/exceptions.py +7 -9
  77. taskflow/flow.py +1 -3
  78. taskflow/formatters.py +22 -8
  79. taskflow/jobs/backends/__init__.py +0 -2
  80. taskflow/jobs/backends/impl_redis.py +22 -18
  81. taskflow/jobs/backends/impl_zookeeper.py +7 -8
  82. taskflow/jobs/base.py +5 -7
  83. taskflow/listeners/base.py +1 -3
  84. taskflow/listeners/capturing.py +1 -3
  85. taskflow/listeners/claims.py +1 -3
  86. taskflow/listeners/logging.py +10 -6
  87. taskflow/listeners/printing.py +1 -3
  88. taskflow/listeners/timing.py +10 -13
  89. taskflow/logging.py +0 -2
  90. taskflow/patterns/graph_flow.py +2 -4
  91. taskflow/patterns/linear_flow.py +4 -9
  92. taskflow/patterns/unordered_flow.py +4 -9
  93. taskflow/persistence/backends/__init__.py +1 -3
  94. taskflow/persistence/backends/impl_dir.py +3 -6
  95. taskflow/persistence/backends/impl_memory.py +6 -9
  96. taskflow/persistence/backends/impl_sqlalchemy.py +4 -6
  97. taskflow/persistence/backends/impl_zookeeper.py +2 -4
  98. taskflow/persistence/backends/sqlalchemy/alembic/env.py +0 -2
  99. taskflow/persistence/backends/sqlalchemy/alembic/versions/00af93df9d77_add_unique_into_all_indexes.py +74 -0
  100. taskflow/persistence/backends/sqlalchemy/alembic/versions/14b227d79a87_add_intention_column.py +0 -2
  101. taskflow/persistence/backends/sqlalchemy/alembic/versions/1c783c0c2875_replace_exception_an.py +0 -2
  102. taskflow/persistence/backends/sqlalchemy/alembic/versions/1cea328f0f65_initial_logbook_deta.py +0 -2
  103. taskflow/persistence/backends/sqlalchemy/alembic/versions/2ad4984f2864_switch_postgres_to_json_native.py +0 -2
  104. taskflow/persistence/backends/sqlalchemy/alembic/versions/3162c0f3f8e4_add_revert_results_and_revert_failure_.py +0 -2
  105. taskflow/persistence/backends/sqlalchemy/alembic/versions/589dccdf2b6e_rename_taskdetails_to_atomdetails.py +0 -2
  106. taskflow/persistence/backends/sqlalchemy/alembic/versions/84d6e888850_add_task_detail_type.py +0 -2
  107. taskflow/persistence/backends/sqlalchemy/tables.py +0 -2
  108. taskflow/persistence/base.py +2 -4
  109. taskflow/persistence/models.py +19 -24
  110. taskflow/persistence/path_based.py +1 -3
  111. taskflow/retry.py +12 -18
  112. taskflow/states.py +0 -2
  113. taskflow/storage.py +9 -11
  114. taskflow/task.py +15 -18
  115. taskflow/test.py +5 -5
  116. taskflow/tests/test_examples.py +0 -2
  117. taskflow/tests/unit/action_engine/test_builder.py +1 -3
  118. taskflow/tests/unit/action_engine/test_compile.py +4 -6
  119. taskflow/tests/unit/action_engine/test_creation.py +0 -21
  120. taskflow/tests/unit/action_engine/test_scoping.py +1 -3
  121. taskflow/tests/unit/jobs/base.py +1 -3
  122. taskflow/tests/unit/jobs/test_entrypoint.py +0 -2
  123. taskflow/tests/unit/jobs/test_redis_job.py +1 -3
  124. taskflow/tests/unit/jobs/test_zk_job.py +2 -4
  125. taskflow/tests/unit/patterns/test_graph_flow.py +18 -20
  126. taskflow/tests/unit/patterns/test_linear_flow.py +7 -9
  127. taskflow/tests/unit/patterns/test_unordered_flow.py +12 -14
  128. taskflow/tests/unit/persistence/base.py +2 -4
  129. taskflow/tests/unit/persistence/test_dir_persistence.py +2 -4
  130. taskflow/tests/unit/persistence/test_memory_persistence.py +2 -4
  131. taskflow/tests/unit/persistence/test_sql_persistence.py +8 -10
  132. taskflow/tests/unit/persistence/test_zk_persistence.py +2 -4
  133. taskflow/tests/unit/test_arguments_passing.py +3 -25
  134. taskflow/tests/unit/test_check_transition.py +3 -5
  135. taskflow/tests/unit/test_conductors.py +0 -2
  136. taskflow/tests/unit/test_deciders.py +1 -3
  137. taskflow/tests/unit/test_engine_helpers.py +0 -2
  138. taskflow/tests/unit/test_engines.py +19 -102
  139. taskflow/tests/unit/test_exceptions.py +4 -6
  140. taskflow/tests/unit/test_failure.py +10 -12
  141. taskflow/tests/unit/test_flow_dependencies.py +62 -64
  142. taskflow/tests/unit/test_formatters.py +0 -2
  143. taskflow/tests/unit/test_functor_task.py +1 -3
  144. taskflow/tests/unit/test_listeners.py +9 -11
  145. taskflow/tests/unit/test_mapfunctor_task.py +1 -3
  146. taskflow/tests/unit/test_notifier.py +1 -3
  147. taskflow/tests/unit/test_progress.py +2 -4
  148. taskflow/tests/unit/test_reducefunctor_task.py +1 -3
  149. taskflow/tests/unit/test_retries.py +1 -25
  150. taskflow/tests/unit/test_states.py +0 -2
  151. taskflow/tests/unit/test_storage.py +10 -12
  152. taskflow/tests/unit/test_suspend.py +2 -23
  153. taskflow/tests/unit/test_task.py +17 -19
  154. taskflow/tests/unit/test_types.py +4 -6
  155. taskflow/tests/unit/test_utils.py +9 -11
  156. taskflow/tests/unit/test_utils_async_utils.py +0 -2
  157. taskflow/tests/unit/test_utils_binary.py +12 -14
  158. taskflow/tests/unit/test_utils_iter_utils.py +1 -3
  159. taskflow/tests/unit/test_utils_kazoo_utils.py +0 -2
  160. taskflow/tests/unit/test_utils_threading_utils.py +1 -3
  161. taskflow/tests/unit/worker_based/test_creation.py +0 -2
  162. taskflow/tests/unit/worker_based/test_dispatcher.py +0 -2
  163. taskflow/tests/unit/worker_based/test_endpoint.py +2 -4
  164. taskflow/tests/unit/worker_based/test_executor.py +1 -3
  165. taskflow/tests/unit/worker_based/test_message_pump.py +0 -2
  166. taskflow/tests/unit/worker_based/test_pipeline.py +0 -2
  167. taskflow/tests/unit/worker_based/test_protocol.py +2 -4
  168. taskflow/tests/unit/worker_based/test_proxy.py +2 -4
  169. taskflow/tests/unit/worker_based/test_server.py +3 -5
  170. taskflow/tests/unit/worker_based/test_types.py +0 -2
  171. taskflow/tests/unit/worker_based/test_worker.py +1 -3
  172. taskflow/tests/utils.py +11 -15
  173. taskflow/types/entity.py +1 -3
  174. taskflow/types/failure.py +3 -6
  175. taskflow/types/graph.py +14 -18
  176. taskflow/types/latch.py +1 -3
  177. taskflow/types/notifier.py +6 -9
  178. taskflow/types/sets.py +2 -5
  179. taskflow/types/timing.py +1 -3
  180. taskflow/types/tree.py +6 -10
  181. taskflow/utils/async_utils.py +0 -2
  182. taskflow/utils/banner.py +8 -9
  183. taskflow/utils/eventlet_utils.py +0 -2
  184. taskflow/utils/iter_utils.py +0 -2
  185. taskflow/utils/kazoo_utils.py +7 -9
  186. taskflow/utils/kombu_utils.py +5 -7
  187. taskflow/utils/misc.py +4 -6
  188. taskflow/utils/persistence_utils.py +0 -2
  189. taskflow/utils/redis_utils.py +2 -4
  190. taskflow/utils/schema_utils.py +0 -2
  191. taskflow/utils/threading_utils.py +1 -3
  192. taskflow/version.py +1 -3
  193. {taskflow-5.12.0.dist-info → taskflow-6.0.1.dist-info}/AUTHORS +1 -0
  194. {taskflow-5.12.0.dist-info → taskflow-6.0.1.dist-info}/METADATA +1 -1
  195. taskflow-6.0.1.dist-info/RECORD +243 -0
  196. {taskflow-5.12.0.dist-info → taskflow-6.0.1.dist-info}/WHEEL +1 -1
  197. taskflow-6.0.1.dist-info/pbr.json +1 -0
  198. taskflow/engines/action_engine/process_executor.py +0 -720
  199. taskflow/tests/unit/action_engine/test_process_executor.py +0 -106
  200. taskflow-5.12.0.dist-info/RECORD +0 -244
  201. taskflow-5.12.0.dist-info/pbr.json +0 -1
  202. {taskflow-5.12.0.dist-info → taskflow-6.0.1.dist-info}/LICENSE +0 -0
  203. {taskflow-5.12.0.dist-info → taskflow-6.0.1.dist-info}/entry_points.txt +0 -0
  204. {taskflow-5.12.0.dist-info → taskflow-6.0.1.dist-info}/top_level.txt +0 -0
@@ -1,720 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- # Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
- # not use this file except in compliance with the License. You may obtain
7
- # a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
- # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
- # License for the specific language governing permissions and limitations
15
- # under the License.
16
-
17
- import asyncore
18
- import binascii
19
- import collections
20
- import errno
21
- import functools
22
- import hashlib
23
- import hmac
24
- import math
25
- import os
26
- import pickle
27
- import socket
28
- import struct
29
- import time
30
-
31
- import futurist
32
- from oslo_utils import excutils
33
-
34
- from taskflow.engines.action_engine import executor as base
35
- from taskflow import logging
36
- from taskflow import task as ta
37
- from taskflow.types import notifier as nt
38
- from taskflow.utils import iter_utils
39
- from taskflow.utils import misc
40
- from taskflow.utils import schema_utils as su
41
- from taskflow.utils import threading_utils
42
-
43
- LOG = logging.getLogger(__name__)
44
-
45
- # Internal parent <-> child process protocol schema, message constants...
46
- MAGIC_HEADER = 0xDECAF
47
- CHALLENGE = 'identify_yourself'
48
- CHALLENGE_RESPONSE = 'worker_reporting_in'
49
- ACK = 'ack'
50
- EVENT = 'event'
51
- SCHEMAS = {
52
- # Basic jsonschemas for verifying that the data we get back and
53
- # forth from parent <-> child observes at least a basic expected
54
- # format.
55
- CHALLENGE: {
56
- "type": "string",
57
- "minLength": 1,
58
- },
59
- ACK: {
60
- "type": "string",
61
- "minLength": 1,
62
- },
63
- CHALLENGE_RESPONSE: {
64
- "type": "string",
65
- "minLength": 1,
66
- },
67
- EVENT: {
68
- "type": "object",
69
- "properties": {
70
- 'event_type': {
71
- "type": "string",
72
- },
73
- 'sent_on': {
74
- "type": "number",
75
- },
76
- },
77
- "required": ['event_type', 'sent_on'],
78
- "additionalProperties": True,
79
- },
80
- }
81
-
82
-
83
- class UnknownSender(Exception):
84
- """Exception raised when message from unknown sender is recvd."""
85
-
86
-
87
- class ChallengeIgnored(Exception):
88
- """Exception raised when challenge has not been responded to."""
89
-
90
-
91
- class Reader(object):
92
- """Reader machine that streams & parses messages that it then dispatches.
93
-
94
- TODO(harlowja): Use python-suitcase in the future when the following
95
- are addressed/resolved and released:
96
-
97
- - https://github.com/digidotcom/python-suitcase/issues/28
98
- - https://github.com/digidotcom/python-suitcase/issues/29
99
-
100
- Binary format format is the following (no newlines in actual format)::
101
-
102
- <magic-header> (4 bytes)
103
- <mac-header-length> (4 bytes)
104
- <mac> (1 or more variable bytes)
105
- <identity-header-length> (4 bytes)
106
- <identity> (1 or more variable bytes)
107
- <msg-header-length> (4 bytes)
108
- <msg> (1 or more variable bytes)
109
- """
110
-
111
- #: Per state memory initializers.
112
- _INITIALIZERS = {
113
- 'magic_header_left': 4,
114
- 'mac_header_left': 4,
115
- 'identity_header_left': 4,
116
- 'msg_header_left': 4,
117
- }
118
-
119
- #: Linear steps/transitions (order matters here).
120
- _TRANSITIONS = tuple([
121
- 'magic_header_left',
122
- 'mac_header_left',
123
- 'mac_left',
124
- 'identity_header_left',
125
- 'identity_left',
126
- 'msg_header_left',
127
- 'msg_left',
128
- ])
129
-
130
- def __init__(self, auth_key, dispatch_func, msg_limit=-1):
131
- if not callable(dispatch_func):
132
- raise ValueError("Expected provided dispatch function"
133
- " to be callable")
134
- self.auth_key = auth_key
135
- self.dispatch_func = dispatch_func
136
- msg_limiter = iter_utils.iter_forever(msg_limit)
137
- self.msg_count = next(msg_limiter)
138
- self._msg_limiter = msg_limiter
139
- self._buffer = misc.BytesIO()
140
- self._state = None
141
- # Local machine variables and such are stored in here.
142
- self._memory = {}
143
- self._transitions = collections.deque(self._TRANSITIONS)
144
- # This is the per state callback handler set. The first entry reads
145
- # the data and the second entry is called after reading is completed,
146
- # typically to save that data into object memory, or to validate
147
- # it.
148
- self._handlers = {
149
- 'magic_header_left': (self._read_field_data,
150
- self._save_and_validate_magic),
151
- 'mac_header_left': (self._read_field_data,
152
- functools.partial(self._save_pos_integer,
153
- 'mac_left')),
154
- 'mac_left': (functools.partial(self._read_data, 'mac'),
155
- functools.partial(self._save_data, 'mac')),
156
- 'identity_header_left': (self._read_field_data,
157
- functools.partial(self._save_pos_integer,
158
- 'identity_left')),
159
- 'identity_left': (functools.partial(self._read_data, 'identity'),
160
- functools.partial(self._save_data, 'identity')),
161
- 'msg_header_left': (self._read_field_data,
162
- functools.partial(self._save_pos_integer,
163
- 'msg_left')),
164
- 'msg_left': (functools.partial(self._read_data, 'msg'),
165
- self._dispatch_and_reset),
166
- }
167
- # Force transition into first state...
168
- self._transition()
169
-
170
- def _save_pos_integer(self, key_name, data):
171
- key_val = struct.unpack("!i", data)[0]
172
- if key_val <= 0:
173
- raise IOError("Invalid %s length received for key '%s', expected"
174
- " greater than zero length" % (key_val, key_name))
175
- self._memory[key_name] = key_val
176
- return True
177
-
178
- def _save_data(self, key_name, data):
179
- self._memory[key_name] = data
180
- return True
181
-
182
- def _dispatch_and_reset(self, data):
183
- self.dispatch_func(
184
- self._memory['identity'],
185
- # Lazy evaluate so the message can be thrown out as needed
186
- # (instead of the receiver discarding it after the fact)...
187
- functools.partial(_decode_message, self.auth_key, data,
188
- self._memory['mac']))
189
- self.msg_count = next(self._msg_limiter)
190
- self._memory.clear()
191
-
192
- def _transition(self):
193
- try:
194
- self._state = self._transitions.popleft()
195
- except IndexError:
196
- self._transitions.extend(self._TRANSITIONS)
197
- self._state = self._transitions.popleft()
198
- try:
199
- self._memory[self._state] = self._INITIALIZERS[self._state]
200
- except KeyError:
201
- pass
202
- self._handle_func, self._post_handle_func = self._handlers[self._state]
203
-
204
- def _save_and_validate_magic(self, data):
205
- magic_header = struct.unpack("!i", data)[0]
206
- if magic_header != MAGIC_HEADER:
207
- raise IOError("Invalid magic header received, expected 0x%x but"
208
- " got 0x%x for message %s" % (MAGIC_HEADER,
209
- magic_header,
210
- self.msg_count + 1))
211
- self._memory['magic'] = magic_header
212
- return True
213
-
214
- def _read_data(self, save_key_name, data):
215
- data_len_left = self._memory[self._state]
216
- self._buffer.write(data[0:data_len_left])
217
- if len(data) < data_len_left:
218
- data_len_left -= len(data)
219
- self._memory[self._state] = data_len_left
220
- return ''
221
- else:
222
- self._memory[self._state] = 0
223
- buf_data = self._buffer.getvalue()
224
- self._buffer.reset()
225
- self._post_handle_func(buf_data)
226
- self._transition()
227
- return data[data_len_left:]
228
-
229
- def _read_field_data(self, data):
230
- return self._read_data(self._state, data)
231
-
232
- @property
233
- def bytes_needed(self):
234
- return self._memory.get(self._state, 0)
235
-
236
- def feed(self, data):
237
- while len(data):
238
- data = self._handle_func(data)
239
-
240
-
241
- class BadHmacValueError(ValueError):
242
- """Value error raised when an invalid hmac is discovered."""
243
-
244
-
245
- def _create_random_string(desired_length):
246
- if desired_length <= 0:
247
- return b''
248
- data_length = int(math.ceil(desired_length / 2.0))
249
- data = os.urandom(data_length)
250
- hex_data = binascii.hexlify(data)
251
- return hex_data[0:desired_length]
252
-
253
-
254
- def _calculate_hmac(auth_key, body):
255
- mac = hmac.new(auth_key, body, hashlib.md5).hexdigest()
256
- if isinstance(mac, str):
257
- mac = mac.encode("ascii")
258
- return mac
259
-
260
-
261
- def _encode_message(auth_key, message, identity, reverse=False):
262
- message = pickle.dumps(message, 2)
263
- message_mac = _calculate_hmac(auth_key, message)
264
- pieces = [
265
- struct.pack("!i", MAGIC_HEADER),
266
- struct.pack("!i", len(message_mac)),
267
- message_mac,
268
- struct.pack("!i", len(identity)),
269
- identity,
270
- struct.pack("!i", len(message)),
271
- message,
272
- ]
273
- if reverse:
274
- pieces.reverse()
275
- return tuple(pieces)
276
-
277
-
278
- def _decode_message(auth_key, message, message_mac):
279
- tmp_message_mac = _calculate_hmac(auth_key, message)
280
- if tmp_message_mac != message_mac:
281
- raise BadHmacValueError('Invalid message hmac')
282
- return pickle.loads(message)
283
-
284
-
285
- class Channel(object):
286
- """Object that workers use to communicate back to their creator."""
287
-
288
- def __init__(self, port, identity, auth_key):
289
- self.identity = identity
290
- self.port = port
291
- self.auth_key = auth_key
292
- self.dead = False
293
- self._sent = self._received = 0
294
- self._socket = None
295
- self._read_pipe = None
296
- self._write_pipe = None
297
-
298
- def close(self):
299
- if self._socket is not None:
300
- self._socket.close()
301
- self._socket = None
302
- self._read_pipe = None
303
- self._write_pipe = None
304
-
305
- def _ensure_connected(self):
306
- if self._socket is None:
307
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
308
- s.setblocking(1)
309
- try:
310
- s.connect(("", self.port))
311
- except socket.error as e:
312
- with excutils.save_and_reraise_exception():
313
- s.close()
314
- if e.errno in (errno.ECONNREFUSED, errno.ENOTCONN,
315
- errno.ECONNRESET):
316
- # Don't bother with further connections...
317
- self.dead = True
318
- read_pipe = s.makefile("rb", 0)
319
- write_pipe = s.makefile("wb", 0)
320
- try:
321
- msg = self._do_recv(read_pipe=read_pipe)
322
- su.schema_validate(msg, SCHEMAS[CHALLENGE])
323
- if msg != CHALLENGE:
324
- raise IOError("Challenge expected not received")
325
- else:
326
- pieces = _encode_message(self.auth_key,
327
- CHALLENGE_RESPONSE,
328
- self.identity)
329
- self._do_send_and_ack(pieces, write_pipe=write_pipe,
330
- read_pipe=read_pipe)
331
- except Exception:
332
- with excutils.save_and_reraise_exception():
333
- s.close()
334
- else:
335
- self._socket = s
336
- self._read_pipe = read_pipe
337
- self._write_pipe = write_pipe
338
-
339
- def recv(self):
340
- self._ensure_connected()
341
- return self._do_recv()
342
-
343
- def _do_recv(self, read_pipe=None):
344
- if read_pipe is None:
345
- read_pipe = self._read_pipe
346
- msg_capture = collections.deque(maxlen=1)
347
- msg_capture_func = (lambda _from_who, msg_decoder_func:
348
- msg_capture.append(msg_decoder_func()))
349
- reader = Reader(self.auth_key, msg_capture_func, msg_limit=1)
350
- try:
351
- maybe_msg_num = self._received + 1
352
- bytes_needed = reader.bytes_needed
353
- while True:
354
- blob = read_pipe.read(bytes_needed)
355
- if len(blob) != bytes_needed:
356
- raise EOFError("Read pipe closed while reading %s"
357
- " bytes for potential message %s"
358
- % (bytes_needed, maybe_msg_num))
359
- reader.feed(blob)
360
- bytes_needed = reader.bytes_needed
361
- except StopIteration:
362
- pass
363
- msg = msg_capture[0]
364
- self._received += 1
365
- return msg
366
-
367
- def _do_send(self, pieces, write_pipe=None):
368
- if write_pipe is None:
369
- write_pipe = self._write_pipe
370
- for piece in pieces:
371
- write_pipe.write(piece)
372
- write_pipe.flush()
373
-
374
- def _do_send_and_ack(self, pieces, write_pipe=None, read_pipe=None):
375
- self._do_send(pieces, write_pipe=write_pipe)
376
- self._sent += 1
377
- msg = self._do_recv(read_pipe=read_pipe)
378
- su.schema_validate(msg, SCHEMAS[ACK])
379
- if msg != ACK:
380
- raise IOError("Failed receiving ack for sent"
381
- " message %s" % self._metrics['sent'])
382
-
383
- def send(self, message):
384
- self._ensure_connected()
385
- self._do_send_and_ack(_encode_message(self.auth_key, message,
386
- self.identity))
387
-
388
-
389
- class EventSender(object):
390
- """Sends event information from a child worker process to its creator."""
391
-
392
- def __init__(self, channel):
393
- self._channel = channel
394
- self._pid = None
395
-
396
- def __call__(self, event_type, details):
397
- if not self._channel.dead:
398
- if self._pid is None:
399
- self._pid = os.getpid()
400
- message = {
401
- 'event_type': event_type,
402
- 'details': details,
403
- 'sent_on': time.time(),
404
- }
405
- LOG.trace("Sending %s (from child %s)", message, self._pid)
406
- self._channel.send(message)
407
-
408
-
409
- class DispatcherHandler(asyncore.dispatcher):
410
- """Dispatches from a single connection into a target."""
411
-
412
- #: Read/write chunk size.
413
- CHUNK_SIZE = 8192
414
-
415
- def __init__(self, sock, addr, dispatcher):
416
- super(DispatcherHandler, self).__init__(map=dispatcher.map,
417
- sock=sock)
418
- self.blobs_to_write = list(dispatcher.challenge_pieces)
419
- self.reader = Reader(dispatcher.auth_key, self._dispatch)
420
- self.targets = dispatcher.targets
421
- self.tied_to = None
422
- self.challenge_responded = False
423
- self.ack_pieces = _encode_message(dispatcher.auth_key, ACK,
424
- dispatcher.identity,
425
- reverse=True)
426
- self.addr = addr
427
-
428
- def handle_close(self):
429
- self.close()
430
-
431
- def writable(self):
432
- return bool(self.blobs_to_write)
433
-
434
- def handle_write(self):
435
- try:
436
- blob = self.blobs_to_write.pop()
437
- except IndexError:
438
- pass
439
- else:
440
- sent = self.send(blob[0:self.CHUNK_SIZE])
441
- if sent < len(blob):
442
- self.blobs_to_write.append(blob[sent:])
443
-
444
- def _send_ack(self):
445
- self.blobs_to_write.extend(self.ack_pieces)
446
-
447
- def _dispatch(self, from_who, msg_decoder_func):
448
- if not self.challenge_responded:
449
- msg = msg_decoder_func()
450
- su.schema_validate(msg, SCHEMAS[CHALLENGE_RESPONSE])
451
- if msg != CHALLENGE_RESPONSE:
452
- raise ChallengeIgnored("Discarding connection from %s"
453
- " challenge was not responded to"
454
- % self.addr)
455
- else:
456
- LOG.trace("Peer %s (%s) has passed challenge sequence",
457
- self.addr, from_who)
458
- self.challenge_responded = True
459
- self.tied_to = from_who
460
- self._send_ack()
461
- else:
462
- if self.tied_to != from_who:
463
- raise UnknownSender("Sender %s previously identified as %s"
464
- " changed there identity to %s after"
465
- " challenge sequence" % (self.addr,
466
- self.tied_to,
467
- from_who))
468
- try:
469
- task = self.targets[from_who]
470
- except KeyError:
471
- raise UnknownSender("Unknown message from %s (%s) not matched"
472
- " to any known target" % (self.addr,
473
- from_who))
474
- msg = msg_decoder_func()
475
- su.schema_validate(msg, SCHEMAS[EVENT])
476
- if LOG.isEnabledFor(logging.TRACE):
477
- msg_delay = max(0, time.time() - msg['sent_on'])
478
- LOG.trace("Dispatching message from %s (%s) (it took %0.3f"
479
- " seconds for it to arrive for processing after"
480
- " being sent)", self.addr, from_who, msg_delay)
481
- task.notifier.notify(msg['event_type'], msg.get('details'))
482
- self._send_ack()
483
-
484
- def handle_read(self):
485
- data = self.recv(self.CHUNK_SIZE)
486
- if len(data) == 0:
487
- self.handle_close()
488
- else:
489
- try:
490
- self.reader.feed(data)
491
- except (IOError, UnknownSender):
492
- LOG.warning("Invalid received message", exc_info=True)
493
- self.handle_close()
494
- except (pickle.PickleError, TypeError):
495
- LOG.warning("Badly formatted message", exc_info=True)
496
- self.handle_close()
497
- except (ValueError, su.ValidationError):
498
- LOG.warning("Failed validating message", exc_info=True)
499
- self.handle_close()
500
- except ChallengeIgnored:
501
- LOG.warning("Failed challenge sequence", exc_info=True)
502
- self.handle_close()
503
-
504
-
505
- class Dispatcher(asyncore.dispatcher):
506
- """Accepts messages received from child worker processes."""
507
-
508
- #: See https://docs.python.org/2/library/socket.html#socket.socket.listen
509
- MAX_BACKLOG = 5
510
-
511
- def __init__(self, map, auth_key, identity):
512
- super(Dispatcher, self).__init__(map=map)
513
- self.identity = identity
514
- self.challenge_pieces = _encode_message(auth_key, CHALLENGE,
515
- identity, reverse=True)
516
- self.auth_key = auth_key
517
- self.targets = {}
518
-
519
- @property
520
- def port(self):
521
- if self.socket is not None:
522
- return self.socket.getsockname()[1]
523
- else:
524
- return None
525
-
526
- def setup(self):
527
- self.targets.clear()
528
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
529
- self.bind(("", 0))
530
- LOG.trace("Accepting dispatch requests on port %s", self.port)
531
- self.listen(self.MAX_BACKLOG)
532
-
533
- def writable(self):
534
- return False
535
-
536
- @property
537
- def map(self):
538
- return self._map
539
-
540
- def handle_close(self):
541
- if self.socket is not None:
542
- self.close()
543
-
544
- def handle_accept(self):
545
- pair = self.accept()
546
- if pair is not None:
547
- sock, addr = pair
548
- addr = "%s:%s" % (addr[0], addr[1])
549
- LOG.trace("Potentially accepted new connection from %s", addr)
550
- DispatcherHandler(sock, addr, self)
551
-
552
-
553
- class ParallelProcessTaskExecutor(base.ParallelTaskExecutor):
554
- """Executes tasks in parallel using a process pool executor.
555
-
556
- NOTE(harlowja): this executor executes tasks in external processes, so that
557
- implies that tasks that are sent to that external process are pickleable
558
- since this is how the multiprocessing works (sending pickled objects back
559
- and forth) and that the bound handlers (for progress updating in
560
- particular) are proxied correctly from that external process to the one
561
- that is alive in the parent process to ensure that callbacks registered in
562
- the parent are executed on events in the child.
563
- """
564
-
565
- #: Default timeout used by asyncore io loop (and eventually select/poll).
566
- WAIT_TIMEOUT = 0.01
567
-
568
- constructor_options = [
569
- ('max_workers', lambda v: v if v is None else int(v)),
570
- ('wait_timeout', lambda v: v if v is None else float(v)),
571
- ]
572
- """
573
- Optional constructor keyword arguments this executor supports. These will
574
- typically be passed via engine options (by a engine user) and converted
575
- into the correct type before being sent into this
576
- classes ``__init__`` method.
577
- """
578
-
579
- def __init__(self, executor=None,
580
- max_workers=None, wait_timeout=None):
581
- super(ParallelProcessTaskExecutor, self).__init__(
582
- executor=executor, max_workers=max_workers)
583
- LOG.warning('Process task executor is deprecated. It is now disabled '
584
- 'in Python 3.12 or later and will be removed.')
585
- self._auth_key = _create_random_string(32)
586
- self._dispatcher = Dispatcher({}, self._auth_key,
587
- _create_random_string(32))
588
- if wait_timeout is None:
589
- self._wait_timeout = self.WAIT_TIMEOUT
590
- else:
591
- if wait_timeout <= 0:
592
- raise ValueError("Provided wait timeout must be greater"
593
- " than zero and not '%s'" % wait_timeout)
594
- self._wait_timeout = wait_timeout
595
- # Only created after starting...
596
- self._worker = None
597
-
598
- def _create_executor(self, max_workers=None):
599
- return futurist.ProcessPoolExecutor(max_workers=max_workers)
600
-
601
- def start(self):
602
- if threading_utils.is_alive(self._worker):
603
- raise RuntimeError("Worker thread must be stopped via stop()"
604
- " before starting/restarting")
605
- super(ParallelProcessTaskExecutor, self).start()
606
- self._dispatcher.setup()
607
- self._worker = threading_utils.daemon_thread(
608
- asyncore.loop, map=self._dispatcher.map,
609
- timeout=self._wait_timeout)
610
- self._worker.start()
611
-
612
- def stop(self):
613
- super(ParallelProcessTaskExecutor, self).stop()
614
- self._dispatcher.close()
615
- if threading_utils.is_alive(self._worker):
616
- self._worker.join()
617
- self._worker = None
618
-
619
- def _submit_task(self, func, task, *args, **kwargs):
620
- """Submit a function to run the given task (with given args/kwargs).
621
-
622
- NOTE(harlowja): Adjust all events to be proxies instead since we want
623
- those callbacks to be activated in this process, not in the child,
624
- also since typically callbacks are functors (or callables) we can
625
- not pickle those in the first place...
626
-
627
- To make sure people understand how this works, the following is a
628
- lengthy description of what is going on here, read at will:
629
-
630
- So to ensure that we are proxying task triggered events that occur
631
- in the executed subprocess (which will be created and used by the
632
- thing using the multiprocessing based executor) we need to establish
633
- a link between that process and this process that ensures that when a
634
- event is triggered in that task in that process that a corresponding
635
- event is triggered on the original task that was requested to be ran
636
- in this process.
637
-
638
- To accomplish this we have to create a copy of the task (without
639
- any listeners) and then reattach a new set of listeners that will
640
- now instead of calling the desired listeners just place messages
641
- for this process (a dispatcher thread that is created in this class)
642
- to dispatch to the original task (using a common accepting socket and
643
- per task sender socket that is used and associated to know
644
- which task to proxy back too, since it is possible that there many
645
- be *many* subprocess running at the same time).
646
-
647
- Once the subprocess task has finished execution, the executor will
648
- then trigger a callback that will remove the task + target from the
649
- dispatcher (which will stop any further proxying back to the original
650
- task).
651
- """
652
- progress_callback = kwargs.pop('progress_callback', None)
653
- clone = task.copy(retain_listeners=False)
654
- identity = _create_random_string(32)
655
- channel = Channel(self._dispatcher.port, identity, self._auth_key)
656
-
657
- def rebind_task():
658
- # Creates and binds proxies for all events the task could receive
659
- # so that when the clone runs in another process that this task
660
- # can receive the same notifications (thus making it look like the
661
- # the notifications are transparently happening in this process).
662
- proxy_event_types = set()
663
- for (event_type, listeners) in task.notifier.listeners_iter():
664
- if listeners:
665
- proxy_event_types.add(event_type)
666
- if progress_callback is not None:
667
- proxy_event_types.add(ta.EVENT_UPDATE_PROGRESS)
668
- if nt.Notifier.ANY in proxy_event_types:
669
- # NOTE(harlowja): If ANY is present, just have it be
670
- # the **only** event registered, as all other events will be
671
- # sent if ANY is registered (due to the nature of ANY sending
672
- # all the things); if we also include the other event types
673
- # in this set if ANY is present we will receive duplicate
674
- # messages in this process (the one where the local
675
- # task callbacks are being triggered). For example the
676
- # emissions of the tasks notifier (that is running out
677
- # of process) will for specific events send messages for
678
- # its ANY event type **and** the specific event
679
- # type (2 messages, when we just want one) which will
680
- # cause > 1 notify() call on the local tasks notifier, which
681
- # causes more local callback triggering than we want
682
- # to actually happen.
683
- proxy_event_types = set([nt.Notifier.ANY])
684
- if proxy_event_types:
685
- # This sender acts as our forwarding proxy target, it
686
- # will be sent pickled to the process that will execute
687
- # the needed task and it will do the work of using the
688
- # channel object to send back messages to this process for
689
- # dispatch into the local task.
690
- sender = EventSender(channel)
691
- for event_type in proxy_event_types:
692
- clone.notifier.register(event_type, sender)
693
- return bool(proxy_event_types)
694
-
695
- def register():
696
- if progress_callback is not None:
697
- task.notifier.register(ta.EVENT_UPDATE_PROGRESS,
698
- progress_callback)
699
- self._dispatcher.targets[identity] = task
700
-
701
- def deregister(fut=None):
702
- if progress_callback is not None:
703
- task.notifier.deregister(ta.EVENT_UPDATE_PROGRESS,
704
- progress_callback)
705
- self._dispatcher.targets.pop(identity, None)
706
-
707
- should_register = rebind_task()
708
- if should_register:
709
- register()
710
- try:
711
- fut = self._executor.submit(func, clone, *args, **kwargs)
712
- except RuntimeError:
713
- with excutils.save_and_reraise_exception():
714
- if should_register:
715
- deregister()
716
-
717
- fut.atom = task
718
- if should_register:
719
- fut.add_done_callback(deregister)
720
- return fut