ServiceX_DID_Finder_lib 2.0.2__tar.gz → 3.0.0a2__tar.gz
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.
- {servicex_did_finder_lib-2.0.2 → servicex_did_finder_lib-3.0.0a2}/PKG-INFO +3 -4
- {servicex_did_finder_lib-2.0.2 → servicex_did_finder_lib-3.0.0a2}/pyproject.toml +6 -5
- servicex_did_finder_lib-3.0.0a2/src/servicex_did_finder_lib/__init__.py +1 -0
- servicex_did_finder_lib-3.0.0a2/src/servicex_did_finder_lib/accumulator.py +76 -0
- servicex_did_finder_lib-3.0.0a2/src/servicex_did_finder_lib/did_finder_app.py +198 -0
- {servicex_did_finder_lib-2.0.2 → servicex_did_finder_lib-3.0.0a2}/src/servicex_did_finder_lib/servicex_adaptor.py +0 -17
- servicex_did_finder_lib-2.0.2/src/servicex_did_finder_lib/__init__.py +0 -4
- servicex_did_finder_lib-2.0.2/src/servicex_did_finder_lib/communication.py +0 -272
- {servicex_did_finder_lib-2.0.2 → servicex_did_finder_lib-3.0.0a2}/LICENSE +0 -0
- {servicex_did_finder_lib-2.0.2 → servicex_did_finder_lib-3.0.0a2}/src/servicex_did_finder_lib/did_logging.py +0 -0
- {servicex_did_finder_lib-2.0.2 → servicex_did_finder_lib-3.0.0a2}/src/servicex_did_finder_lib/did_summary.py +0 -0
- {servicex_did_finder_lib-2.0.2 → servicex_did_finder_lib-3.0.0a2}/src/servicex_did_finder_lib/util_uri.py +0 -0
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: ServiceX_DID_Finder_lib
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0a2
|
|
4
4
|
Summary: ServiceX DID Library Routines
|
|
5
5
|
Author: Gordon Watts
|
|
6
6
|
Author-email: gwatts@uw.edu
|
|
7
|
-
Requires-Python: >=3.8,<4.0
|
|
7
|
+
Requires-Python: >=3.8.1,<4.0.0
|
|
8
8
|
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
10
9
|
Classifier: Programming Language :: Python :: 3.9
|
|
11
10
|
Classifier: Programming Language :: Python :: 3.10
|
|
12
11
|
Classifier: Programming Language :: Python :: 3.11
|
|
13
12
|
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Requires-Dist: Celery (>=5.4,<6.0)
|
|
14
14
|
Requires-Dist: make-it-sync (>=1.0.0,<2.0.0)
|
|
15
|
-
Requires-Dist: pika (==1.1.0)
|
|
16
15
|
Requires-Dist: requests (>=2.25.0,<3.0.0)
|
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "ServiceX_DID_Finder_lib"
|
|
3
|
-
version = "
|
|
3
|
+
version = "3.0.0-alpha.2"
|
|
4
4
|
description = "ServiceX DID Library Routines"
|
|
5
5
|
authors = ["Gordon Watts <gwatts@uw.edu>"]
|
|
6
6
|
|
|
7
7
|
[tool.poetry.dependencies]
|
|
8
|
-
python = "^3.8"
|
|
9
|
-
pika = "1.1.0"
|
|
8
|
+
python = "^3.8.1"
|
|
10
9
|
make-it-sync = "^1.0.0"
|
|
11
10
|
requests = "^2.25.0"
|
|
11
|
+
Celery= "^5.4"
|
|
12
|
+
|
|
12
13
|
|
|
13
14
|
[tool.poetry.group.dev]
|
|
14
15
|
optional = true
|
|
15
16
|
|
|
16
17
|
[tool.poetry.group.dev.dependencies]
|
|
17
|
-
pytest = "^
|
|
18
|
-
flake8 = "^
|
|
18
|
+
pytest = "^8.2"
|
|
19
|
+
flake8 = "^7.1"
|
|
19
20
|
pytest-mock = "^3.12.0"
|
|
20
21
|
coverage = "^7.4.0"
|
|
21
22
|
responses = "^0.14.0"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .did_finder_app import DIDFinderApp # NOQA F401
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Copyright (c) 2024, IRIS-HEP
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Redistribution and use in source and binary forms, with or without
|
|
5
|
+
# modification, are permitted provided that the following conditions are met:
|
|
6
|
+
#
|
|
7
|
+
# * Redistributions of source code must retain the above copyright notice, this
|
|
8
|
+
# list of conditions and the following disclaimer.
|
|
9
|
+
#
|
|
10
|
+
# * Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
# and/or other materials provided with the distribution.
|
|
13
|
+
#
|
|
14
|
+
# * Neither the name of the copyright holder nor the names of its
|
|
15
|
+
# contributors may be used to endorse or promote products derived from
|
|
16
|
+
# this software without specific prior written permission.
|
|
17
|
+
#
|
|
18
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
19
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
20
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
22
|
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
23
|
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
24
|
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
25
|
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
26
|
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
27
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
28
|
+
from typing import List, Dict, Any, Union
|
|
29
|
+
|
|
30
|
+
from servicex_did_finder_lib.did_summary import DIDSummary
|
|
31
|
+
from servicex_did_finder_lib.servicex_adaptor import ServiceXAdapter
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Accumulator:
|
|
35
|
+
"""Track or cache files depending on the mode we are operating in"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, sx: ServiceXAdapter, sum: DIDSummary):
|
|
38
|
+
self.servicex = sx
|
|
39
|
+
self.summary = sum
|
|
40
|
+
self.file_cache: List[Dict[str, Any]] = []
|
|
41
|
+
|
|
42
|
+
def add(self, file_info: Union[Dict[str, Any], List[Dict[str, Any]]]):
|
|
43
|
+
"""
|
|
44
|
+
Track and inject the file back into the system
|
|
45
|
+
:param file_info: The file information to track can be a single record or a list
|
|
46
|
+
"""
|
|
47
|
+
if isinstance(file_info, dict):
|
|
48
|
+
self.file_cache.append(file_info)
|
|
49
|
+
elif isinstance(file_info, list):
|
|
50
|
+
self.file_cache.extend(file_info)
|
|
51
|
+
else:
|
|
52
|
+
raise ValueError("Invalid input: expected a dictionary or a list of dictionaries")
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def cache_len(self) -> int:
|
|
56
|
+
return len(self.file_cache)
|
|
57
|
+
|
|
58
|
+
def send_on(self, count):
|
|
59
|
+
"""
|
|
60
|
+
Send the accumulated files
|
|
61
|
+
:param count: The number of files to send. Set to -1 to send all
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
# Sort the list to insure reproducibility
|
|
65
|
+
files = sorted(self.file_cache, key=lambda x: x["paths"])
|
|
66
|
+
self.send_bulk(files[:count])
|
|
67
|
+
self.file_cache.clear()
|
|
68
|
+
|
|
69
|
+
def send_bulk(self, file_list: List[Dict[str, Any]]):
|
|
70
|
+
"""
|
|
71
|
+
does a bulk put of files
|
|
72
|
+
:param file_list: The list of files to send
|
|
73
|
+
"""
|
|
74
|
+
for ifl in file_list:
|
|
75
|
+
self.summary.add_file(ifl)
|
|
76
|
+
self.servicex.put_file_add_bulk(file_list)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# Copyright (c) 2022, IRIS-HEP
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Redistribution and use in source and binary forms, with or without
|
|
5
|
+
# modification, are permitted provided that the following conditions are met:
|
|
6
|
+
#
|
|
7
|
+
# * Redistributions of source code must retain the above copyright notice, this
|
|
8
|
+
# list of conditions and the following disclaimer.
|
|
9
|
+
#
|
|
10
|
+
# * Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
# and/or other materials provided with the distribution.
|
|
13
|
+
#
|
|
14
|
+
# * Neither the name of the copyright holder nor the names of its
|
|
15
|
+
# contributors may be used to endorse or promote products derived from
|
|
16
|
+
# this software without specific prior written permission.
|
|
17
|
+
#
|
|
18
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
19
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
20
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
22
|
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
23
|
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
24
|
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
25
|
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
26
|
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
27
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
28
|
+
import argparse
|
|
29
|
+
import logging
|
|
30
|
+
from datetime import datetime
|
|
31
|
+
from typing import Any, Generator, Callable, Dict, Optional
|
|
32
|
+
|
|
33
|
+
from celery import Celery, Task
|
|
34
|
+
|
|
35
|
+
from servicex_did_finder_lib.accumulator import Accumulator
|
|
36
|
+
from servicex_did_finder_lib.did_logging import initialize_root_logger
|
|
37
|
+
from servicex_did_finder_lib.did_summary import DIDSummary
|
|
38
|
+
from servicex_did_finder_lib.servicex_adaptor import ServiceXAdapter
|
|
39
|
+
from servicex_did_finder_lib.util_uri import parse_did_uri
|
|
40
|
+
|
|
41
|
+
# The type for the callback method to handle DID's, supplied by the user.
|
|
42
|
+
# Arguments are:
|
|
43
|
+
# - The DID to process
|
|
44
|
+
# - A dictionary of information about the DID request
|
|
45
|
+
# - A dictionary of arguments passed to the DID finder
|
|
46
|
+
UserDIDHandler = Callable[
|
|
47
|
+
[str, Dict[str, Any], Dict[str, Any]],
|
|
48
|
+
Generator[Dict[str, Any], None, None]
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
__logging = logging.getLogger(__name__)
|
|
53
|
+
__logging.addHandler(logging.NullHandler())
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class DIDFinderTask(Task):
|
|
57
|
+
"""
|
|
58
|
+
A Celery task that will process a single DID request. This task will
|
|
59
|
+
call the user supplied DID finder to get the list of files associated
|
|
60
|
+
with the DID, and then send that list to ServiceX for processing.
|
|
61
|
+
"""
|
|
62
|
+
def __init__(self):
|
|
63
|
+
super().__init__()
|
|
64
|
+
self.logger = logging.getLogger(__name__)
|
|
65
|
+
self.logger.addHandler(logging.NullHandler())
|
|
66
|
+
|
|
67
|
+
def do_lookup(self, did: str, dataset_id: int, endpoint: str, user_did_finder: UserDIDHandler):
|
|
68
|
+
"""
|
|
69
|
+
Perform the DID lookup for the given DID. This will call the user supplied
|
|
70
|
+
DID finder to get the list of files associated with the DID, and then send
|
|
71
|
+
that list to ServiceX for processing.
|
|
72
|
+
After all of the files have been sent, send a message to ServiceX indicating
|
|
73
|
+
that the fileset is complete
|
|
74
|
+
Args:
|
|
75
|
+
did: The DID to process
|
|
76
|
+
dataset_id: The dataset ID for the request
|
|
77
|
+
endpoint: The ServiceX endpoint to send the request to
|
|
78
|
+
user_did_finder: The user supplied DID finder to call to get the list of files
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
self.logger.info(
|
|
82
|
+
f"Received DID request {did}",
|
|
83
|
+
extra={"dataset_id": dataset_id}
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
servicex = ServiceXAdapter(dataset_id=dataset_id, endpoint=endpoint)
|
|
87
|
+
|
|
88
|
+
info = {
|
|
89
|
+
"dataset-id": dataset_id,
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
start_time = datetime.now()
|
|
93
|
+
|
|
94
|
+
summary = DIDSummary(did)
|
|
95
|
+
did_info = parse_did_uri(did)
|
|
96
|
+
acc = Accumulator(servicex, summary)
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
for file_info in user_did_finder(did_info.did, info, self.app.did_finder_args):
|
|
100
|
+
acc.add(file_info)
|
|
101
|
+
|
|
102
|
+
acc.send_on(did_info.file_count)
|
|
103
|
+
except Exception as e:
|
|
104
|
+
self.logger.error(
|
|
105
|
+
f"Error processing DID {did}: {e}",
|
|
106
|
+
extra={"dataset_id": dataset_id}
|
|
107
|
+
)
|
|
108
|
+
finally:
|
|
109
|
+
elapsed_time = int((datetime.now() - start_time).total_seconds())
|
|
110
|
+
servicex.put_fileset_complete(
|
|
111
|
+
{
|
|
112
|
+
"files": summary.file_count,
|
|
113
|
+
"files-skipped": summary.files_skipped,
|
|
114
|
+
"total-events": summary.total_events,
|
|
115
|
+
"total-bytes": summary.total_bytes,
|
|
116
|
+
"elapsed-time": elapsed_time,
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class DIDFinderApp:
|
|
122
|
+
"""
|
|
123
|
+
The main application for a DID finder. This will setup the Celery application
|
|
124
|
+
and start the worker to process the DID requests.
|
|
125
|
+
"""
|
|
126
|
+
def __init__(self, did_finder_name: str,
|
|
127
|
+
parsed_args: Optional[argparse.Namespace] = None):
|
|
128
|
+
"""
|
|
129
|
+
Initialize the DID finder application
|
|
130
|
+
Args:
|
|
131
|
+
did_finder_name: The name of the DID finder
|
|
132
|
+
parsed_args: The parsed command line arguments. Leave as None to use the default parser
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
self.name = did_finder_name
|
|
136
|
+
self.parsed_args = vars(parsed_args) if parsed_args else None
|
|
137
|
+
|
|
138
|
+
# Setup command line parsing
|
|
139
|
+
if self.parsed_args is None:
|
|
140
|
+
parser = argparse.ArgumentParser()
|
|
141
|
+
self.add_did_finder_cnd_arguments(parser)
|
|
142
|
+
self.parsed_args = vars(parser.parse_args())
|
|
143
|
+
|
|
144
|
+
initialize_root_logger(self.name)
|
|
145
|
+
|
|
146
|
+
self.app = Celery(f"did_finder_{self.name}", broker_url=self.parsed_args['rabbit_uri'])
|
|
147
|
+
|
|
148
|
+
# Cache the args in the App so they are accessible to the tasks
|
|
149
|
+
self.app.did_finder_args = self.parsed_args
|
|
150
|
+
|
|
151
|
+
def did_lookup_task(self, name):
|
|
152
|
+
"""
|
|
153
|
+
Decorator to create a new task to handle a DID lookup request wihout
|
|
154
|
+
needing to know about Celery tasks.
|
|
155
|
+
Usage:
|
|
156
|
+
@app.did_lookup_task(name="did_finder_cern_opendata.lookup_dataset")
|
|
157
|
+
def lookup_dataset(self, did: str, dataset_id: int, endpoint: str) -> None:
|
|
158
|
+
self.do_lookup(did=did, dataset_id=dataset_id,
|
|
159
|
+
endpoint=endpoint, user_did_finder=find_files)
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
name: The name of the task
|
|
163
|
+
"""
|
|
164
|
+
def decorator(func):
|
|
165
|
+
@self.app.task(base=DIDFinderTask, bind=True, name=name)
|
|
166
|
+
def wrapper(*args, **kwargs):
|
|
167
|
+
return func(*args, **kwargs)
|
|
168
|
+
return wrapper
|
|
169
|
+
return decorator
|
|
170
|
+
|
|
171
|
+
def start(self):
|
|
172
|
+
self.app.worker_main(argv=['worker', '--loglevel=INFO'])
|
|
173
|
+
|
|
174
|
+
@classmethod
|
|
175
|
+
def add_did_finder_cnd_arguments(cls, parser: argparse.ArgumentParser):
|
|
176
|
+
"""add_did_finder_cnd_arguments Add required arguments to a parser
|
|
177
|
+
|
|
178
|
+
If you need to parse command line arguments for some special configuration, create your
|
|
179
|
+
own argument parser, and call this function to make sure the arguments needed
|
|
180
|
+
for running the back-end communication are filled in properly.
|
|
181
|
+
|
|
182
|
+
Then pass the results of the parsing to the DID Finder App's constructor method.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
parser (argparse.ArgumentParser): The argument parser. Arguments needed for the
|
|
186
|
+
did finder/servicex communication will be added.
|
|
187
|
+
"""
|
|
188
|
+
parser.add_argument(
|
|
189
|
+
"--rabbit-uri", dest="rabbit_uri", action="store", required=True
|
|
190
|
+
)
|
|
191
|
+
parser.add_argument(
|
|
192
|
+
"--prefix",
|
|
193
|
+
dest="prefix",
|
|
194
|
+
action="store",
|
|
195
|
+
required=False,
|
|
196
|
+
default="",
|
|
197
|
+
help="Prefix to add to use a caching proxy for URIs",
|
|
198
|
+
)
|
|
@@ -51,23 +51,6 @@ class ServiceXAdapter:
|
|
|
51
51
|
'file_events': file_info['file_events']
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
def put_file_add(self, file_info):
|
|
55
|
-
success = False
|
|
56
|
-
attempts = 0
|
|
57
|
-
while not success and attempts < MAX_RETRIES:
|
|
58
|
-
try:
|
|
59
|
-
mesg = self._create_json(file_info)
|
|
60
|
-
requests.put(f"{self.endpoint}{self.dataset_id}/files", json=mesg)
|
|
61
|
-
self.logger.info("adding file:", extra=file_info)
|
|
62
|
-
success = True
|
|
63
|
-
except requests.exceptions.ConnectionError:
|
|
64
|
-
self.logger.exception(f'Connection error to ServiceX App. Will retry '
|
|
65
|
-
f'(try {attempts} out of {MAX_RETRIES}')
|
|
66
|
-
attempts += 1
|
|
67
|
-
if not success:
|
|
68
|
-
self.logger.error(f'After {attempts} tries, failed to send ServiceX App a put_file '
|
|
69
|
-
f'message: {str(file_info)} - Ignoring error.')
|
|
70
|
-
|
|
71
54
|
def put_file_add_bulk(self, file_list, chunk_length=300):
|
|
72
55
|
# we first chunk up file_list as it can be very large in
|
|
73
56
|
# case there are a lot of replicas and a lot of files.
|
|
@@ -1,272 +0,0 @@
|
|
|
1
|
-
import argparse
|
|
2
|
-
from datetime import datetime
|
|
3
|
-
import json
|
|
4
|
-
import logging
|
|
5
|
-
import time
|
|
6
|
-
from typing import Any, AsyncGenerator, Callable, Dict, List, Optional
|
|
7
|
-
import sys
|
|
8
|
-
|
|
9
|
-
import pika
|
|
10
|
-
from make_it_sync import make_sync
|
|
11
|
-
|
|
12
|
-
from servicex_did_finder_lib.did_summary import DIDSummary
|
|
13
|
-
from servicex_did_finder_lib.did_logging import initialize_root_logger
|
|
14
|
-
from servicex_did_finder_lib.util_uri import parse_did_uri
|
|
15
|
-
from .servicex_adaptor import ServiceXAdapter
|
|
16
|
-
|
|
17
|
-
# The type for the callback method to handle DID's, supplied by the user.
|
|
18
|
-
UserDIDHandler = Callable[[str, Dict[str, Any]], AsyncGenerator[Dict[str, Any], None]]
|
|
19
|
-
|
|
20
|
-
# Given name, build the RabbitMQ queue name by appending this.
|
|
21
|
-
# This is backed into how ServiceX works - do not change unless it
|
|
22
|
-
# is also changed in the ServiceX_App
|
|
23
|
-
QUEUE_NAME_POSTFIX = "_did_requests"
|
|
24
|
-
|
|
25
|
-
# Easy to use local logger
|
|
26
|
-
__logging = logging.getLogger(__name__)
|
|
27
|
-
__logging.addHandler(logging.NullHandler())
|
|
28
|
-
|
|
29
|
-
# TODO: get rid of different modes. It should always be batch.
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
class _accumulator:
|
|
33
|
-
"Track or cache files depending on the mode we are operating in"
|
|
34
|
-
|
|
35
|
-
def __init__(self, sx: ServiceXAdapter, sum: DIDSummary, hold_till_end: bool):
|
|
36
|
-
self._servicex = sx
|
|
37
|
-
self._summary = sum
|
|
38
|
-
self._hold_till_end = hold_till_end
|
|
39
|
-
self._file_cache: List[Dict[str, Any]] = []
|
|
40
|
-
|
|
41
|
-
def add(self, file_info: Dict[str, Any]):
|
|
42
|
-
"Track and inject the file back into the system"
|
|
43
|
-
if self._hold_till_end:
|
|
44
|
-
self._file_cache.append(file_info)
|
|
45
|
-
else:
|
|
46
|
-
self._summary.add_file(file_info)
|
|
47
|
-
self._servicex.put_file_add(file_info)
|
|
48
|
-
|
|
49
|
-
def send_on(self, count):
|
|
50
|
-
"Send the accumulated files"
|
|
51
|
-
if self._hold_till_end:
|
|
52
|
-
self._hold_till_end = False
|
|
53
|
-
files = sorted(self._file_cache, key=lambda x: x["paths"])
|
|
54
|
-
self.send_bulk(files[:count])
|
|
55
|
-
|
|
56
|
-
def send_bulk(self, file_list: List[Dict[str, Any]]):
|
|
57
|
-
"does a bulk put of files"
|
|
58
|
-
if self._hold_till_end:
|
|
59
|
-
for f in file_list:
|
|
60
|
-
self.add(f)
|
|
61
|
-
else:
|
|
62
|
-
for ifl in file_list:
|
|
63
|
-
self._summary.add_file(ifl)
|
|
64
|
-
self._servicex.put_file_add_bulk(file_list)
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
async def run_file_fetch_loop(
|
|
68
|
-
did: str,
|
|
69
|
-
servicex: ServiceXAdapter,
|
|
70
|
-
info: Dict[str, Any],
|
|
71
|
-
user_callback: UserDIDHandler,
|
|
72
|
-
):
|
|
73
|
-
start_time = datetime.now()
|
|
74
|
-
|
|
75
|
-
summary = DIDSummary(did)
|
|
76
|
-
did_info = parse_did_uri(did)
|
|
77
|
-
hold_till_end = did_info.file_count != -1
|
|
78
|
-
acc = _accumulator(servicex, summary, hold_till_end)
|
|
79
|
-
|
|
80
|
-
try:
|
|
81
|
-
async for file_info in user_callback(did_info.did, info):
|
|
82
|
-
if type(file_info) is dict:
|
|
83
|
-
acc.add(file_info)
|
|
84
|
-
else:
|
|
85
|
-
acc.send_bulk(file_info)
|
|
86
|
-
|
|
87
|
-
except Exception:
|
|
88
|
-
if did_info.get_mode == "all":
|
|
89
|
-
raise
|
|
90
|
-
|
|
91
|
-
# If we've been holding onto any files, we need to send them now.
|
|
92
|
-
acc.send_on(did_info.file_count)
|
|
93
|
-
|
|
94
|
-
elapsed_time = int((datetime.now() - start_time).total_seconds())
|
|
95
|
-
servicex.put_fileset_complete(
|
|
96
|
-
{
|
|
97
|
-
"files": summary.file_count,
|
|
98
|
-
"files-skipped": summary.files_skipped,
|
|
99
|
-
"total-events": summary.total_events,
|
|
100
|
-
"total-bytes": summary.total_bytes,
|
|
101
|
-
"elapsed-time": elapsed_time,
|
|
102
|
-
}
|
|
103
|
-
)
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def rabbit_mq_callback(
|
|
107
|
-
user_callback: UserDIDHandler, channel, method, properties, body
|
|
108
|
-
):
|
|
109
|
-
"""rabbit_mq_callback Respond to RabbitMQ Message
|
|
110
|
-
|
|
111
|
-
When a request to resolve a DID comes into the DID finder, we
|
|
112
|
-
respond with this callback. This callback will remain active
|
|
113
|
-
until the request has been completed satisfied (so for some
|
|
114
|
-
DID finders, this could be a fairly long time.)
|
|
115
|
-
|
|
116
|
-
Args:
|
|
117
|
-
channel ([type]): RabbitMQ channel
|
|
118
|
-
method ([type]): Delivery method
|
|
119
|
-
properties ([type]): Properties of the message
|
|
120
|
-
body ([type]): The body (json for us) of the message
|
|
121
|
-
"""
|
|
122
|
-
dataset_id = None # set this in case we get an exception while loading request
|
|
123
|
-
try:
|
|
124
|
-
# Unpack the message. Really bad if we fail up here!
|
|
125
|
-
did_request = json.loads(body)
|
|
126
|
-
did = did_request["did"]
|
|
127
|
-
dataset_id = did_request["dataset_id"]
|
|
128
|
-
endpoint = did_request["endpoint"]
|
|
129
|
-
__logging.info(
|
|
130
|
-
f"Received DID request {did_request}",
|
|
131
|
-
extra={"dataset_id": dataset_id}
|
|
132
|
-
)
|
|
133
|
-
servicex = ServiceXAdapter(dataset_id=dataset_id,
|
|
134
|
-
endpoint=endpoint)
|
|
135
|
-
|
|
136
|
-
info = {
|
|
137
|
-
"dataset-id": dataset_id,
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
# Process the request and resolve the DID
|
|
141
|
-
try:
|
|
142
|
-
make_sync(run_file_fetch_loop)(did, servicex, info, user_callback)
|
|
143
|
-
|
|
144
|
-
except Exception as e:
|
|
145
|
-
_, exec_value, _ = sys.exc_info()
|
|
146
|
-
__logging.exception(f"DID Request Failed {str(e)}", extra={"dataset_id": dataset_id})
|
|
147
|
-
raise
|
|
148
|
-
|
|
149
|
-
except Exception as e:
|
|
150
|
-
__logging.exception(
|
|
151
|
-
f"DID request failed {str(e)}", extra={"dataset_id": dataset_id}
|
|
152
|
-
)
|
|
153
|
-
|
|
154
|
-
finally:
|
|
155
|
-
channel.basic_ack(delivery_tag=method.delivery_tag)
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
def init_rabbit_mq(
|
|
159
|
-
user_callback: UserDIDHandler,
|
|
160
|
-
rabbitmq_url: str,
|
|
161
|
-
queue_name: str,
|
|
162
|
-
retries: int,
|
|
163
|
-
retry_interval: float,
|
|
164
|
-
): # type: ignore
|
|
165
|
-
rabbitmq = None
|
|
166
|
-
retry_count = 0
|
|
167
|
-
|
|
168
|
-
while not rabbitmq:
|
|
169
|
-
try:
|
|
170
|
-
rabbitmq = pika.BlockingConnection(pika.URLParameters(rabbitmq_url))
|
|
171
|
-
_channel = rabbitmq.channel()
|
|
172
|
-
_channel.queue_declare(queue=queue_name)
|
|
173
|
-
|
|
174
|
-
__logging.info("Connected to RabbitMQ. Ready to start consuming requests")
|
|
175
|
-
|
|
176
|
-
_channel.basic_consume(
|
|
177
|
-
queue=queue_name,
|
|
178
|
-
auto_ack=False,
|
|
179
|
-
on_message_callback=lambda c, m, p, b: rabbit_mq_callback(
|
|
180
|
-
user_callback, c, m, p, b
|
|
181
|
-
),
|
|
182
|
-
)
|
|
183
|
-
_channel.start_consuming()
|
|
184
|
-
|
|
185
|
-
except pika.exceptions.AMQPConnectionError: # type: ignore
|
|
186
|
-
rabbitmq = None
|
|
187
|
-
retry_count += 1
|
|
188
|
-
if retry_count <= retries:
|
|
189
|
-
__logging.exception(
|
|
190
|
-
f"Failed to connect to RabbitMQ at {rabbitmq_url} "
|
|
191
|
-
f"(try #{retry_count}). Waiting {retry_interval} seconds "
|
|
192
|
-
"before trying again"
|
|
193
|
-
)
|
|
194
|
-
time.sleep(retry_interval)
|
|
195
|
-
else:
|
|
196
|
-
__logging.exception(
|
|
197
|
-
f"Failed to connect to RabbitMQ. Giving Up after {retry_count}"
|
|
198
|
-
" tries"
|
|
199
|
-
)
|
|
200
|
-
raise
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
def add_did_finder_cnd_arguments(parser: argparse.ArgumentParser):
|
|
204
|
-
"""add_did_finder_cnd_arguments Add required arguments to a parser
|
|
205
|
-
|
|
206
|
-
If you need to parse command line arguments for some special configuration, create your
|
|
207
|
-
own argument parser, and call this function to make sure the arguments needed
|
|
208
|
-
for running the back-end communication are filled in properly.
|
|
209
|
-
|
|
210
|
-
Then pass the results of the parsing to the `start_did_finder` method.
|
|
211
|
-
|
|
212
|
-
Args:
|
|
213
|
-
parser (argparse.ArgumentParser): The argument parser. Arguments needed for the
|
|
214
|
-
did finder/servicex communication will be added.
|
|
215
|
-
"""
|
|
216
|
-
parser.add_argument(
|
|
217
|
-
"--rabbit-uri", dest="rabbit_uri", action="store", required=True
|
|
218
|
-
)
|
|
219
|
-
parser.add_argument(
|
|
220
|
-
"--prefix",
|
|
221
|
-
dest="prefix",
|
|
222
|
-
action="store",
|
|
223
|
-
required=False,
|
|
224
|
-
default="",
|
|
225
|
-
help="Prefix to add to use a caching proxy for URIs",
|
|
226
|
-
)
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
def start_did_finder(
|
|
230
|
-
did_finder_name: str,
|
|
231
|
-
callback: UserDIDHandler,
|
|
232
|
-
parsed_args: Optional[argparse.Namespace] = None,
|
|
233
|
-
):
|
|
234
|
-
"""start_did_finder Start the DID finder
|
|
235
|
-
|
|
236
|
-
Top level method that starts the DID finder, hooking it up to rabbitmq queues, etc.,
|
|
237
|
-
and sets up the callback to be called each time ServiceX wants to render a DID into
|
|
238
|
-
files.
|
|
239
|
-
|
|
240
|
-
Once called this will not return unless it totally fails to connect to the rabbit
|
|
241
|
-
mq server (which must have been specified on the command line that started this).
|
|
242
|
-
If it can't return, then it will raise the appropriate exception.
|
|
243
|
-
|
|
244
|
-
Args:
|
|
245
|
-
did_name (str): Name of the DID finder (baked into the rabbit mq name)
|
|
246
|
-
callback (UserDIDHandler): Callback to handle the DID rendering requests
|
|
247
|
-
parser (Optional[argparse.Namespace], optional): If you need to parse your own
|
|
248
|
-
an arg parser, make sure to call
|
|
249
|
-
add_did_finder_cnd_arguments, run the
|
|
250
|
-
parser and pass in the resulting
|
|
251
|
-
parsed arguments.
|
|
252
|
-
Defaults to None (automatically
|
|
253
|
-
parses)
|
|
254
|
-
command line arguments, create
|
|
255
|
-
"""
|
|
256
|
-
# Setup command line parsing
|
|
257
|
-
if parsed_args is None:
|
|
258
|
-
parser = argparse.ArgumentParser()
|
|
259
|
-
add_did_finder_cnd_arguments(parser)
|
|
260
|
-
parsed_args = parser.parse_args()
|
|
261
|
-
|
|
262
|
-
# Initialize the root logger
|
|
263
|
-
initialize_root_logger(did_finder_name)
|
|
264
|
-
|
|
265
|
-
# Start up rabbit mq and also callbacks
|
|
266
|
-
init_rabbit_mq(
|
|
267
|
-
callback,
|
|
268
|
-
parsed_args.rabbit_uri,
|
|
269
|
-
f"{did_finder_name}{QUEUE_NAME_POSTFIX}",
|
|
270
|
-
retries=12,
|
|
271
|
-
retry_interval=10,
|
|
272
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|