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,1674 @@
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
+ import copy
17
+ import enum
18
+ import itertools
19
+ import logging
20
+ import os
21
+ import random
22
+ import shutil
23
+ import signal
24
+ import subprocess
25
+ import time
26
+ from queue import Queue, Empty, deque
27
+ from threading import Thread
28
+
29
+ from rucio import version
30
+ from rucio.client.client import Client
31
+ from rucio.common.config import config_get
32
+ from rucio.common.didtype import DID
33
+ from rucio.common.exception import (InputValidationError, NoFilesDownloaded, NotAllFilesDownloaded, RucioException)
34
+ from rucio.common.pcache import Pcache
35
+ from rucio.common.utils import GLOBALLY_SUPPORTED_CHECKSUMS, CHECKSUM_ALGO_DICT, PREFERRED_CHECKSUM
36
+ from rucio.common.utils import adler32, detect_client_location, generate_uuid, parse_replicas_from_string, \
37
+ send_trace, sizefmt, execute, parse_replicas_from_file, extract_scope
38
+ from rucio.rse import rsemanager as rsemgr
39
+
40
+
41
+ @enum.unique
42
+ class FileDownloadState(str, enum.Enum):
43
+ """
44
+ The state a file can be in before/while/after downloading.
45
+ """
46
+ PROCESSING = "PROCESSING"
47
+ DOWNLOAD_ATTEMPT = "DOWNLOAD_ATTEMPT"
48
+ DONE = "DONE"
49
+ ALREADY_DONE = "ALREADY_DONE"
50
+ FOUND_IN_PCACHE = "FOUND_IN_PCACHE"
51
+ FILE_NOT_FOUND = "FILE_NOT_FOUND"
52
+ FAIL_VALIDATE = "FAIL_VALIDATE"
53
+ FAILED = "FAILED"
54
+
55
+
56
+ class BaseExtractionTool:
57
+
58
+ def __init__(self, program_name, useability_check_args, extract_args, logger=logging.log):
59
+ """
60
+ Initialises a extraction tool object
61
+
62
+ :param program_name: the name of the archive extraction program, e.g., unzip
63
+ :param useability_check_args: the arguments of the extraction program to test if its installed, e.g., --version
64
+ :param extract_args: the arguments that will be passed to the program for extraction
65
+ :param logger: optional decorated logging.log object that can be passed from the calling daemon or client.
66
+ """
67
+ self.program_name = program_name
68
+ self.useability_check_args = useability_check_args
69
+ self.extract_args = extract_args
70
+ self.logger = logger
71
+ self.is_useable_result = None
72
+
73
+ def is_useable(self):
74
+ """
75
+ Checks if the extraction tool is installed and usable
76
+
77
+ :returns: True if it is usable otherwise False
78
+ """
79
+ if self.is_useable_result is not None:
80
+ return self.is_useable_result
81
+ self.is_usable_result = False
82
+ cmd = '%s %s' % (self.program_name, self.useability_check_args)
83
+ try:
84
+ exitcode, out, err = execute(cmd)
85
+ exitcode = int(exitcode)
86
+ self.logger(logging.DEBUG, '"%s" returned with exitcode %d' % (cmd, exitcode))
87
+ self.is_usable_result = (exitcode == 0)
88
+ except Exception as error:
89
+ self.logger(logging.DEBUG, 'Failed to execute: "%s"' % cmd)
90
+ self.logger(logging.DEBUG, error)
91
+ return self.is_usable_result
92
+
93
+ def try_extraction(self, archive_file_path, file_to_extract, dest_dir_path):
94
+ """
95
+ Calls the extraction program to extract a file from an archive
96
+
97
+ :param archive_file_path: path to the archive
98
+ :param file_to_extract: file name to extract from the archive
99
+ :param dest_dir_path: destination directory where the extracted file will be stored
100
+
101
+ :returns: True on success otherwise False
102
+ """
103
+ if not self.is_useable():
104
+ return False
105
+ args_map = {'archive_file_path': archive_file_path,
106
+ 'file_to_extract': file_to_extract,
107
+ 'dest_dir_path': dest_dir_path}
108
+ extract_args = self.extract_args % args_map
109
+ cmd = '%s %s' % (self.program_name, extract_args)
110
+ try:
111
+ exitcode, out, err = execute(cmd)
112
+ exitcode = int(exitcode)
113
+ self.logger(logging.DEBUG, '"%s" returned with exitcode %d' % (cmd, exitcode))
114
+ return (exitcode == 0)
115
+ except Exception as error:
116
+ self.logger(logging.DEBUG, 'Failed to execute: "%s"' % cmd)
117
+ self.logger(logging.DEBUG, error)
118
+ return False
119
+
120
+
121
+ class DownloadClient:
122
+
123
+ def __init__(self, client=None, logger=None, tracing=True, check_admin=False, check_pcache=False):
124
+ """
125
+ Initialises the basic settings for an DownloadClient object
126
+
127
+ :param client: Optional: rucio.client.client.Client object. If None, a new object will be created.
128
+ :param external_traces: Optional: reference to a list where traces can be added
129
+ :param logger: Optional: logging.Logger object. If None, default logger will be used.
130
+ """
131
+ self.check_pcache = check_pcache
132
+ if not logger:
133
+ self.logger = logging.log
134
+ else:
135
+ self.logger = logger.log
136
+ self.tracing = tracing
137
+ if not self.tracing:
138
+ logger(logging.DEBUG, 'Tracing is turned off.')
139
+ self.is_human_readable = True
140
+ self.client = client if client else Client()
141
+ # if token should be used, use only JWT tokens
142
+ self.auth_token = self.client.auth_token if len(self.client.auth_token.split(".")) == 3 else None
143
+
144
+ self.client_location = detect_client_location()
145
+
146
+ self.is_tape_excluded = True
147
+ self.is_admin = False
148
+ if check_admin:
149
+ account_attributes = list(self.client.list_account_attributes(self.client.account))
150
+ for attr in account_attributes[0]:
151
+ if attr['key'] == 'admin':
152
+ self.is_admin = attr['value'] is True
153
+ break
154
+ if self.is_admin:
155
+ self.is_tape_excluded = False
156
+ logger(logging.DEBUG, 'Admin mode enabled')
157
+
158
+ self.trace_tpl = {}
159
+ self.trace_tpl['hostname'] = self.client_location['fqdn']
160
+ self.trace_tpl['localSite'] = self.client_location['site']
161
+ self.trace_tpl['account'] = self.client.account
162
+ if self.client.vo != 'def':
163
+ self.trace_tpl['vo'] = self.client.vo
164
+ self.trace_tpl['eventType'] = 'download'
165
+ self.trace_tpl['eventVersion'] = 'api_%s' % version.RUCIO_VERSION[0]
166
+
167
+ self.use_cea_threshold = 10
168
+ self.extraction_tools = []
169
+
170
+ # unzip <archive_file_path> <did_name> -d <dest_dir_path>
171
+ extract_args = '%(archive_file_path)s %(file_to_extract)s -d %(dest_dir_path)s'
172
+ self.extraction_tools.append(BaseExtractionTool('unzip', '-v', extract_args, logger=self.logger))
173
+
174
+ # tar -C <dest_dir_path> -xf <archive_file_path> <did_name>
175
+ extract_args = '-C %(dest_dir_path)s -xf %(archive_file_path)s %(file_to_extract)s'
176
+ self.extraction_tools.append(BaseExtractionTool('tar', '--version', extract_args, logger=self.logger))
177
+ self.extract_scope_convention = config_get('common', 'extract_scope', False, None)
178
+
179
+ def download_pfns(self, items, num_threads=2, trace_custom_fields={}, traces_copy_out=None, deactivate_file_download_exceptions=False):
180
+ """
181
+ Download items with a given PFN. This function can only download files, no datasets.
182
+
183
+ :param items: List of dictionaries. Each dictionary describing a file to download. Keys:
184
+ pfn - PFN string of this file
185
+ did - DID string of this file (e.g. 'scope:file.name'). Wildcards are not allowed
186
+ rse - rse name (e.g. 'CERN-PROD_DATADISK'). RSE Expressions are not allowed
187
+ base_dir - Optional: Base directory where the downloaded files will be stored. (Default: '.')
188
+ no_subdir - Optional: If true, files are written directly into base_dir. (Default: False)
189
+ adler32 - Optional: The adler32 checmsum to compare the downloaded files adler32 checksum with
190
+ md5 - Optional: The md5 checksum to compare the downloaded files md5 checksum with
191
+ transfer_timeout - Optional: Timeout time for the download protocols. (Default: None)
192
+ check_local_with_filesize_only - Optional: If true, already downloaded files will not be validated by checksum.
193
+ :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high.
194
+ :param trace_custom_fields: Custom key value pairs to send with the traces
195
+ :param traces_copy_out: reference to an external list, where the traces should be uploaded
196
+ :param deactivate_file_download_exceptions: Boolean, if file download exceptions shouldn't be raised
197
+
198
+
199
+ :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState
200
+ clientState can be one of the following: ALREADY_DONE, DONE, FILE_NOT_FOUND, FAIL_VALIDATE, FAILED
201
+
202
+ :raises InputValidationError: if one of the input items is in the wrong format
203
+ :raises NoFilesDownloaded: if no files could be downloaded
204
+ :raises NotAllFilesDownloaded: if not all files could be downloaded
205
+ :raises RucioException: if something unexpected went wrong during the download
206
+ """
207
+ logger = self.logger
208
+ trace_custom_fields['uuid'] = generate_uuid()
209
+
210
+ logger(logging.INFO, 'Processing %d item(s) for input' % len(items))
211
+ input_items = []
212
+ for item in items:
213
+ did_str = item.get('did')
214
+ pfn = item.get('pfn')
215
+ rse = item.get('rse')
216
+ item['input_dids'] = {DID(did_str): {}}
217
+
218
+ if not did_str or not pfn or not rse:
219
+ logger(logging.DEBUG, item)
220
+ raise InputValidationError('The keys did, pfn, and rse are mandatory')
221
+
222
+ logger(logging.DEBUG, 'Preparing PFN download of %s (%s) from %s' % (did_str, pfn, rse))
223
+
224
+ if '*' in did_str:
225
+ logger(logging.DEBUG, did_str)
226
+ raise InputValidationError('Cannot use PFN download with wildcard in DID')
227
+
228
+ did_scope, did_name = self._split_did_str(did_str)
229
+ dest_dir_path = self._prepare_dest_dir(item.get('base_dir', '.'), did_scope, item.get('no_subdir'))
230
+
231
+ item['scope'] = did_scope
232
+ item['name'] = did_name
233
+ item['sources'] = [{'pfn': pfn, 'rse': rse}]
234
+ did_path_name = did_name
235
+ if did_name.startswith('/'):
236
+ did_path_name = did_name[1:]
237
+ dest_file_path = os.path.join(dest_dir_path, did_path_name)
238
+ item['dest_file_paths'] = [dest_file_path]
239
+ item['temp_file_path'] = '%s.part' % dest_file_path
240
+ options = item.setdefault('merged_options', {})
241
+ options['ignore_checksum'] = 'adler32' not in item and 'md5' not in item
242
+ options.setdefault('transfer_timeout', item.pop('transfer_timeout', None))
243
+
244
+ input_items.append(item)
245
+
246
+ num_files_in = len(input_items)
247
+ output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields, traces_copy_out)
248
+ num_files_out = len(output_items)
249
+
250
+ if not deactivate_file_download_exceptions and num_files_in != num_files_out:
251
+ raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out))
252
+
253
+ return self._check_output(output_items, deactivate_file_download_exceptions=deactivate_file_download_exceptions)
254
+
255
+ def download_dids(self, items, num_threads=2, trace_custom_fields={}, traces_copy_out=None,
256
+ deactivate_file_download_exceptions=False, sort=None):
257
+ """
258
+ Download items with given DIDs. This function can also download datasets and wildcarded DIDs.
259
+
260
+ :param items: List of dictionaries. Each dictionary describing an item to download. Keys:
261
+ did - DID string of this file (e.g. 'scope:file.name')
262
+ filters - Filter to select DIDs for download. Optional if DID is given
263
+ rse - Optional: rse name (e.g. 'CERN-PROD_DATADISK') or rse expression from where to download
264
+ impl - Optional: name of the protocol implementation to be used to download this item.
265
+ no_resolve_archives - Optional: bool indicating whether archives should not be considered for download (Default: False)
266
+ resolve_archives - Deprecated: Use no_resolve_archives instead
267
+ force_scheme - Optional: force a specific scheme to download this item. (Default: None)
268
+ base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.')
269
+ no_subdir - Optional: If true, files are written directly into base_dir. (Default: False)
270
+ nrandom - Optional: if the DID addresses a dataset, nrandom files will be randomly choosen for download from the dataset
271
+ ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False)
272
+ transfer_timeout - Optional: Timeout time for the download protocols. (Default: None)
273
+ transfer_speed_timeout - Optional: Minimum allowed transfer speed (in KBps). Ignored if transfer_timeout set. Otherwise, used to compute default timeout (Default: 500)
274
+ check_local_with_filesize_only - Optional: If true, already downloaded files will not be validated by checksum.
275
+ :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high.
276
+ :param trace_custom_fields: Custom key value pairs to send with the traces.
277
+ :param traces_copy_out: reference to an external list, where the traces should be uploaded
278
+ :param deactivate_file_download_exceptions: Boolean, if file download exceptions shouldn't be raised
279
+ :param sort: Select best replica by replica sorting algorithm. Available algorithms:
280
+ ``geoip`` - based on src/dst IP topographical distance
281
+ ``closeness`` - based on src/dst closeness
282
+ ``dynamic`` - Rucio Dynamic Smart Sort (tm)
283
+
284
+ :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState
285
+
286
+ :raises InputValidationError: if one of the input items is in the wrong format
287
+ :raises NoFilesDownloaded: if no files could be downloaded
288
+ :raises NotAllFilesDownloaded: if not all files could be downloaded
289
+ :raises RucioException: if something unexpected went wrong during the download
290
+ """
291
+ logger = self.logger
292
+ trace_custom_fields['uuid'] = generate_uuid()
293
+
294
+ logger(logging.INFO, 'Processing %d item(s) for input' % len(items))
295
+ did_to_input_items, file_items_with_sources = self._resolve_and_merge_input_items(copy.deepcopy(items), sort=sort)
296
+ self.logger(logging.DEBUG, 'num_unmerged_items=%d; num_dids=%d; num_file_items=%d' % (len(items), len(did_to_input_items), len(file_items_with_sources)))
297
+
298
+ input_items = self._prepare_items_for_download(did_to_input_items, file_items_with_sources)
299
+
300
+ num_files_in = len(input_items)
301
+ output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields, traces_copy_out)
302
+ num_files_out = len(output_items)
303
+
304
+ if not deactivate_file_download_exceptions and num_files_in != num_files_out:
305
+ raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out))
306
+
307
+ return self._check_output(output_items, deactivate_file_download_exceptions=deactivate_file_download_exceptions)
308
+
309
+ def download_from_metalink_file(self, item, metalink_file_path, num_threads=2, trace_custom_fields={}, traces_copy_out=None, deactivate_file_download_exceptions=False):
310
+ """
311
+ Download items using a given metalink file.
312
+
313
+ :param item: dictionary describing an item to download. Keys:
314
+ base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.')
315
+ no_subdir - Optional: If true, files are written directly into base_dir. (Default: False)
316
+ ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False)
317
+ transfer_timeout - Optional: Timeout time for the download protocols. (Default: None)
318
+ check_local_with_filesize_only - Optional: If true, already downloaded files will not be validated by checksum.
319
+
320
+ :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high.
321
+ :param trace_custom_fields: Custom key value pairs to send with the traces.
322
+ :param traces_copy_out: reference to an external list, where the traces should be uploaded
323
+ :param deactivate_file_download_exceptions: Boolean, if file download exceptions shouldn't be raised
324
+
325
+ :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState
326
+
327
+ :raises InputValidationError: if one of the input items is in the wrong format
328
+ :raises NoFilesDownloaded: if no files could be downloaded
329
+ :raises NotAllFilesDownloaded: if not all files could be downloaded
330
+ :raises RucioException: if something unexpected went wrong during the download
331
+ """
332
+ logger = self.logger
333
+
334
+ logger(logging.INFO, 'Getting sources from metalink file')
335
+ metalinks = parse_replicas_from_file(metalink_file_path)
336
+
337
+ trace_custom_fields['uuid'] = generate_uuid()
338
+
339
+ did_to_options = {}
340
+ for metalink in metalinks:
341
+ did = DID(metalink['did'])
342
+ did_to_options[did] = [item]
343
+ metalink['input_dids'] = {did: {}}
344
+
345
+ input_items = self._prepare_items_for_download(did_to_options, metalinks)
346
+
347
+ num_files_in = len(input_items)
348
+ output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields, traces_copy_out)
349
+ num_files_out = len(output_items)
350
+
351
+ if not deactivate_file_download_exceptions and num_files_in != num_files_out:
352
+ raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out))
353
+
354
+ return self._check_output(output_items, deactivate_file_download_exceptions=deactivate_file_download_exceptions)
355
+
356
+ def _download_multithreaded(self, input_items, num_threads, trace_custom_fields={}, traces_copy_out=None):
357
+ """
358
+ Starts an appropriate number of threads to download items from the input list.
359
+ (This function is meant to be used as class internal only)
360
+
361
+ :param input_items: list containing the input items to download
362
+ :param num_threads: suggestion of how many threads should be started
363
+ :param trace_custom_fields: Custom key value pairs to send with the traces
364
+ :param traces_copy_out: reference to an external list, where the traces should be uploaded
365
+
366
+ :returns: list with output items as dictionaries
367
+ """
368
+ logger = self.logger
369
+
370
+ num_files = len(input_items)
371
+ nlimit = 5
372
+ num_threads = max(1, num_threads)
373
+ num_threads = min(num_files, num_threads, nlimit)
374
+
375
+ input_queue = Queue()
376
+ output_queue = Queue()
377
+ input_queue.queue = deque(input_items)
378
+
379
+ if num_threads < 2:
380
+ logger(logging.INFO, 'Using main thread to download %d file(s)' % num_files)
381
+ self._download_worker(input_queue, output_queue, trace_custom_fields, traces_copy_out, '')
382
+ return list(output_queue.queue)
383
+
384
+ logger(logging.INFO, 'Using %d threads to download %d files' % (num_threads, num_files))
385
+ threads = []
386
+ for thread_num in range(0, num_threads):
387
+ log_prefix = 'Thread %s/%s: ' % (thread_num, num_threads)
388
+ kwargs = {'input_queue': input_queue,
389
+ 'output_queue': output_queue,
390
+ 'trace_custom_fields': trace_custom_fields,
391
+ 'traces_copy_out': traces_copy_out,
392
+ 'log_prefix': log_prefix}
393
+ try:
394
+ thread = Thread(target=self._download_worker, kwargs=kwargs)
395
+ thread.start()
396
+ threads.append(thread)
397
+ except Exception as error:
398
+ logger(logging.WARNING, 'Failed to start thread %d' % thread_num)
399
+ logger(logging.DEBUG, error)
400
+
401
+ try:
402
+ logger(logging.DEBUG, 'Waiting for threads to finish')
403
+ for thread in threads:
404
+ thread.join()
405
+ except KeyboardInterrupt:
406
+ logger(logging.WARNING, 'You pressed Ctrl+C! Exiting gracefully')
407
+ for thread in threads:
408
+ thread.kill_received = True
409
+ return list(output_queue.queue)
410
+
411
+ def _download_worker(self, input_queue, output_queue, trace_custom_fields, traces_copy_out, log_prefix):
412
+ """
413
+ This function runs as long as there are items in the input queue,
414
+ downloads them and stores the output in the output queue.
415
+ (This function is meant to be used as class internal only)
416
+
417
+ :param input_queue: queue containing the input items to download
418
+ :param output_queue: queue where the output items will be stored
419
+ :param trace_custom_fields: Custom key value pairs to send with the traces
420
+ :param traces_copy_out: reference to an external list, where the traces should be uploaded
421
+ :param log_prefix: string that will be put at the beginning of every log message
422
+ """
423
+ logger = self.logger
424
+
425
+ logger(logging.DEBUG, '%sStart processing queued downloads' % log_prefix)
426
+ while True:
427
+ try:
428
+ item = input_queue.get_nowait()
429
+ except Empty:
430
+ break
431
+ try:
432
+ trace = copy.deepcopy(self.trace_tpl)
433
+ trace.update(trace_custom_fields)
434
+ download_result = self._download_item(item, trace, traces_copy_out, log_prefix)
435
+ output_queue.put(download_result)
436
+ except KeyboardInterrupt:
437
+ logger(logging.WARNING, 'You pressed Ctrl+C! Exiting gracefully')
438
+ os.kill(os.getpgid(), signal.SIGINT)
439
+ break
440
+ except Exception as error:
441
+ logger(logging.ERROR, '%sFailed to download item' % log_prefix)
442
+ logger(logging.DEBUG, error)
443
+ item["clientState"] = "FAILED"
444
+ output_queue.put(item)
445
+
446
+ @staticmethod
447
+ def _compute_actual_transfer_timeout(item):
448
+ """
449
+ Merge the two options related to timeout into the value which will be used for protocol download.
450
+ :param item: dictionary that describes the item to download
451
+ :return: timeout in seconds
452
+ """
453
+ default_transfer_timeout = 360
454
+ default_transfer_speed_timeout = 500 # KBps
455
+ # Static additive increment of the speed timeout. To include the static cost of
456
+ # establishing connections and download of small files
457
+ transfer_speed_timeout_static_increment = 60
458
+
459
+ transfer_timeout = item.get('merged_options', {}).get('transfer_timeout')
460
+ if transfer_timeout is not None:
461
+ return transfer_timeout
462
+
463
+ transfer_speed_timeout = item.get('merged_options', {}).get('transfer_speed_timeout')
464
+ bytes_ = item.get('bytes')
465
+ if not bytes_ or transfer_speed_timeout is None:
466
+ return default_transfer_timeout
467
+
468
+ if not transfer_speed_timeout > 0:
469
+ transfer_speed_timeout = default_transfer_speed_timeout
470
+
471
+ # Convert from KBytes/s to bytes/s
472
+ transfer_speed_timeout = transfer_speed_timeout * 1000
473
+ timeout = bytes_ // transfer_speed_timeout + transfer_speed_timeout_static_increment
474
+ return timeout
475
+
476
+ def _download_item(self, item, trace, traces_copy_out, log_prefix=''):
477
+ """
478
+ Downloads the given item and sends traces for success/failure.
479
+ (This function is meant to be used as class internal only)
480
+
481
+ :param item: dictionary that describes the item to download
482
+ :param trace: dictionary representing a pattern of trace that will be send
483
+ :param traces_copy_out: reference to an external list, where the traces should be uploaded
484
+ :param log_prefix: string that will be put at the beginning of every log message
485
+
486
+ :returns: dictionary with all attributes from the input item and a clientState attribute
487
+ """
488
+ logger = self.logger
489
+ pcache = Pcache() if self.check_pcache and len(item.get('archive_items', [])) == 0 else None
490
+ did_scope = item['scope']
491
+ did_name = item['name']
492
+ did_str = '%s:%s' % (did_scope, did_name)
493
+ logger(logging.INFO, '%sPreparing download of %s' % (log_prefix, did_str))
494
+
495
+ trace['scope'] = did_scope
496
+ trace['filename'] = did_name
497
+ trace.setdefault('datasetScope', item.get('dataset_scope', ''))
498
+ trace.setdefault('dataset', item.get('dataset_name', ''))
499
+ trace.setdefault('filesize', item.get('bytes'))
500
+ trace.setdefault('clientState', FileDownloadState.PROCESSING)
501
+ trace.setdefault('stateReason', 'UNKNOWN')
502
+
503
+ dest_file_paths = item['dest_file_paths']
504
+
505
+ # appending trace to list reference, if the reference exists
506
+ if traces_copy_out is not None:
507
+ traces_copy_out.append(trace)
508
+
509
+ # if file already exists make sure it exists at all destination paths, set state, send trace, and return
510
+ for dest_file_path in dest_file_paths:
511
+ if os.path.isfile(dest_file_path):
512
+ if item.get('merged_options', {}).get('check_local_with_filesize_only', False):
513
+ local_filesize = os.stat(dest_file_path).st_size
514
+ if item.get('bytes') != local_filesize:
515
+ logger(logging.INFO, '%sFile with same name exists locally, but filesize mismatches: %s' % (log_prefix, did_str))
516
+ logger(logging.DEBUG, '%slocal filesize: %d bytes, expected filesize: %d bytes' % (log_prefix, local_filesize, item.get('bytes')))
517
+ continue
518
+ elif not item.get('merged_options', {}).get('ignore_checksum', False):
519
+ verified, _, _ = _verify_checksum(item, dest_file_path)
520
+ if not verified:
521
+ logger(logging.INFO, '%sFile with same name exists locally, but checksum mismatches: %s' % (log_prefix, did_str))
522
+ continue
523
+
524
+ logger(logging.INFO, '%sFile exists already locally: %s' % (log_prefix, did_str))
525
+ for missing_file_path in dest_file_paths:
526
+ if not os.path.isfile(missing_file_path):
527
+ logger(logging.DEBUG, "copying '%s' to '%s'" % (dest_file_path, missing_file_path))
528
+ shutil.copy2(dest_file_path, missing_file_path)
529
+ item['clientState'] = FileDownloadState.ALREADY_DONE
530
+ trace['transferStart'] = time.time()
531
+ trace['transferEnd'] = time.time()
532
+ trace['clientState'] = FileDownloadState.ALREADY_DONE
533
+ send_trace(trace, self.client.host, self.client.user_agent)
534
+ return item
535
+
536
+ # check if file has replicas
537
+ sources = item.get('sources')
538
+ if not sources or not len(sources):
539
+ logger(logging.WARNING, '%sNo available source found for file: %s' % (log_prefix, did_str))
540
+ item['clientState'] = FileDownloadState.FILE_NOT_FOUND
541
+ trace['clientState'] = FileDownloadState.FILE_NOT_FOUND
542
+ trace['stateReason'] = 'No available sources'
543
+ self._send_trace(trace)
544
+ return item
545
+
546
+ # checking Pcache
547
+ storage_prefix = None
548
+ if pcache:
549
+
550
+ # to check only first replica is enough
551
+ pfn = sources[0]['pfn']
552
+ rse_name = sources[0]['rse']
553
+
554
+ # protocols are needed to extract deterministic part of the pfn
555
+ scheme = None
556
+ prots = self.client.get_protocols(rse_name)
557
+ for prot in prots:
558
+ if prot['scheme'] in pfn and prot['prefix'] in pfn:
559
+ scheme = prot['scheme']
560
+ storage_prefix = prot['prefix']
561
+
562
+ # proceed with the actual check
563
+ logger(logging.INFO, 'Checking whether %s is in pcache' % dest_file_path)
564
+ pcache_state = None
565
+ hardlink_state = None
566
+ try:
567
+ pcache_state, hardlink_state = pcache.check_and_link(src=pfn, storage_root=storage_prefix, dst=dest_file_path)
568
+ except Exception as e:
569
+ logger(logging.WARNING, 'Pcache failure: %s' % str(e))
570
+
571
+ # if file found in pcache, send trace and return
572
+ if pcache_state == 0 and hardlink_state == 1:
573
+ logger(logging.INFO, 'File found in pcache.')
574
+ item['clientState'] = FileDownloadState.FOUND_IN_PCACHE
575
+ trace['transferStart'] = time.time()
576
+ trace['transferEnd'] = time.time()
577
+ trace['clientState'] = FileDownloadState.FOUND_IN_PCACHE
578
+ self._send_trace(trace)
579
+ return item
580
+ else:
581
+ logger(logging.INFO, 'File not found in pcache.')
582
+
583
+ # try different PFNs until one succeeded
584
+ temp_file_path = item['temp_file_path']
585
+ success = False
586
+ i = 0
587
+ while not success and i < len(sources):
588
+ source = sources[i]
589
+ i += 1
590
+ pfn = source['pfn']
591
+ rse_name = source['rse']
592
+ scheme = pfn.split(':')[0]
593
+
594
+ try:
595
+ rse = rsemgr.get_rse_info(rse_name, vo=self.client.vo)
596
+ except RucioException as error:
597
+ logger(logging.WARNING, '%sCould not get info of RSE %s: %s' % (log_prefix, rse_name, error))
598
+ trace['stateReason'] = str(error)
599
+ continue
600
+
601
+ trace['remoteSite'] = rse_name
602
+ trace['clientState'] = FileDownloadState.DOWNLOAD_ATTEMPT
603
+ trace['protocol'] = scheme
604
+
605
+ transfer_timeout = self._compute_actual_transfer_timeout(item)
606
+ timeout_log_string = ""
607
+ if transfer_timeout:
608
+ timeout_log_string = " and timeout of %ds" % transfer_timeout
609
+
610
+ logger(logging.INFO, '%sTrying to download with %s%s from %s: %s ' % (log_prefix, scheme, timeout_log_string, rse_name, did_str))
611
+
612
+ impl = item.get('impl')
613
+ if impl:
614
+ logger(logging.INFO, '%sUsing Implementation (impl): %s ' % (log_prefix, impl))
615
+
616
+ try:
617
+ protocol = rsemgr.create_protocol(rse, operation='read', scheme=scheme, impl=impl, auth_token=self.auth_token, logger=logger)
618
+ protocol.connect()
619
+ except Exception as error:
620
+ logger(logging.WARNING, '%sFailed to create protocol for PFN: %s' % (log_prefix, pfn))
621
+ logger(logging.DEBUG, 'scheme: %s, exception: %s' % (scheme, error))
622
+ trace['stateReason'] = str(error)
623
+ continue
624
+
625
+ logger(logging.INFO, '%sUsing PFN: %s' % (log_prefix, pfn))
626
+ attempt = 0
627
+ retries = 2
628
+ # do some retries with the same PFN if the download fails
629
+ while not success and attempt < retries:
630
+ attempt += 1
631
+ item['attemptnr'] = attempt
632
+
633
+ if os.path.isfile(temp_file_path):
634
+ logger(logging.DEBUG, '%sDeleting existing temporary file: %s' % (log_prefix, temp_file_path))
635
+ os.unlink(temp_file_path)
636
+
637
+ start_time = time.time()
638
+
639
+ try:
640
+ protocol.get(pfn, temp_file_path, transfer_timeout=transfer_timeout)
641
+ success = True
642
+ except Exception as error:
643
+ logger(logging.DEBUG, error)
644
+ trace['clientState'] = FileDownloadState.FAILED
645
+ trace['stateReason'] = str(error)
646
+
647
+ end_time = time.time()
648
+
649
+ if success and not item.get('merged_options', {}).get('ignore_checksum', False):
650
+ verified, rucio_checksum, local_checksum = _verify_checksum(item, temp_file_path)
651
+ if not verified:
652
+ success = False
653
+ os.unlink(temp_file_path)
654
+ logger(logging.WARNING, '%sChecksum validation failed for file: %s' % (log_prefix, did_str))
655
+ logger(logging.DEBUG, 'Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum))
656
+ trace['clientState'] = FileDownloadState.FAIL_VALIDATE
657
+ trace['stateReason'] = 'Checksum validation failed: Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum)
658
+ if not success:
659
+ logger(logging.WARNING, '%sDownload attempt failed. Try %s/%s' % (log_prefix, attempt, retries))
660
+ self._send_trace(trace)
661
+
662
+ protocol.close()
663
+
664
+ if not success:
665
+ logger(logging.ERROR, '%sFailed to download file %s' % (log_prefix, did_str))
666
+ item['clientState'] = FileDownloadState.FAILED
667
+ return item
668
+
669
+ dest_file_path_iter = iter(dest_file_paths)
670
+ first_dest_file_path = next(dest_file_path_iter)
671
+ logger(logging.DEBUG, "renaming '%s' to '%s'" % (temp_file_path, first_dest_file_path))
672
+ os.rename(temp_file_path, first_dest_file_path)
673
+
674
+ # if the file was downloaded with success, it can be linked to pcache
675
+ if pcache:
676
+ logger(logging.INFO, 'File %s is going to be registerred into pcache.' % dest_file_path)
677
+ try:
678
+ pcache_state, hardlink_state = pcache.check_and_link(src=pfn, storage_root=storage_prefix, local_src=first_dest_file_path)
679
+ logger(logging.INFO, 'File %s is now registerred into pcache.' % first_dest_file_path)
680
+ except Exception as e:
681
+ logger(logging.WARNING, 'Failed to load file to pcache: %s' % str(e))
682
+
683
+ for cur_dest_file_path in dest_file_path_iter:
684
+ logger(logging.DEBUG, "copying '%s' to '%s'" % (first_dest_file_path, cur_dest_file_path))
685
+ shutil.copy2(first_dest_file_path, cur_dest_file_path)
686
+
687
+ trace['transferStart'] = start_time
688
+ trace['transferEnd'] = end_time
689
+ trace['clientState'] = FileDownloadState.DONE
690
+ trace['stateReason'] = 'OK'
691
+ item['clientState'] = FileDownloadState.DONE
692
+ self._send_trace(trace)
693
+
694
+ duration = round(end_time - start_time, 2)
695
+ size = item.get('bytes')
696
+ size_str = sizefmt(size, self.is_human_readable)
697
+ if size and duration:
698
+ rate = round((size / duration) * 1e-6, 2)
699
+ logger(logging.INFO, '%sFile %s successfully downloaded. %s in %s seconds = %s MBps' % (log_prefix, did_str, size_str, duration, rate))
700
+ else:
701
+ logger(logging.INFO, '%sFile %s successfully downloaded in %s seconds' % (log_prefix, did_str, duration))
702
+
703
+ file_items_in_archive = item.get('archive_items', [])
704
+ if len(file_items_in_archive) > 0:
705
+ logger(logging.INFO, '%sExtracting %d file(s) from %s' % (log_prefix, len(file_items_in_archive), did_name))
706
+
707
+ archive_file_path = first_dest_file_path
708
+ for file_item in file_items_in_archive:
709
+ extraction_ok = False
710
+ extract_file_name = file_item['name']
711
+ dest_file_path_iter = iter(file_item['dest_file_paths'])
712
+ first_dest_file_path = next(dest_file_path_iter)
713
+ dest_dir = os.path.dirname(first_dest_file_path)
714
+ logger(logging.DEBUG, '%sExtracting %s to %s' % (log_prefix, extract_file_name, dest_dir))
715
+ for extraction_tool in self.extraction_tools:
716
+ if extraction_tool.try_extraction(archive_file_path, extract_file_name, dest_dir):
717
+ extraction_ok = True
718
+ break
719
+
720
+ if not extraction_ok:
721
+ logger(logging.ERROR, 'Extraction of file %s from archive %s failed.' % (extract_file_name, did_name))
722
+ continue
723
+
724
+ first_dest_file_path = os.path.join(dest_dir, extract_file_name)
725
+ for cur_dest_file_path in dest_file_path_iter:
726
+ logger(logging.DEBUG, "copying '%s' to '%s'" % (first_dest_file_path, cur_dest_file_path))
727
+ shutil.copy2(first_dest_file_path, cur_dest_file_path)
728
+
729
+ if not item.get('shall_keep_archive'):
730
+ logger(logging.DEBUG, '%sDeleting archive %s' % (log_prefix, did_name))
731
+ os.remove(archive_file_path)
732
+
733
+ return item
734
+
735
+ def download_aria2c(self, items, trace_custom_fields={}, filters={}, deactivate_file_download_exceptions=False, sort=None):
736
+ """
737
+ Uses aria2c to download the items with given DIDs. This function can also download datasets and wildcarded DIDs.
738
+ It only can download files that are available via https/davs.
739
+ Aria2c needs to be installed and X509_USER_PROXY needs to be set!
740
+
741
+ :param items: List of dictionaries. Each dictionary describing an item to download. Keys:
742
+ did - DID string of this file (e.g. 'scope:file.name'). Wildcards are not allowed
743
+ rse - Optional: rse name (e.g. 'CERN-PROD_DATADISK') or rse expression from where to download
744
+ base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.')
745
+ no_subdir - Optional: If true, files are written directly into base_dir. (Default: False)
746
+ nrandom - Optional: if the DID addresses a dataset, nrandom files will be randomly choosen for download from the dataset
747
+ ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False)
748
+ check_local_with_filesize_only - Optional: If true, already downloaded files will not be validated by checksum.
749
+
750
+ :param trace_custom_fields: Custom key value pairs to send with the traces
751
+ :param filters: dictionary containing filter options
752
+ :param deactivate_file_download_exceptions: Boolean, if file download exceptions shouldn't be raised
753
+ :param sort: Select best replica by replica sorting algorithm. Available algorithms:
754
+ ``geoip`` - based on src/dst IP topographical distance
755
+ ``closeness`` - based on src/dst closeness
756
+ ``dynamic`` - Rucio Dynamic Smart Sort (tm)
757
+
758
+ :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState
759
+
760
+ :raises InputValidationError: if one of the input items is in the wrong format
761
+ :raises NoFilesDownloaded: if no files could be downloaded
762
+ :raises NotAllFilesDownloaded: if not all files could be downloaded
763
+ :raises RucioException: if something went wrong during the download (e.g. aria2c could not be started)
764
+ """
765
+ logger = self.logger
766
+ trace_custom_fields['uuid'] = generate_uuid()
767
+
768
+ rpc_secret = '%x' % (random.getrandbits(64))
769
+ rpc_auth = 'token:%s' % rpc_secret
770
+ rpcproc, aria_rpc = self._start_aria2c_rpc(rpc_secret)
771
+
772
+ for item in items:
773
+ item['force_scheme'] = ['https', 'davs']
774
+ item['no_resolve_archives'] = True
775
+
776
+ logger(logging.INFO, 'Processing %d item(s) for input' % len(items))
777
+ did_to_input_items, file_items_with_sources = self._resolve_and_merge_input_items(copy.deepcopy(items), sort=sort)
778
+ self.logger(logging.DEBUG, 'num_unmerged_items=%d; num_dids=%d; num_file_items=%d' % (len(items), len(did_to_input_items), len(file_items_with_sources)))
779
+
780
+ input_items = self._prepare_items_for_download(did_to_input_items, file_items_with_sources)
781
+
782
+ try:
783
+ output_items = self._download_items_aria2c(input_items, aria_rpc, rpc_auth, trace_custom_fields)
784
+ except Exception as error:
785
+ self.logger(logging.ERROR, 'Unknown exception during aria2c download')
786
+ self.logger(logging.DEBUG, error)
787
+ finally:
788
+ try:
789
+ aria_rpc.aria2.forceShutdown(rpc_auth)
790
+ finally:
791
+ rpcproc.terminate()
792
+
793
+ return self._check_output(output_items, deactivate_file_download_exceptions=deactivate_file_download_exceptions)
794
+
795
+ def _start_aria2c_rpc(self, rpc_secret):
796
+ """
797
+ Starts aria2c in RPC mode as a subprocess. Also creates
798
+ the RPC proxy instance.
799
+ (This function is meant to be used as class internal only)
800
+
801
+ :param rpc_secret: the secret for the RPC proxy
802
+
803
+ :returns: a tupel with the process and the rpc proxy objects
804
+
805
+ :raises RucioException: if the process or the proxy could not be created
806
+ """
807
+ logger = self.logger
808
+ from xmlrpc.client import ServerProxy as RPCServerProxy
809
+
810
+ cmd = 'aria2c '\
811
+ '--enable-rpc '\
812
+ '--certificate=$X509_USER_PROXY '\
813
+ '--private-key=$X509_USER_PROXY '\
814
+ '--ca-certificate=/etc/pki/tls/certs/CERN-bundle.pem '\
815
+ '--quiet=true '\
816
+ '--allow-overwrite=true '\
817
+ '--auto-file-renaming=false '\
818
+ '--stop-with-process=%d '\
819
+ '--rpc-secret=%s '\
820
+ '--rpc-listen-all=false '\
821
+ '--rpc-max-request-size=100M '\
822
+ '--connect-timeout=5 '\
823
+ '--rpc-listen-port=%d'
824
+
825
+ logger(logging.INFO, 'Starting aria2c rpc server...')
826
+
827
+ # trying up to 3 random ports
828
+ for attempt in range(3):
829
+ port = random.randint(1024, 65534)
830
+ logger(logging.DEBUG, 'Trying to start rpc server on port: %d' % port)
831
+ try:
832
+ to_exec = cmd % (os.getpid(), rpc_secret, port)
833
+ logger(logging.DEBUG, to_exec)
834
+ rpcproc = subprocess.Popen(
835
+ cmd,
836
+ shell=True,
837
+ stdin=subprocess.PIPE,
838
+ stdout=subprocess.PIPE,
839
+ stderr=subprocess.PIPE
840
+ )
841
+ except Exception as error:
842
+ raise RucioException('Failed to execute aria2c!', error)
843
+
844
+ # if port is in use aria should fail to start so give it some time
845
+ time.sleep(2)
846
+
847
+ # did it fail?
848
+ if rpcproc.poll() is not None:
849
+ (out, err) = rpcproc.communicate()
850
+ logger(logging.DEBUG, 'Failed to start aria2c with port: %d' % port)
851
+ logger(logging.DEBUG, 'aria2c output: %s' % out)
852
+ else:
853
+ break
854
+
855
+ if rpcproc.poll() is not None:
856
+ raise RucioException('Failed to start aria2c rpc server!')
857
+
858
+ try:
859
+ aria_rpc = RPCServerProxy('http://localhost:%d/rpc' % port)
860
+ except Exception as error:
861
+ rpcproc.kill()
862
+ raise RucioException('Failed to initialise rpc proxy!', error)
863
+ return (rpcproc, aria_rpc)
864
+
865
+ def _download_items_aria2c(self, items, aria_rpc, rpc_auth, trace_custom_fields={}):
866
+ """
867
+ Uses aria2c to download the given items. Aria2c needs to be started
868
+ as RPC background process first and a RPC proxy is needed.
869
+ (This function is meant to be used as class internal only)
870
+
871
+ :param items: list of dictionaries containing one dict for each file to download
872
+ :param aria_rcp: RPCProxy to the aria2c process
873
+ :param rpc_auth: the rpc authentication token
874
+ :param trace_custom_fields: Custom key value pairs to send with the traces
875
+
876
+ :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState
877
+ """
878
+ logger = self.logger
879
+
880
+ gid_to_item = {} # maps an aria2c download id (gid) to the download item
881
+ pfn_to_rse = {}
882
+ items_to_queue = [item for item in items]
883
+
884
+ # items get removed from gid_to_item when they are complete or failed
885
+ while len(gid_to_item) or len(items_to_queue):
886
+ num_queued = 0
887
+
888
+ # queue up to 100 files and then check arias status
889
+ while (num_queued < 100) and len(items_to_queue):
890
+ item = items_to_queue.pop()
891
+
892
+ file_scope = item['scope']
893
+ file_name = item['name']
894
+ file_did_str = '%s:%s' % (file_scope, file_name)
895
+ trace = {'scope': file_scope,
896
+ 'filename': file_name,
897
+ 'datasetScope': item.get('dataset_scope', ''),
898
+ 'dataset': item.get('dataset_name', ''),
899
+ 'protocol': 'https',
900
+ 'remoteSite': '',
901
+ 'filesize': item.get('bytes', None),
902
+ 'transferStart': time.time(),
903
+ 'transferEnd': time.time()}
904
+ trace.update(self.trace_tpl)
905
+ trace.update(trace_custom_fields)
906
+
907
+ # get pfns from all replicas
908
+ pfns = []
909
+ for src in item['sources']:
910
+ pfn = src['pfn']
911
+ if pfn[0:4].lower() == 'davs':
912
+ pfn = pfn.replace('davs', 'https', 1)
913
+ pfns.append(pfn)
914
+ pfn_to_rse[pfn] = src['rse']
915
+
916
+ # does file exist and are sources available?
917
+ # workaround: only consider first dest file path for aria2c download
918
+ dest_file_path = next(iter(item['dest_file_paths']))
919
+ if os.path.isfile(dest_file_path):
920
+ logger(logging.INFO, 'File exists already locally: %s' % file_did_str)
921
+ item['clientState'] = FileDownloadState.ALREADY_DONE
922
+ trace['clientState'] = FileDownloadState.ALREADY_DONE
923
+ self._send_trace(trace)
924
+ elif len(pfns) == 0:
925
+ logger(logging.WARNING, 'No available source found for file: %s' % file_did_str)
926
+ item['clientState'] = FileDownloadState.FILE_NOT_FOUND
927
+ trace['clientState'] = FileDownloadState.FILE_NOT_FOUND
928
+ self._send_trace(trace)
929
+ else:
930
+ item['trace'] = trace
931
+ options = {'dir': os.path.dirname(dest_file_path),
932
+ 'out': os.path.basename(item['temp_file_path'])}
933
+ gid = aria_rpc.aria2.addUri(rpc_auth, pfns, options)
934
+ gid_to_item[gid] = item
935
+ num_queued += 1
936
+ logger(logging.DEBUG, 'Queued file: %s' % file_did_str)
937
+
938
+ # get some statistics
939
+ aria_stat = aria_rpc.aria2.getGlobalStat(rpc_auth)
940
+ num_active = int(aria_stat['numActive'])
941
+ num_waiting = int(aria_stat['numWaiting'])
942
+ num_stopped = int(aria_stat['numStoppedTotal'])
943
+
944
+ # save start time if one of the active downloads has started
945
+ active = aria_rpc.aria2.tellActive(rpc_auth, ['gid', 'completedLength'])
946
+ for dlinfo in active:
947
+ gid = dlinfo['gid']
948
+ if int(dlinfo['completedLength']) > 0:
949
+ gid_to_item[gid].setdefault('transferStart', time.time())
950
+
951
+ stopped = aria_rpc.aria2.tellStopped(rpc_auth, -1, num_stopped, ['gid', 'status', 'files'])
952
+ for dlinfo in stopped:
953
+ gid = dlinfo['gid']
954
+ item = gid_to_item[gid]
955
+
956
+ file_scope = item['scope']
957
+ file_name = item['name']
958
+ file_did_str = '%s:%s' % (file_scope, file_name)
959
+ temp_file_path = item['temp_file_path']
960
+ # workaround: only consider first dest file path for aria2c download
961
+ dest_file_path = next(iter(item['dest_file_paths']))
962
+
963
+ # ensure we didnt miss the active state (e.g. a very fast download)
964
+ start_time = item.setdefault('transferStart', time.time())
965
+ end_time = item.setdefault('transferEnd', time.time())
966
+
967
+ # get used pfn for traces
968
+ trace = item['trace']
969
+ for uri in dlinfo['files'][0]['uris']:
970
+ if uri['status'].lower() == 'used':
971
+ trace['remoteSite'] = pfn_to_rse.get(uri['uri'], '')
972
+
973
+ trace['transferStart'] = start_time
974
+ trace['transferEnd'] = end_time
975
+
976
+ # ensure file exists
977
+ status = dlinfo.get('status', '').lower()
978
+ if status == 'complete' and os.path.isfile(temp_file_path):
979
+ # checksum check
980
+ skip_check = item.get('ignore_checksum', False)
981
+ rucio_checksum = 0 if skip_check else item.get('adler32')
982
+ local_checksum = 0 if skip_check else adler32(temp_file_path)
983
+ if str(rucio_checksum).lstrip('0') == str(local_checksum).lstrip('0'):
984
+ item['clientState'] = FileDownloadState.DONE
985
+ trace['clientState'] = FileDownloadState.DONE
986
+ # remove .part ending
987
+ os.rename(temp_file_path, dest_file_path)
988
+
989
+ # calculate duration
990
+ duration = round(end_time - start_time, 2)
991
+ duration = max(duration, 0.01) # protect against 0 division
992
+ size = item.get('bytes', 0)
993
+ rate = round((size / duration) * 1e-6, 2)
994
+ size_str = sizefmt(size, self.is_human_readable)
995
+ logger(logging.INFO, 'File %s successfully downloaded. %s in %s seconds = %s MBps' % (file_did_str,
996
+ size_str,
997
+ duration,
998
+ rate))
999
+ else:
1000
+ os.unlink(temp_file_path)
1001
+ logger(logging.WARNING, 'Checksum validation failed for file: %s' % file_did_str)
1002
+ logger(logging.DEBUG, 'Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum))
1003
+ item['clientState'] = FileDownloadState.FAIL_VALIDATE
1004
+ trace['clientState'] = FileDownloadState.FAIL_VALIDATE
1005
+ else:
1006
+ logger(logging.ERROR, 'Failed to download file: %s' % file_did_str)
1007
+ logger(logging.DEBUG, 'Aria2c status: %s' % status)
1008
+ item['clientState'] = FileDownloadState.FAILED
1009
+ trace['clientState'] = FileDownloadState.DOWNLOAD_ATTEMPT
1010
+
1011
+ self._send_trace(trace)
1012
+ del item['trace']
1013
+
1014
+ aria_rpc.aria2.removeDownloadResult(rpc_auth, gid)
1015
+ del gid_to_item[gid]
1016
+
1017
+ if len(stopped) > 0:
1018
+ logger(logging.INFO, 'Active: %d, Waiting: %d, Stopped: %d' % (num_active, num_waiting, num_stopped))
1019
+
1020
+ return items
1021
+
1022
+ def _resolve_one_item_dids(self, item):
1023
+ """
1024
+ Resolve scopes or wildcard DIDs to lists of full did names:
1025
+ :param item: One input item
1026
+ """
1027
+ dids = item.get('did')
1028
+ filters = item.get('filters', {})
1029
+ if filters:
1030
+ filters = copy.copy(filters)
1031
+
1032
+ if dids is None:
1033
+ self.logger(logging.DEBUG, 'Resolving DIDs by using filter options')
1034
+ scope = filters.pop('scope')
1035
+ for did in self.client.list_dids(scope, filters=filters, did_type='all', long=True):
1036
+ yield did
1037
+ return
1038
+
1039
+ if not isinstance(dids, list):
1040
+ dids = [dids]
1041
+
1042
+ for did_str in dids:
1043
+ scope, did_name = self._split_did_str(did_str)
1044
+ filters['name'] = did_name
1045
+ any_did_resolved = False
1046
+ for did in self.client.list_dids(scope, filters=filters, did_type='all', long=True):
1047
+ yield did
1048
+ any_did_resolved = True
1049
+
1050
+ # Maintain compatibility with existing code, which expects non-existing DIDs be
1051
+ # passed through in order to correctly set trace state to FILE_NOT_FOUND
1052
+ if not any_did_resolved and '*' not in did_name:
1053
+ yield {'scope': scope, 'name': did_name}
1054
+
1055
+ def _resolve_and_merge_input_items(self, input_items, sort=None):
1056
+ """
1057
+ This function takes the input items given to download_dids etc.
1058
+ and resolves the sources.
1059
+
1060
+ - It first performs a list_dids call to dereference any wildcards and
1061
+ retrieve DID stats (size, length, type).
1062
+ - Next, input items are grouped together by common list_replicas options.
1063
+ For each group, a single list_replicas call is performed.
1064
+ - The resolved File DIDs with sources are finally mapped back to initial
1065
+ input items to be able to correctly retrieve download options
1066
+ (timeout, destination directories, etc)
1067
+
1068
+ :param input_items: List of dictionaries. Each dictionary describing an input item
1069
+
1070
+ :returns: a tuple:
1071
+ - a dictionary that maps the dereferenced(w/o wildcards) input DIDs to a list of input items
1072
+ - and a list with a dictionary for each file DID which has to be downloaded
1073
+
1074
+ :raises InputValidationError: if one of the input items is in the wrong format
1075
+ """
1076
+ logger = self.logger
1077
+
1078
+ # check mandatory options before doing any server calls
1079
+ resolve_archives = False
1080
+ for item in input_items:
1081
+ if item.get('resolve_archives') is not None:
1082
+ logger(logging.WARNING, 'resolve_archives option is deprecated and will be removed in a future release.')
1083
+ item.setdefault('no_resolve_archives', not item.pop('resolve_archives'))
1084
+
1085
+ # If any item needs to resolve archives
1086
+ if not item.get('no_resolve_archives'):
1087
+ resolve_archives = True
1088
+
1089
+ if not item.get('did'):
1090
+ if not item.get('filters', {}).get('scope'):
1091
+ logger(logging.DEBUG, item)
1092
+ raise InputValidationError('Item without did and filter/scope')
1093
+ if resolve_archives:
1094
+ # perhaps we'll need an extraction tool so check what is installed
1095
+ self.extraction_tools = [tool for tool in self.extraction_tools if tool.is_useable()]
1096
+ if len(self.extraction_tools) < 1:
1097
+ logger(logging.WARNING, 'Archive resolution is enabled but no extraction tool is available. '
1098
+ 'Sources whose protocol doesnt support extraction wont be considered for download.')
1099
+
1100
+ # if excluding tapes, we need to list them first
1101
+ tape_rses = []
1102
+ if self.is_tape_excluded:
1103
+ try:
1104
+ tape_rses = [endp['rse'] for endp in self.client.list_rses(rse_expression='istape=true')]
1105
+ except:
1106
+ logger(logging.DEBUG, 'No tapes found.')
1107
+
1108
+ # Matches each dereferenced DID back to a list of input items
1109
+ did_to_input_items = {}
1110
+
1111
+ # Resolve DIDs
1112
+ for item in input_items:
1113
+ resolved_dids = list(self._resolve_one_item_dids(item))
1114
+ if not resolved_dids:
1115
+ logger(logging.WARNING, 'An item didnt have any DIDs after resolving the input: %s.' % item.get('did', item))
1116
+ item['dids'] = resolved_dids
1117
+ for did in resolved_dids:
1118
+ did_to_input_items.setdefault(DID(did), []).append(item)
1119
+
1120
+ if 'CONTAINER' in did.get('did_type', '').upper() or ('length' in did and not did['length']):
1121
+ did_with_size = self.client.get_did(scope=did['scope'], name=did['name'], dynamic_depth='FILE')
1122
+ did['length'] = did_with_size['length']
1123
+ did['bytes'] = did_with_size['bytes']
1124
+
1125
+ # group input items by common options to reduce the number of calls to list_replicas
1126
+ distinct_keys = ['rse', 'force_scheme', 'no_resolve_archives']
1127
+ item_groups = []
1128
+ for item in input_items:
1129
+ found_compatible_group = False
1130
+ if not item.get('nrandom'):
1131
+ # Don't merge items if nrandom is set. Otherwise two items with the same nrandom will be merged into one
1132
+ # and we'll effectively download only half of the desired replicas for each item.
1133
+ for item_group in item_groups:
1134
+ if all(item.get(k) == item_group[0].get(k) for k in distinct_keys):
1135
+ item_group.append(item)
1136
+ found_compatible_group = True
1137
+ break
1138
+ if not found_compatible_group:
1139
+ item_groups.append([item])
1140
+
1141
+ # List replicas for dids
1142
+ merged_items_with_sources = []
1143
+ for item_group in item_groups:
1144
+ # Take configuration from the first item in the group; but dids from all items
1145
+ item = item_group[0]
1146
+ input_dids = {DID(did): did
1147
+ for item in item_group
1148
+ for did in item.get('dids')}
1149
+
1150
+ # since we're using metalink we need to explicitly give all schemes
1151
+ schemes = item.get('force_scheme')
1152
+ if schemes:
1153
+ schemes = schemes if isinstance(schemes, list) else [schemes]
1154
+ logger(logging.DEBUG, 'schemes: %s' % schemes)
1155
+
1156
+ # RSE expression, still with tape endpoints included
1157
+ rse_expression = item.get('rse')
1158
+ logger(logging.DEBUG, 'rse_expression: %s' % rse_expression)
1159
+
1160
+ # obtaining the choice of Implementation
1161
+ impl = item.get('impl')
1162
+ if impl:
1163
+ impl_split = impl.split('.')
1164
+ if len(impl_split) == 1:
1165
+ impl = 'rucio.rse.protocols.' + impl + '.Default'
1166
+ else:
1167
+ impl = 'rucio.rse.protocols.' + impl
1168
+ logger(logging.DEBUG, 'impl: %s' % impl)
1169
+
1170
+ # get PFNs of files and datasets
1171
+ logger(logging.DEBUG, 'num DIDs for list_replicas call: %d' % len(item['dids']))
1172
+
1173
+ nrandom = item.get('nrandom')
1174
+ if nrandom:
1175
+ logger(logging.INFO, 'Selecting %d random replicas from DID(s): %s' % (nrandom, [str(did) for did in input_dids]))
1176
+
1177
+ metalink_str = self.client.list_replicas([{'scope': did.scope, 'name': did.name} for did in input_dids],
1178
+ schemes=schemes,
1179
+ ignore_availability=False,
1180
+ rse_expression=rse_expression,
1181
+ client_location=self.client_location,
1182
+ sort=sort,
1183
+ resolve_archives=not item.get('no_resolve_archives'),
1184
+ resolve_parents=True,
1185
+ nrandom=nrandom,
1186
+ metalink=True)
1187
+ file_items = parse_replicas_from_string(metalink_str)
1188
+ for file in file_items:
1189
+ if impl:
1190
+ file['impl'] = impl
1191
+ elif not item.get('force_scheme'):
1192
+ file['impl'] = self.preferred_impl(file['sources'])
1193
+
1194
+ logger(logging.DEBUG, 'num resolved files: %s' % len(file_items))
1195
+
1196
+ if not nrandom or nrandom != len(file_items):
1197
+ # If list_replicas didn't resolve any file DIDs for any input did, we pass through the input DID.
1198
+ # This is done to keep compatibility with later code which generates "FILE_NOT_FOUND" traces
1199
+ # and output items.
1200
+ # In the special case of nrandom, when serverside filtering is applied, it's "normal" for some input
1201
+ # dids to be ignored as long as we got exactly nrandom file_items from the server.
1202
+ for input_did in input_dids:
1203
+ if not any([input_did == f['did'] or str(input_did) in f['parent_dids'] for f in file_items]):
1204
+ logger(logging.ERROR, 'DID does not exist: %s' % input_did)
1205
+ # TODO: store did directly as DIDType object
1206
+ file_items.append({'did': str(input_did), 'adler32': None, 'md5': None, 'sources': [], 'parent_dids': set(), 'impl': impl or None})
1207
+
1208
+ # filtering out tape sources
1209
+ if self.is_tape_excluded:
1210
+ for file_item in file_items:
1211
+ unfiltered_sources = copy.copy(file_item['sources'])
1212
+ for src in unfiltered_sources:
1213
+ if src['rse'] in tape_rses:
1214
+ file_item['sources'].remove(src)
1215
+ if unfiltered_sources and not file_item['sources']:
1216
+ logger(logging.WARNING, 'The requested DID {} only has replicas on tape. Direct download from tape is prohibited. '
1217
+ 'Please request a transfer to a non-tape endpoint.'.format(file_item['did']))
1218
+
1219
+ # Match the file did back to the dids which were provided to list_replicas.
1220
+ # Later, this will allow to match the file back to input_items via did_to_input_items
1221
+ for file_item in file_items:
1222
+ file_did = DID(file_item['did'])
1223
+
1224
+ file_input_dids = {DID(did) for did in file_item.get('parent_dids', [])}.intersection(input_dids)
1225
+ if file_did in input_dids:
1226
+ file_input_dids.add(file_did)
1227
+ file_item['input_dids'] = {did: input_dids[did] for did in file_input_dids}
1228
+ merged_items_with_sources.extend(file_items)
1229
+
1230
+ return did_to_input_items, merged_items_with_sources
1231
+
1232
+ def _options_from_input_items(self, input_items):
1233
+ """
1234
+ Best-effort generation of download options from multiple input items which resolve to the same file DID.
1235
+ This is done to download each file DID only once, even if it is requested multiple times via overlapping
1236
+ datasets and/or wildcard resolutions in distinct input items.
1237
+
1238
+ Some options can be easily merged. For example: multiple base_dir are all appended to a list. As a result,
1239
+ the file is downloaded once and copied to all desired destinations.
1240
+ Other options are not necessarily compatible. For example, two items requesting two different values for
1241
+ download timeout. We make our best to merge the options in such cases.
1242
+ """
1243
+ options = {}
1244
+ for item in input_items:
1245
+ base_dir = item.get('base_dir', '.')
1246
+ no_subdir = item.get('no_subdir', False)
1247
+ new_transfer_timeout = item.get('transfer_timeout', None)
1248
+ new_transfer_speed_timeout = item.get('transfer_speed_timeout', None)
1249
+
1250
+ options.setdefault('destinations', set()).add((base_dir, no_subdir))
1251
+
1252
+ # Merge some options
1253
+ # The other options of this DID will be inherited from the first item that contained the DID
1254
+ options['ignore_checksum'] = options.get('ignore_checksum') or item.get('ignore_checksum', False)
1255
+ options['check_local_with_filesize_only'] = options.get('check_local_with_filesize_only') or item.get('check_local_with_filesize_only', False)
1256
+
1257
+ # if one item wants to resolve archives we enable it for all items
1258
+ options['resolve_archives'] = (options.get('resolve_archives') or not item.get('no_resolve_archives'))
1259
+
1260
+ cur_transfer_timeout = options.setdefault('transfer_timeout', None)
1261
+ if cur_transfer_timeout is not None and new_transfer_timeout is not None:
1262
+ options['transfer_timeout'] = max(int(cur_transfer_timeout), int(new_transfer_timeout))
1263
+ elif new_transfer_timeout is not None:
1264
+ options['transfer_timeout'] = int(new_transfer_timeout)
1265
+
1266
+ cur_transfer_speed_timeout = options.setdefault('transfer_speed_timeout', None)
1267
+ if cur_transfer_speed_timeout is not None and new_transfer_speed_timeout is not None:
1268
+ options['transfer_speed_timeout'] = min(float(cur_transfer_speed_timeout), float(new_transfer_speed_timeout))
1269
+ elif new_transfer_speed_timeout is not None:
1270
+ options['transfer_speed_timeout'] = float(new_transfer_speed_timeout)
1271
+ return options
1272
+
1273
+ def _prepare_items_for_download(self, did_to_input_items, file_items):
1274
+ """
1275
+ Optimises the amount of files to download
1276
+ (This function is meant to be used as class internal only)
1277
+
1278
+ :param did_to_input_items: dictionary that maps resolved input DIDs to input items
1279
+ :param file_items: list of dictionaries. Each dictionary describes a File DID to download
1280
+
1281
+ :returns: list of dictionaries. Each dictionary describes an element to download
1282
+
1283
+ :raises InputValidationError: if the given input is not valid or incomplete
1284
+ """
1285
+ logger = self.logger
1286
+
1287
+ # maps file item IDs (fiid) to the file item object
1288
+ fiid_to_file_item = {}
1289
+
1290
+ # cea -> client_extract archives to avoid confusion with archives that dont need explicit extraction
1291
+ # this dict will contain all ids of cea's that definitely will be downloaded
1292
+ cea_id_pure_to_fiids = {}
1293
+
1294
+ # this dict will contain ids of cea's that have higher prioritised non cea sources
1295
+ cea_id_mixed_to_fiids = {}
1296
+
1297
+ all_dest_file_paths = set()
1298
+
1299
+ # get replicas for every file of the given dids
1300
+ for file_item in file_items:
1301
+ file_did = DID(file_item['did'])
1302
+ input_items = list(itertools.chain.from_iterable(did_to_input_items.get(did, []) for did in file_item['input_dids']))
1303
+ options = self._options_from_input_items(input_items)
1304
+
1305
+ file_item['scope'] = file_did.scope
1306
+ file_item['name'] = file_did.name
1307
+
1308
+ logger(logging.DEBUG, 'Queueing file: %s' % file_did)
1309
+ logger(logging.DEBUG, 'real parents: %s' % [str(did) for did in file_item['input_dids'] if did != file_did])
1310
+ logger(logging.DEBUG, 'options: %s' % options)
1311
+
1312
+ # prepare destinations folders:
1313
+ dest_file_paths = file_item.get('dest_file_paths', set())
1314
+ for input_did in file_item['input_dids']:
1315
+ for item in did_to_input_items[input_did]:
1316
+ base_dir = item.get('base_dir', '.')
1317
+ no_subdir = item.get('no_subdir', False)
1318
+ file_did_path = file_did.name
1319
+ if input_did != file_did:
1320
+ # if datasets were given: prepare the destination paths for each dataset
1321
+ if self.extract_scope_convention == 'belleii' and file_did_path.startswith('/'):
1322
+ file_did_path = file_did_path.split('/')[-1]
1323
+ path = os.path.join(self._prepare_dest_dir(base_dir, input_did.name, no_subdir), file_did_path)
1324
+ else:
1325
+ # if no datasets were given only prepare the given destination paths
1326
+ if file_did_path.startswith('/'):
1327
+ file_did_path = file_did_path[1:]
1328
+ path = os.path.join(self._prepare_dest_dir(base_dir, file_did.scope, no_subdir), file_did_path)
1329
+
1330
+ if path in all_dest_file_paths:
1331
+ raise RucioException("Multiple file items with same destination file path")
1332
+
1333
+ all_dest_file_paths.add(path)
1334
+ dest_file_paths.add(path)
1335
+
1336
+ # workaround: just take any given dataset for the traces and the output
1337
+ file_item.setdefault('dataset_scope', input_did.scope)
1338
+ file_item.setdefault('dataset_name', input_did.name)
1339
+
1340
+ if not options:
1341
+ continue
1342
+ resolve_archives = options.get('resolve_archives')
1343
+ file_item['merged_options'] = options
1344
+ file_item['dest_file_paths'] = list(dest_file_paths)
1345
+ file_item['temp_file_path'] = '%s.part' % file_item['dest_file_paths'][0]
1346
+
1347
+ # the file did str ist not an unique key for this dict because multiple calls of list_replicas
1348
+ # could result in the same DID multiple times. So we're using the id of the dictionary objects
1349
+ fiid = id(file_item)
1350
+ fiid_to_file_item[fiid] = file_item
1351
+
1352
+ if resolve_archives:
1353
+ min_cea_priority = None
1354
+ num_non_cea_sources = 0
1355
+ cea_ids = []
1356
+ sources = []
1357
+ # go through sources and check how many (non-)cea sources there are,
1358
+ # index cea sources, or remove cea sources if there is no extraction tool
1359
+ for source in file_item['sources']:
1360
+ is_cea = source.get('client_extract', False)
1361
+ if is_cea and (len(self.extraction_tools) > 0):
1362
+ priority = int(source['priority'])
1363
+ if min_cea_priority is None or priority < min_cea_priority:
1364
+ min_cea_priority = priority
1365
+
1366
+ # workaround since we dont have the archive DID use the part behind the last slash of the PFN
1367
+ # this doesn't respect the scope of the archive DID!!!
1368
+ # and we trust that client_extract==True sources dont have any parameters at the end of the PFN
1369
+ cea_id = source['pfn'].split('/')
1370
+ cea_id = cea_id[-1] if len(cea_id[-1]) > 0 else cea_id[-2]
1371
+ cea_ids.append(cea_id)
1372
+
1373
+ sources.append(source)
1374
+ elif not is_cea:
1375
+ num_non_cea_sources += 1
1376
+ sources.append(source)
1377
+ else:
1378
+ # no extraction tool
1379
+ logger(logging.DEBUG, 'client_extract=True; ignoring source: %s' % source['pfn'])
1380
+
1381
+ logger(logging.DEBUG, 'Prepared sources: num_sources=%d/%d; num_non_cea_sources=%d; num_cea_ids=%d'
1382
+ % (len(sources), len(file_item['sources']), num_non_cea_sources, len(cea_ids)))
1383
+
1384
+ file_item['sources'] = sources
1385
+
1386
+ # if there are no cea sources we are done for this item
1387
+ if min_cea_priority is None:
1388
+ continue
1389
+ # decide if file item belongs to the pure or mixed map
1390
+ # if no non-archive src exists or the highest prio src is an archive src we put it in the pure map
1391
+ elif num_non_cea_sources == 0 or min_cea_priority == 1:
1392
+ logger(logging.DEBUG, 'Adding fiid to cea pure map: '
1393
+ 'num_non_cea_sources=%d; min_cea_priority=%d; num_cea_sources=%d'
1394
+ % (num_non_cea_sources, min_cea_priority, len(cea_ids)))
1395
+ for cea_id in cea_ids:
1396
+ cea_id_pure_to_fiids.setdefault(cea_id, set()).add(fiid)
1397
+ file_item.setdefault('cea_ids_pure', set()).add(cea_id)
1398
+ # if there are non-archive sources and archive sources we put it in the mixed map
1399
+ elif len(cea_ids) > 0:
1400
+ logger(logging.DEBUG, 'Adding fiid to cea mixed map: '
1401
+ 'num_non_cea_sources=%d; min_cea_priority=%d; num_cea_sources=%d'
1402
+ % (num_non_cea_sources, min_cea_priority, len(cea_ids)))
1403
+ for cea_id in cea_ids:
1404
+ cea_id_mixed_to_fiids.setdefault(cea_id, set()).add(fiid)
1405
+ file_item.setdefault('cea_ids_mixed', set()).add(cea_id)
1406
+
1407
+ # put all archives from the mixed list into the pure list if they meet
1408
+ # certain conditions, e.g., an archive that is already in the pure list
1409
+ for cea_id_mixed in list(cea_id_mixed_to_fiids.keys()):
1410
+ fiids_mixed = cea_id_mixed_to_fiids[cea_id_mixed]
1411
+ if cea_id_mixed in cea_id_pure_to_fiids:
1412
+ # file from mixed list is already in a pure list
1413
+ logger(logging.DEBUG, 'Mixed ID is already in cea pure map: '
1414
+ 'cea_id_mixed=%s; num_fiids_mixed=%d; num_cea_pure_fiids=%d'
1415
+ % (cea_id_mixed, len(fiids_mixed), len(cea_id_pure_to_fiids[cea_id_mixed])))
1416
+ elif len(fiids_mixed) >= self.use_cea_threshold:
1417
+ # more than use_cea_threshold files are in a common archive
1418
+ logger(logging.DEBUG, 'Number of needed files in cea reached threshold: '
1419
+ 'cea_id_mixed=%s; num_fiids_mixed=%d; threshold=%d'
1420
+ % (cea_id_mixed, len(fiids_mixed), self.use_cea_threshold))
1421
+ else:
1422
+ # dont move from mixed list to pure list
1423
+ continue
1424
+
1425
+ # first add cea_id to pure map so it can be removed from mixed map later
1426
+ cea_id_pure_to_fiids.setdefault(cea_id_mixed, set()).update(fiids_mixed)
1427
+
1428
+ # now update all file_item mixed/pure maps
1429
+ for fiid_mixed in list(fiids_mixed):
1430
+ file_item = fiid_to_file_item[fiid_mixed]
1431
+ # add cea id to file_item pure map
1432
+ file_item.setdefault('cea_ids_pure', set()).add(cea_id_mixed)
1433
+
1434
+ # remove file item mixed map and
1435
+ # remove references from all other mixed archives to file_item
1436
+ for cea_id_mixed2 in file_item.pop('cea_ids_mixed'):
1437
+ cea_id_mixed_to_fiids[cea_id_mixed2].remove(fiid_mixed)
1438
+
1439
+ # finally remove cea_id from mixed map
1440
+ cea_id_mixed_to_fiids.pop(cea_id_mixed)
1441
+
1442
+ for file_item in file_items:
1443
+ cea_ids_pure = file_item.get('cea_ids_pure', set())
1444
+ cea_ids_mixed = file_item.get('cea_ids_mixed', set())
1445
+
1446
+ if len(cea_ids_pure) > 0:
1447
+ logger(logging.DEBUG, 'Removing all non-cea sources of file %s' % file_item['did'])
1448
+ file_item['sources'] = [s for s in file_item['sources'] if s.get('client_extract', False)]
1449
+ elif len(cea_ids_mixed) > 0:
1450
+ logger(logging.DEBUG, 'Removing all cea sources of file %s' % file_item['did'])
1451
+ file_item['sources'] = [s for s in file_item['sources'] if not s.get('client_extract', False)]
1452
+
1453
+ # reduce the amount of archives to download by removing
1454
+ # all redundant pure archives (=all files can be extracted from other archives)
1455
+ for cea_id_pure in list(cea_id_pure_to_fiids.keys()):
1456
+ # if all files of this archive are available in more than one archive the archive is redundant
1457
+ if all(len(fiid_to_file_item[fiid_pure]['cea_ids_pure']) > 1 for fiid_pure in cea_id_pure_to_fiids[cea_id_pure]):
1458
+ for fiid_pure in cea_id_pure_to_fiids[cea_id_pure]:
1459
+ fiid_to_file_item[fiid_pure]['cea_ids_pure'].discard(cea_id_pure)
1460
+ logger(logging.DEBUG, 'Removing redundant archive %s' % cea_id_pure)
1461
+ cea_id_pure_to_fiids.pop(cea_id_pure)
1462
+
1463
+ # remove all archives of a file except a single one so
1464
+ # that each file is assigned to exactly one pure archive
1465
+ for cea_id_pure in cea_id_pure_to_fiids:
1466
+ for fiid_pure in cea_id_pure_to_fiids[cea_id_pure]:
1467
+ cea_ids_pure = fiid_to_file_item[fiid_pure]['cea_ids_pure']
1468
+ for cea_id_pure_other in list(cea_ids_pure):
1469
+ if cea_id_pure != cea_id_pure_other:
1470
+ cea_id_pure_to_fiids[cea_id_pure_other].discard(fiid_pure)
1471
+ cea_ids_pure.discard(cea_id_pure_other)
1472
+
1473
+ download_packs = []
1474
+ cea_id_to_pack = {}
1475
+ for file_item in file_items:
1476
+ cea_ids = file_item.get('cea_ids_pure', set())
1477
+ if len(cea_ids) > 0:
1478
+ cea_id = next(iter(cea_ids))
1479
+ pack = cea_id_to_pack.get(cea_id)
1480
+ if pack is None:
1481
+ scope = file_item['scope']
1482
+ first_dest = next(iter(file_item['merged_options']['destinations']))
1483
+ dest_path = os.path.join(self._prepare_dest_dir(first_dest[0], scope, first_dest[1]), cea_id)
1484
+ pack = {'scope': scope,
1485
+ 'name': cea_id,
1486
+ 'dest_file_paths': [dest_path],
1487
+ 'temp_file_path': '%s.part' % dest_path,
1488
+ 'sources': file_item['sources'],
1489
+ 'merged_options': {'ignore_checksum': True}, # we currently dont have checksums for the archive
1490
+ 'archive_items': []
1491
+ }
1492
+ cea_id_to_pack[cea_id] = pack
1493
+ download_packs.append(pack)
1494
+ file_item.pop('sources')
1495
+ pack['archive_items'].append(file_item)
1496
+ else:
1497
+ download_packs.append(file_item)
1498
+ return download_packs
1499
+
1500
+ def _split_did_str(self, did_str):
1501
+ """
1502
+ Splits a given DID string (e.g. 'scope1:name.file') into its scope and name part
1503
+ (This function is meant to be used as class internal only)
1504
+
1505
+ :param did_str: the DID string that will be splitted
1506
+
1507
+ :returns: the scope- and name part of the given DID
1508
+
1509
+ :raises InputValidationError: if the given DID string is not valid
1510
+ """
1511
+ did = did_str.split(':')
1512
+ if len(did) == 2:
1513
+ did_scope = did[0]
1514
+ did_name = did[1]
1515
+ elif len(did) == 1:
1516
+ if self.extract_scope_convention == 'belleii':
1517
+ scopes = [scope for scope in self.client.list_scopes()]
1518
+ did_scope, did_name = extract_scope(did[0], scopes)
1519
+ else:
1520
+ did = did_str.split('.')
1521
+ did_scope = did[0]
1522
+ if did_scope == 'user' or did_scope == 'group':
1523
+ did_scope = '%s.%s' % (did[0], did[1])
1524
+ did_name = did_str
1525
+ else:
1526
+ raise InputValidationError('%s is not a valid DID. To many colons.' % did_str)
1527
+
1528
+ if did_name.endswith('/'):
1529
+ did_name = did_name[:-1]
1530
+
1531
+ return did_scope, did_name
1532
+
1533
+ def _prepare_dest_dir(self, base_dir, dest_dir_name, no_subdir):
1534
+ """
1535
+ Builds the final destination path for a file and creates the
1536
+ destination directory if it's not existent.
1537
+ (This function is meant to be used as class internal only)
1538
+
1539
+ :param base_dir: base directory part
1540
+ :param dest_dir_name: name of the destination directory
1541
+ :param no_subdir: if no subdirectory should be created
1542
+
1543
+ :returns: the absolut path of the destination directory
1544
+ """
1545
+ # append dest_dir_name, if subdir should be used
1546
+ if dest_dir_name.startswith('/'):
1547
+ dest_dir_name = dest_dir_name[1:]
1548
+ dest_dir_path = os.path.join(os.path.abspath(base_dir), '' if no_subdir else dest_dir_name)
1549
+
1550
+ if not os.path.isdir(dest_dir_path):
1551
+ os.makedirs(dest_dir_path)
1552
+
1553
+ return dest_dir_path
1554
+
1555
+ def _check_output(self, output_items, deactivate_file_download_exceptions=False):
1556
+ """
1557
+ Checks if all files were successfully downloaded
1558
+ (This function is meant to be used as class internal only)
1559
+
1560
+ :param output_items: list of dictionaries describing the downloaded files
1561
+ :param deactivate_file_download_exceptions: Boolean, if file download exceptions shouldn't be raised
1562
+
1563
+ :returns: output_items list
1564
+
1565
+ :raises NoFilesDownloaded:
1566
+ :raises NotAllFilesDownloaded:
1567
+ """
1568
+ success_states = [FileDownloadState.ALREADY_DONE, FileDownloadState.DONE, FileDownloadState.FOUND_IN_PCACHE]
1569
+ num_successful = 0
1570
+ num_failed = 0
1571
+ for item in output_items:
1572
+ clientState = item.get('clientState', FileDownloadState.FAILED)
1573
+ if clientState in success_states:
1574
+ num_successful += 1
1575
+ else:
1576
+ num_failed += 1
1577
+
1578
+ if not deactivate_file_download_exceptions and num_successful == 0:
1579
+ raise NoFilesDownloaded()
1580
+ elif not deactivate_file_download_exceptions and num_failed > 0:
1581
+ raise NotAllFilesDownloaded()
1582
+
1583
+ return output_items
1584
+
1585
+ def _send_trace(self, trace):
1586
+ """
1587
+ Checks if sending trace is allowed and send the trace.
1588
+
1589
+ :param trace: the trace
1590
+ """
1591
+ if self.tracing:
1592
+ send_trace(trace, self.client.trace_host, self.client.user_agent)
1593
+
1594
+ def preferred_impl(self, sources):
1595
+ """
1596
+ Finds the optimum protocol impl preferred by the client and
1597
+ supported by the remote RSE.
1598
+
1599
+ :param sources: List of sources for a given DID
1600
+
1601
+ :raises RucioException(msg): general exception with msg for more details.
1602
+ """
1603
+
1604
+ preferred_protocols = []
1605
+ checked_rses = []
1606
+ supported_impl = None
1607
+
1608
+ try:
1609
+ preferred_impls = config_get('download', 'preferred_impl')
1610
+ except Exception as error:
1611
+ self.logger(logging.INFO, 'No preferred protocol impl in rucio.cfg: %s' % (error))
1612
+ return supported_impl
1613
+ else:
1614
+ preferred_impls = list(preferred_impls.split(', '))
1615
+ i = 0
1616
+ while i < len(preferred_impls):
1617
+ impl = preferred_impls[i]
1618
+ impl_split = impl.split('.')
1619
+ if len(impl_split) == 1:
1620
+ preferred_impls[i] = 'rucio.rse.protocols.' + impl + '.Default'
1621
+ else:
1622
+ preferred_impls[i] = 'rucio.rse.protocols.' + impl
1623
+ i += 1
1624
+
1625
+ for source in sources:
1626
+ if source['rse'] in checked_rses:
1627
+ continue
1628
+ try:
1629
+ rse_settings = rsemgr.get_rse_info(source['rse'], vo=self.client.vo)
1630
+ checked_rses.append(str(source['rse']))
1631
+ except RucioException as error:
1632
+ self.logger(logging.DEBUG, 'Could not get info of RSE %s: %s' % (source['source'], error))
1633
+ continue
1634
+
1635
+ preferred_protocols = [protocol for protocol in reversed(rse_settings['protocols']) if protocol['impl'] in preferred_impls]
1636
+
1637
+ if len(preferred_protocols) == 0:
1638
+ continue
1639
+
1640
+ for protocol in preferred_protocols:
1641
+ if not protocol['domains']['wan'].get("read"):
1642
+ self.logger(logging.WARNING, 'Unsuitable protocol "%s": "WAN Read" operation is not supported' % (protocol['impl']))
1643
+ continue
1644
+ try:
1645
+ supported_protocol = rsemgr.create_protocol(rse_settings, 'read', impl=protocol['impl'], auth_token=self.auth_token, logger=self.logger)
1646
+ supported_protocol.connect()
1647
+ except Exception as error:
1648
+ self.logger(logging.WARNING, 'Failed to create protocol "%s", exception: %s' % (protocol['impl'], error))
1649
+ pass
1650
+ else:
1651
+ self.logger(logging.INFO, 'Preferred protocol impl supported locally and remotely: %s' % (protocol['impl']))
1652
+ supported_impl = protocol['impl']
1653
+ break
1654
+
1655
+ return supported_impl
1656
+
1657
+
1658
+ def _verify_checksum(item, path):
1659
+ rucio_checksum = item.get(PREFERRED_CHECKSUM)
1660
+ local_checksum = None
1661
+ checksum_algo = CHECKSUM_ALGO_DICT.get(PREFERRED_CHECKSUM)
1662
+
1663
+ if rucio_checksum and checksum_algo:
1664
+ local_checksum = checksum_algo(path)
1665
+ return rucio_checksum == local_checksum, rucio_checksum, local_checksum
1666
+
1667
+ for checksum_name in GLOBALLY_SUPPORTED_CHECKSUMS:
1668
+ rucio_checksum = item.get(checksum_name)
1669
+ checksum_algo = CHECKSUM_ALGO_DICT.get(checksum_name)
1670
+ if rucio_checksum and checksum_algo:
1671
+ local_checksum = checksum_algo(path)
1672
+ return rucio_checksum == local_checksum, rucio_checksum, local_checksum
1673
+
1674
+ return False, None, None