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