rucio-clients 32.8.6__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.

Potentially problematic release.


This version of rucio-clients might be problematic. Click here for more details.

Files changed (88) hide show
  1. rucio/__init__.py +18 -0
  2. rucio/alembicrevision.py +16 -0
  3. rucio/client/__init__.py +16 -0
  4. rucio/client/accountclient.py +413 -0
  5. rucio/client/accountlimitclient.py +155 -0
  6. rucio/client/baseclient.py +929 -0
  7. rucio/client/client.py +77 -0
  8. rucio/client/configclient.py +113 -0
  9. rucio/client/credentialclient.py +54 -0
  10. rucio/client/didclient.py +691 -0
  11. rucio/client/diracclient.py +48 -0
  12. rucio/client/downloadclient.py +1674 -0
  13. rucio/client/exportclient.py +44 -0
  14. rucio/client/fileclient.py +51 -0
  15. rucio/client/importclient.py +42 -0
  16. rucio/client/lifetimeclient.py +74 -0
  17. rucio/client/lockclient.py +99 -0
  18. rucio/client/metaclient.py +137 -0
  19. rucio/client/pingclient.py +45 -0
  20. rucio/client/replicaclient.py +444 -0
  21. rucio/client/requestclient.py +109 -0
  22. rucio/client/rseclient.py +664 -0
  23. rucio/client/ruleclient.py +287 -0
  24. rucio/client/scopeclient.py +88 -0
  25. rucio/client/subscriptionclient.py +161 -0
  26. rucio/client/touchclient.py +78 -0
  27. rucio/client/uploadclient.py +871 -0
  28. rucio/common/__init__.py +14 -0
  29. rucio/common/cache.py +74 -0
  30. rucio/common/config.py +796 -0
  31. rucio/common/constants.py +92 -0
  32. rucio/common/constraints.py +18 -0
  33. rucio/common/didtype.py +187 -0
  34. rucio/common/exception.py +1092 -0
  35. rucio/common/extra.py +37 -0
  36. rucio/common/logging.py +404 -0
  37. rucio/common/pcache.py +1387 -0
  38. rucio/common/policy.py +84 -0
  39. rucio/common/schema/__init__.py +143 -0
  40. rucio/common/schema/atlas.py +411 -0
  41. rucio/common/schema/belleii.py +406 -0
  42. rucio/common/schema/cms.py +478 -0
  43. rucio/common/schema/domatpc.py +399 -0
  44. rucio/common/schema/escape.py +424 -0
  45. rucio/common/schema/generic.py +431 -0
  46. rucio/common/schema/generic_multi_vo.py +410 -0
  47. rucio/common/schema/icecube.py +404 -0
  48. rucio/common/schema/lsst.py +423 -0
  49. rucio/common/stomp_utils.py +160 -0
  50. rucio/common/stopwatch.py +56 -0
  51. rucio/common/test_rucio_server.py +148 -0
  52. rucio/common/types.py +158 -0
  53. rucio/common/utils.py +1946 -0
  54. rucio/rse/__init__.py +97 -0
  55. rucio/rse/protocols/__init__.py +14 -0
  56. rucio/rse/protocols/cache.py +123 -0
  57. rucio/rse/protocols/dummy.py +112 -0
  58. rucio/rse/protocols/gfal.py +701 -0
  59. rucio/rse/protocols/globus.py +243 -0
  60. rucio/rse/protocols/gsiftp.py +93 -0
  61. rucio/rse/protocols/http_cache.py +83 -0
  62. rucio/rse/protocols/mock.py +124 -0
  63. rucio/rse/protocols/ngarc.py +210 -0
  64. rucio/rse/protocols/posix.py +251 -0
  65. rucio/rse/protocols/protocol.py +530 -0
  66. rucio/rse/protocols/rclone.py +365 -0
  67. rucio/rse/protocols/rfio.py +137 -0
  68. rucio/rse/protocols/srm.py +339 -0
  69. rucio/rse/protocols/ssh.py +414 -0
  70. rucio/rse/protocols/storm.py +207 -0
  71. rucio/rse/protocols/webdav.py +547 -0
  72. rucio/rse/protocols/xrootd.py +295 -0
  73. rucio/rse/rsemanager.py +752 -0
  74. rucio/vcsversion.py +11 -0
  75. rucio/version.py +46 -0
  76. rucio_clients-32.8.6.data/data/etc/rse-accounts.cfg.template +25 -0
  77. rucio_clients-32.8.6.data/data/etc/rucio.cfg.atlas.client.template +42 -0
  78. rucio_clients-32.8.6.data/data/etc/rucio.cfg.template +257 -0
  79. rucio_clients-32.8.6.data/data/requirements.txt +55 -0
  80. rucio_clients-32.8.6.data/data/rucio_client/merge_rucio_configs.py +147 -0
  81. rucio_clients-32.8.6.data/scripts/rucio +2540 -0
  82. rucio_clients-32.8.6.data/scripts/rucio-admin +2434 -0
  83. rucio_clients-32.8.6.dist-info/METADATA +50 -0
  84. rucio_clients-32.8.6.dist-info/RECORD +88 -0
  85. rucio_clients-32.8.6.dist-info/WHEEL +5 -0
  86. rucio_clients-32.8.6.dist-info/licenses/AUTHORS.rst +94 -0
  87. rucio_clients-32.8.6.dist-info/licenses/LICENSE +201 -0
  88. rucio_clients-32.8.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,423 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright European Organization for Nuclear Research (CERN) since 2012
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from jsonschema import validate, ValidationError
17
+
18
+ from rucio.common.exception import InvalidObject
19
+
20
+ ACCOUNT_LENGTH = 25
21
+
22
+ ACCOUNT = {"description": "Account name",
23
+ "type": "string",
24
+ "pattern": "^[a-z0-9-_]{1,%s}$" % ACCOUNT_LENGTH}
25
+
26
+ ACCOUNTS = {"description": "Array of accounts",
27
+ "type": "array",
28
+ "items": ACCOUNT,
29
+ "minItems": 0,
30
+ "maxItems": 1000}
31
+
32
+
33
+ ACCOUNT_TYPE = {"description": "Account type",
34
+ "type": "string",
35
+ "enum": ["USER", "GROUP", "SERVICE"]}
36
+
37
+ ACTIVITY = {"description": "Activity name",
38
+ "type": "string",
39
+ "enum": ["Data Brokering", "Data Consolidation", "Data rebalancing",
40
+ "Debug", "Express", "Functional Test", "Group Subscriptions",
41
+ "Production Input", "Production Output",
42
+ "Analysis Input", "Analysis Output", "Staging",
43
+ "T0 Export", "T0 Tape", "Upload/Download (Job)",
44
+ "Upload/Download (User)", "User Subscriptions", "Data Challenge"]}
45
+
46
+ SCOPE_LENGTH = 25
47
+
48
+ SCOPE = {"description": "Scope name",
49
+ "type": "string",
50
+ "pattern": "^[a-zA-Z_\\-.0-9]{1,%s}$" % SCOPE_LENGTH}
51
+
52
+ R_SCOPE = {"description": "Scope name",
53
+ "type": "string",
54
+ "pattern": "\\w"}
55
+
56
+ NAME_LENGTH = 500
57
+
58
+ NAME = {"description": "Data Identifier name",
59
+ "type": "string",
60
+ "pattern": r"^/[A-Za-z0-9\.\-\_\+\/]{1,%s}$" % NAME_LENGTH}
61
+
62
+ R_NAME = {"description": "Data Identifier name",
63
+ "type": "string",
64
+ "pattern": "\\w"}
65
+
66
+ LOCKED = {"description": "Rule locked status",
67
+ "type": ["boolean", "null"]}
68
+
69
+ ASK_APPROVAL = {"description": "Rule approval request",
70
+ "type": ["boolean", "null"]}
71
+
72
+ ASYNCHRONOUS = {"description": "Asynchronous rule creation",
73
+ "type": ["boolean", "null"]}
74
+
75
+ DELAY_INJECTION = {"description": "Time (in seconds) to wait before starting applying the rule. Implies asynchronous rule creation.",
76
+ "type": ["integer", "null"]}
77
+
78
+ PURGE_REPLICAS = {"description": "Rule purge replica status",
79
+ "type": "boolean"}
80
+
81
+ IGNORE_AVAILABILITY = {"description": "Rule ignore availability status",
82
+ "type": "boolean"}
83
+
84
+ RSE = {"description": "RSE name",
85
+ "type": "string",
86
+ "pattern": "^([A-Z0-9]+([_-][A-Z0-9]+)*)$"}
87
+
88
+ RSE_ATTRIBUTE = {"description": "RSE attribute",
89
+ "type": "string",
90
+ "pattern": r'([A-Za-z0-9\._-]+[=<>][A-Za-z0-9_-]+)'}
91
+
92
+ DEFAULT_RSE_ATTRIBUTE = {"description": "Default RSE attribute",
93
+ "type": "string",
94
+ "pattern": r'([A-Z0-9]+([_-][A-Z0-9]+)*)'}
95
+
96
+ REPLICA_STATE = {"description": "Replica state",
97
+ "type": "string",
98
+ "enum": ["AVAILABLE", "UNAVAILABLE", "COPYING", "BEING_DELETED", "BAD", "SOURCE", "A", "U", "C", "B", "D", "S"]}
99
+
100
+ DATE = {"description": "Date",
101
+ "type": "string",
102
+ "pattern": r'((Mon)|(Tue)|(Wed)|(Thu)|(Fri)|(Sat)|(Sun))[,]\s\d{2}\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s(0\d|1\d|2[0-3])(\:)(0\d|1\d|2\d|3\d|4\d|5\d)(\:)(0\d|1\d|2\d|3\d|4\d|5\d)\s(UTC)'}
103
+
104
+ DID_TYPE = {"description": "DID type",
105
+ "type": "string",
106
+ "enum": ["DATASET", "CONTAINER", "FILE", "F"]}
107
+
108
+ GROUPING = {"description": "Rule grouping",
109
+ "type": ["string", "null"],
110
+ "enum": ["DATASET", "NONE", "ALL", None]}
111
+
112
+ NOTIFY = {"description": "Rule notification setting",
113
+ "type": ["string", "null"],
114
+ "enum": ["Y", "C", "N", "P", None]}
115
+
116
+ COMMENT = {"description": "Rule comment",
117
+ "type": ["string", "null"],
118
+ "maxLength": 250}
119
+
120
+ METADATA = {"description": "Rule wfms metadata",
121
+ "type": ["string", "null"],
122
+ "maxLength": 3999}
123
+
124
+ BYTES = {"description": "Size in bytes",
125
+ "type": "integer"}
126
+
127
+ ADLER32 = {"description": "adler32",
128
+ "type": "string",
129
+ "pattern": "^[a-fA-F\\d]{8}$"}
130
+
131
+ WEIGHT = {"description": "Rule weight",
132
+ "type": ["string", "null"]}
133
+
134
+ MD5 = {"description": "md5",
135
+ "type": "string",
136
+ "pattern": "^[a-fA-F\\d]{32}$"}
137
+
138
+ UUID = {"description": "Universally Unique Identifier (UUID)",
139
+ "type": "string",
140
+ "pattern": '^(\\{){0,1}[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}(\\}){0,1}$'}
141
+
142
+ META = {"description": "Data Identifier(DID) metadata",
143
+ "type": "object",
144
+ "properties": {"guid": UUID},
145
+ "additionalProperties": True}
146
+
147
+ PFN = {"description": "Physical File Name", "type": "string"}
148
+
149
+ COPIES = {"description": "Number of replica copies", "type": "integer"}
150
+
151
+ RSE_EXPRESSION = {"description": "RSE expression", "type": "string"}
152
+
153
+ SOURCE_REPLICA_EXPRESSION = {"description": "RSE expression", "type": ["string", "null"]}
154
+
155
+ LIFETIME = {"description": "Lifetime", "type": "number"}
156
+
157
+ RULE_LIFETIME = {"description": "Rule lifetime", "type": ["number", "null"]}
158
+
159
+ SUBSCRIPTION_ID = {"description": "Rule Subscription id", "type": ["string", "null"]}
160
+
161
+ PRIORITY = {"description": "Priority of the transfers",
162
+ "type": "integer"}
163
+
164
+ SPLIT_CONTAINER = {"description": "Rule split container mode",
165
+ "type": ["boolean", "null"]}
166
+
167
+ TIME_ENTRY = {
168
+ "description": "Datetime, ISO 8601",
169
+ "type": "string",
170
+ "pattern": r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d*$'
171
+ }
172
+
173
+ IP = {
174
+ "description": "Internet Protocol address v4, RFC 791",
175
+ "type": "string",
176
+ "pattern": r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}$'
177
+ }
178
+
179
+ CLIENT_STATE = {
180
+ "description": "Client state",
181
+ "type": "string",
182
+ "enum": ['DONE', 'FAILED', 'PROCESSING', 'ALREADY_DONE', 'FILE_NOT_FOUND', 'FOUND_IN_PCACHE', 'DOWNLOAD_ATTEMPT',
183
+ 'FAIL_VALIDATE', 'FOUND_ROOT']
184
+ }
185
+
186
+ RULE = {"description": "Replication rule",
187
+ "type": "object",
188
+ "properties": {"dids": {"type": "array"},
189
+ "account": ACCOUNT,
190
+ "copies": COPIES,
191
+ "rse_expression": RSE_EXPRESSION,
192
+ "grouping": GROUPING,
193
+ "weight": WEIGHT,
194
+ "lifetime": RULE_LIFETIME,
195
+ "locked": LOCKED,
196
+ "subscription_id": SUBSCRIPTION_ID,
197
+ "source_replica_expression": SOURCE_REPLICA_EXPRESSION,
198
+ "activity": ACTIVITY,
199
+ "notify": NOTIFY,
200
+ "purge_replicas": PURGE_REPLICAS,
201
+ "ignore_availability": IGNORE_AVAILABILITY,
202
+ "comment": COMMENT,
203
+ "ask_approval": ASK_APPROVAL,
204
+ "asynchronous": ASYNCHRONOUS,
205
+ "delay_injection": DELAY_INJECTION,
206
+ "priority": PRIORITY,
207
+ 'split_container': SPLIT_CONTAINER,
208
+ 'meta': METADATA},
209
+ "required": ["dids", "copies", "rse_expression"],
210
+ "additionalProperties": False}
211
+
212
+ RULES = {"description": "Array of replication rules",
213
+ "type": "array",
214
+ "items": RULE,
215
+ "minItems": 1,
216
+ "maxItems": 1000}
217
+
218
+ COLLECTION_TYPE = {"description": "Dataset or container type",
219
+ "type": "string",
220
+ "enum": ["DATASET", "CONTAINER"]}
221
+
222
+ COLLECTION = {"description": "Dataset or container",
223
+ "type": "object",
224
+ "properties": {"scope": SCOPE,
225
+ "name": NAME,
226
+ "type": COLLECTION_TYPE,
227
+ "meta": META,
228
+ "rules": RULES},
229
+ "required": ["scope", "name", "type"],
230
+ "additionalProperties": False}
231
+
232
+ COLLECTIONS = {"description": "Array of datasets or containers",
233
+ "type": "array",
234
+ "items": COLLECTION,
235
+ "minItems": 1,
236
+ "maxItems": 1000}
237
+
238
+ DID = {"description": "Data Identifier(DID)",
239
+ "type": "object",
240
+ "properties": {"scope": SCOPE,
241
+ "name": NAME,
242
+ "type": DID_TYPE,
243
+ "meta": META,
244
+ "rules": RULES,
245
+ "bytes": BYTES,
246
+ "adler32": ADLER32,
247
+ "md5": MD5,
248
+ "state": REPLICA_STATE,
249
+ "pfn": PFN},
250
+ "required": ["scope", "name"],
251
+ "additionalProperties": False}
252
+
253
+ DID_FILTERS = {"description": "Array to filter DIDs by metadata",
254
+ "type": "array",
255
+ "additionalProperties": True}
256
+
257
+ R_DID = {"description": "Data Identifier(DID)",
258
+ "type": "object",
259
+ "properties": {"scope": R_SCOPE,
260
+ "name": R_NAME,
261
+ "type": DID_TYPE,
262
+ "meta": META,
263
+ "rules": RULES,
264
+ "bytes": BYTES,
265
+ "adler32": ADLER32,
266
+ "md5": MD5,
267
+ "state": REPLICA_STATE,
268
+ "pfn": PFN},
269
+ "required": ["scope", "name"],
270
+ "additionalProperties": False}
271
+
272
+ DIDS = {"description": "Array of Data Identifiers(DIDs)",
273
+ "type": "array",
274
+ "items": DID,
275
+ "minItems": 1,
276
+ "maxItems": 1000}
277
+
278
+ R_DIDS = {"description": "Array of Data Identifiers(DIDs)",
279
+ "type": "array",
280
+ "items": R_DID,
281
+ "minItems": 1,
282
+ "maxItems": 1000}
283
+
284
+ ATTACHMENT = {"description": "Attachement",
285
+ "type": "object",
286
+ "properties": {"scope": SCOPE,
287
+ "name": NAME,
288
+ "rse": {"description": "RSE name",
289
+ "type": ["string", "null"],
290
+ "pattern": "^([A-Z0-9]+([_-][A-Z0-9]+)*)$"},
291
+ "dids": DIDS},
292
+ "required": ["dids"],
293
+ "additionalProperties": False}
294
+
295
+ ATTACHMENTS = {"description": "Array of attachments",
296
+ "type": "array",
297
+ "items": ATTACHMENT,
298
+ "minItems": 1,
299
+ "maxItems": 1000}
300
+
301
+ SUBSCRIPTION_FILTER = {"type": "object",
302
+ "properties": {"datatype": {"type": "array"},
303
+ "prod_step": {"type": "array"},
304
+ "stream_name": {"type": "array"},
305
+ "project": {"type": "array"},
306
+ "scope": {"type": "array"},
307
+ "pattern": {"type": "string"},
308
+ "excluded_pattern": {"type": "string"},
309
+ "group": {"type": "string"},
310
+ "provenance": {"type": "string"},
311
+ "account": ACCOUNTS,
312
+ "grouping": {"type": "string"},
313
+ "split_rule": {"type": "boolean"}}}
314
+
315
+ ADD_REPLICA_FILE = {"description": "add replica file",
316
+ "type": "object",
317
+ "properties": {"scope": SCOPE,
318
+ "name": NAME,
319
+ "bytes": BYTES,
320
+ "adler32": ADLER32},
321
+ "required": ["scope", "name", "bytes", "adler32"]}
322
+
323
+ ADD_REPLICA_FILES = {"description": "add replica files",
324
+ "type": "array",
325
+ "items": ADD_REPLICA_FILE,
326
+ "minItems": 1,
327
+ "maxItems": 1000}
328
+
329
+ CACHE_ADD_REPLICAS = {"description": "rucio cache add replicas",
330
+ "type": "object",
331
+ "properties": {"files": ADD_REPLICA_FILES,
332
+ "rse": RSE,
333
+ "lifetime": LIFETIME,
334
+ "operation": {"enum": ["add_replicas"]}},
335
+ "required": ['files', 'rse', 'lifetime', 'operation']}
336
+
337
+ DELETE_REPLICA_FILE = {"description": "delete replica file",
338
+ "type": "object",
339
+ "properties": {"scope": SCOPE,
340
+ "name": NAME},
341
+ "required": ["scope", "name"]}
342
+
343
+ DELETE_REPLICA_FILES = {"description": "delete replica files",
344
+ "type": "array",
345
+ "items": DELETE_REPLICA_FILE,
346
+ "minItems": 1,
347
+ "maxItems": 1000}
348
+
349
+ CACHE_DELETE_REPLICAS = {"description": "rucio cache delete replicas",
350
+ "type": "object",
351
+ "properties": {"files": DELETE_REPLICA_FILES,
352
+ "rse": RSE,
353
+ "operation": {"enum": ["delete_replicas"]}},
354
+ "required": ['files', 'rse', 'operation']}
355
+
356
+ MESSAGE_OPERATION = {"type": "object",
357
+ "properties": {'operation': {"enum": ["add_replicas", "delete_replicas"]}}}
358
+
359
+ ACCOUNT_ATTRIBUTE = {"description": "Account attribute",
360
+ "type": "string",
361
+ "pattern": r'^[a-zA-Z0-9-_\\/\\.]{1,30}$'}
362
+
363
+ SCOPE_NAME_REGEXP = '/(.*)/(.*)'
364
+
365
+ DISTANCE = {"description": "RSE distance",
366
+ "type": "object",
367
+ "properties": {
368
+ "src_rse_id": {"type": "string"},
369
+ "dest_rse_id": {"type": "string"},
370
+ "ranking": {"type": "integer"}
371
+ },
372
+ "required": ["src_rse_id", "dest_rse_id", "ranking"],
373
+ "additionalProperties": True}
374
+
375
+ IMPORT = {"description": "import data into rucio.",
376
+ "type": "object",
377
+ "properties": {
378
+ "rses": {
379
+ "type": "object"
380
+ },
381
+ "distances": {
382
+ "type": "object"
383
+ }
384
+ }}
385
+
386
+ SCHEMAS = {'account': ACCOUNT,
387
+ 'account_type': ACCOUNT_TYPE,
388
+ 'activity': ACTIVITY,
389
+ 'name': NAME,
390
+ 'r_name': R_NAME,
391
+ 'rse': RSE,
392
+ 'rse_attribute': RSE_ATTRIBUTE,
393
+ 'scope': SCOPE,
394
+ 'r_scope': R_SCOPE,
395
+ 'did': DID,
396
+ 'did_filters': DID_FILTERS,
397
+ 'r_did': R_DID,
398
+ 'dids': DIDS,
399
+ 'rule': RULE,
400
+ 'r_dids': R_DIDS,
401
+ 'collection': COLLECTION,
402
+ 'collections': COLLECTIONS,
403
+ 'attachment': ATTACHMENT,
404
+ 'attachments': ATTACHMENTS,
405
+ 'subscription_filter': SUBSCRIPTION_FILTER,
406
+ 'cache_add_replicas': CACHE_ADD_REPLICAS,
407
+ 'cache_delete_replicas': CACHE_DELETE_REPLICAS,
408
+ 'account_attribute': ACCOUNT_ATTRIBUTE,
409
+ 'import': IMPORT}
410
+
411
+
412
+ def validate_schema(name, obj):
413
+ """
414
+ Validate object against json schema
415
+
416
+ :param name: The json schema name.
417
+ :param obj: The object to validate.
418
+ """
419
+ try:
420
+ if obj:
421
+ validate(obj, SCHEMAS.get(name, {}))
422
+ except ValidationError as error: # NOQA, pylint: disable=W0612
423
+ raise InvalidObject(f'Problem validating {name}: {error}')
@@ -0,0 +1,160 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright European Organization for Nuclear Research (CERN) since 2012
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Common utility functions for stomp connections
18
+ """
19
+
20
+ import logging
21
+ import socket
22
+ from time import monotonic
23
+ from typing import TYPE_CHECKING
24
+
25
+ from stomp import Connection
26
+
27
+ if TYPE_CHECKING:
28
+ from collections.abc import Callable, Sequence
29
+ from typing import Any
30
+
31
+ LoggerFunction = Callable[..., Any]
32
+
33
+
34
+ def resolve_ips(fqdns: "Sequence[str]", logger: "LoggerFunction" = logging.log):
35
+ logger(logging.DEBUG, 'resolving dns aliases: %s' % fqdns)
36
+ resolved = []
37
+ for fqdn in fqdns:
38
+ addrinfos = socket.getaddrinfo(fqdn, 0, socket.AF_INET, 0, socket.IPPROTO_TCP)
39
+ resolved.extend(ai[4][0] for ai in addrinfos)
40
+ logger(logging.DEBUG, 'dns aliases resolved to %s', resolved)
41
+ return resolved
42
+
43
+
44
+ class StompConnectionManager:
45
+
46
+ def __init__(self):
47
+ self._brokers = None
48
+ self._port = None
49
+ self._use_ssl = None
50
+ self._vhost = None
51
+ self._reconnect_attempts = None
52
+ self._ssl_key_file = None
53
+ self._timeout = None
54
+ self._heartbeats = None
55
+
56
+ self._connections = {}
57
+
58
+ def is_stalled(self, connection: Connection, *, logger: "LoggerFunction" = logging.log):
59
+ if not connection.is_connected():
60
+ return True
61
+
62
+ if self._heartbeats and getattr(connection, 'received_heartbeat') and connection.received_heartbeat:
63
+ heartbeat_period_seconds = max(0, self._heartbeats[0], self._heartbeats[1]) / 1000
64
+
65
+ if not heartbeat_period_seconds:
66
+ return False
67
+
68
+ now = monotonic()
69
+ if connection.received_heartbeat + 10 * heartbeat_period_seconds < now:
70
+ logger(logging.WARNING, "Stomp connection missed heartbeats for a long time")
71
+ return True
72
+
73
+ return False
74
+
75
+ def disconnect(self):
76
+ for conn in self._connections.values():
77
+ if not conn.is_connected():
78
+ conn.disconnect()
79
+
80
+ def re_configure(
81
+ self,
82
+ brokers: "Sequence[str]",
83
+ port: int,
84
+ use_ssl: bool,
85
+ vhost,
86
+ reconnect_attempts: int,
87
+ ssl_key_file,
88
+ ssl_cert_file,
89
+ timeout,
90
+ heartbeats=(0, 1000),
91
+ *,
92
+ logger: "LoggerFunction" = logging.log
93
+ ) -> tuple[list, list]:
94
+
95
+ configuration_changed = any([
96
+ self._brokers != brokers,
97
+ self._port != port,
98
+ self._use_ssl != use_ssl,
99
+ self._vhost != vhost,
100
+ self._reconnect_attempts != reconnect_attempts,
101
+ self._ssl_key_file != ssl_key_file,
102
+ self._timeout != timeout,
103
+ self._heartbeats != heartbeats,
104
+ ])
105
+ if configuration_changed:
106
+ self._brokers = brokers
107
+ self._port = port
108
+ self._use_ssl = use_ssl
109
+ self._vhost = vhost
110
+ self._reconnect_attempts = reconnect_attempts
111
+ self._ssl_key_file = ssl_key_file
112
+ self._timeout = timeout
113
+ self._heartbeats = heartbeats
114
+
115
+ current_remotes = set(self._connections)
116
+ desired_remotes = set((ip, port) for ip in resolve_ips(brokers, logger=logger))
117
+
118
+ if configuration_changed:
119
+ # Re-create all connections
120
+ to_delete = current_remotes
121
+ to_create = desired_remotes
122
+ else:
123
+ to_delete = current_remotes.difference(desired_remotes)
124
+ to_create = desired_remotes.difference(current_remotes)
125
+
126
+ for remote in current_remotes.intersection(desired_remotes):
127
+ conn = self._connections[remote]
128
+
129
+ if self.is_stalled(conn, logger=logger):
130
+ # Re-create stalled connections
131
+ to_delete.add(remote)
132
+ to_create.add(remote)
133
+
134
+ deleted_conns = []
135
+ for remote in to_delete:
136
+ conn = self._connections.pop(remote)
137
+ if conn.is_connected():
138
+ conn.disconnect()
139
+ deleted_conns.append(to_delete)
140
+
141
+ created_conns = []
142
+ for remote in to_create:
143
+ conn = Connection(
144
+ host_and_ports=[remote],
145
+ vhost=vhost,
146
+ timeout=timeout,
147
+ heartbeats=heartbeats,
148
+ reconnect_attempts_max=reconnect_attempts
149
+ )
150
+ if use_ssl:
151
+ conn.set_ssl(key_file=ssl_key_file, cert_file=ssl_cert_file)
152
+ self._connections[remote] = conn
153
+ created_conns.append(conn)
154
+
155
+ if not to_delete and not to_create:
156
+ logger(logging.INFO, "Stomp connections didn't change")
157
+ else:
158
+ logger(logging.INFO, f"Stomp connections refreshed. Deleted: {list(to_delete)}. Added: {list(to_create)}")
159
+
160
+ return created_conns, deleted_conns
@@ -0,0 +1,56 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright European Organization for Nuclear Research (CERN) since 2012
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import time
18
+ from typing import Optional
19
+
20
+
21
+ class Stopwatch:
22
+ """Stopwatch to measure time durations.
23
+
24
+ Note: The stopwatch is started on initialization.
25
+ """
26
+
27
+ _t_start: float
28
+ _t_end: Optional[float]
29
+
30
+ def __init__(self) -> None:
31
+ self.restart()
32
+
33
+ def _now(self) -> float:
34
+ # TODO: change to time.monotonic_ns() if python 3.6 support is dropped.
35
+ return time.monotonic()
36
+
37
+ def restart(self) -> None:
38
+ """Resets and starts the stopwatch."""
39
+ self._t_start = self._now()
40
+ self._t_end = None
41
+
42
+ def stop(self) -> None:
43
+ """Stops the stopwatch."""
44
+ self._t_end = self._now()
45
+
46
+ @property
47
+ def elapsed(self) -> float:
48
+ """Returns the total number of elapsed seconds."""
49
+ if self._t_end is None:
50
+ return self._now() - self._t_start
51
+ else:
52
+ return self._t_end - self._t_start
53
+
54
+ def __float__(self) -> float:
55
+ """Returns the total number of elapsed seconds."""
56
+ return self.elapsed