20
20
# Given name, build the RabbitMQ queue name by appending this.
21
21
# This is backed into how ServiceX works - do not change unless it
22
22
# is also changed in the ServiceX_App
23
- QUEUE_NAME_POSTFIX = ' _did_requests'
23
+ QUEUE_NAME_POSTFIX = " _did_requests"
24
24
25
25
# Easy to use local logger
26
26
__logging = logging .getLogger (__name__ )
27
27
__logging .addHandler (logging .NullHandler ())
28
28
29
29
30
30
class _accumulator :
31
- ' Track or cache files depending on the mode we are operating in'
31
+ " Track or cache files depending on the mode we are operating in"
32
32
33
33
def __init__ (self , sx : ServiceXAdapter , sum : DIDSummary , hold_till_end : bool ):
34
34
self ._servicex = sx
@@ -37,7 +37,7 @@ def __init__(self, sx: ServiceXAdapter, sum: DIDSummary, hold_till_end: bool):
37
37
self ._file_cache : List [Dict [str , Any ]] = []
38
38
39
39
def add (self , file_info : Dict [str , Any ]):
40
- ' Track and inject the file back into the system'
40
+ " Track and inject the file back into the system"
41
41
if self ._hold_till_end :
42
42
self ._file_cache .append (file_info )
43
43
else :
@@ -47,23 +47,31 @@ def add(self, file_info: Dict[str, Any]):
47
47
self ._servicex .put_file_add (file_info )
48
48
49
49
def send_on (self , count ):
50
- ' Send the accumulated files'
50
+ " Send the accumulated files"
51
51
if self ._hold_till_end :
52
52
self ._hold_till_end = False
53
- files = sorted (self ._file_cache , key = lambda x : x ['paths' ])
54
- for file_info in files [0 :count ]:
55
- self .add (file_info )
53
+ files = sorted (self ._file_cache , key = lambda x : x ["paths" ])
54
+ self .send_bulk (files [:count ])
56
55
57
56
def send_bulk (self , file_list : List [Dict [str , Any ]]):
58
- 'does a bulk put of files'
59
- for ifl in file_list :
60
- self ._summary .add_file (ifl )
61
- self ._servicex .put_file_add_bulk (file_list )
62
- self ._servicex .post_transform_start ()
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
+ if self ._summary .file_count == 0 :
63
+ self ._servicex .post_transform_start ()
64
+ for ifl in file_list :
65
+ self ._summary .add_file (ifl )
66
+ self ._servicex .put_file_add_bulk (file_list )
63
67
64
68
65
- async def run_file_fetch_loop (did : str , servicex : ServiceXAdapter , info : Dict [str , Any ],
66
- user_callback : UserDIDHandler ):
69
+ async def run_file_fetch_loop (
70
+ did : str ,
71
+ servicex : ServiceXAdapter ,
72
+ info : Dict [str , Any ],
73
+ user_callback : UserDIDHandler ,
74
+ ):
67
75
start_time = datetime .now ()
68
76
69
77
summary = DIDSummary (did )
@@ -79,18 +87,19 @@ async def run_file_fetch_loop(did: str, servicex: ServiceXAdapter, info: Dict[st
79
87
acc .send_bulk (file_info )
80
88
81
89
except Exception :
82
- if did_info .get_mode == ' all' :
90
+ if did_info .get_mode == " all" :
83
91
raise
84
92
85
93
# If we've been holding onto any files, we need to send them now.
86
94
acc .send_on (did_info .file_count )
87
95
88
96
# Simple error checking and reporting
89
97
if summary .file_count == 0 :
90
- servicex .post_status_update (f'DID Finder found zero files for dataset { did } ' ,
91
- severity = 'fatal' )
98
+ servicex .post_status_update (
99
+ f"DID Finder found zero files for dataset { did } " , severity = "fatal"
100
+ )
92
101
93
- elapsed_time = int ((datetime .now ()- start_time ).total_seconds ())
102
+ elapsed_time = int ((datetime .now () - start_time ).total_seconds ())
94
103
servicex .put_fileset_complete (
95
104
{
96
105
"files" : summary .file_count ,
@@ -101,12 +110,13 @@ async def run_file_fetch_loop(did: str, servicex: ServiceXAdapter, info: Dict[st
101
110
}
102
111
)
103
112
104
- servicex .post_status_update (f' Completed load of files in { elapsed_time } seconds' )
113
+ servicex .post_status_update (f" Completed load of files in { elapsed_time } seconds" )
105
114
106
115
107
- def rabbit_mq_callback (user_callback : UserDIDHandler , channel , method , properties , body ,
108
- file_prefix = None ):
109
- '''rabbit_mq_callback Respond to RabbitMQ Message
116
+ def rabbit_mq_callback (
117
+ user_callback : UserDIDHandler , channel , method , properties , body , file_prefix = None
118
+ ):
119
+ """rabbit_mq_callback Respond to RabbitMQ Message
110
120
111
121
When a request to resolve a DID comes into the DID finder, we
112
122
respond with this callback. This callback will remain active
@@ -119,19 +129,21 @@ def rabbit_mq_callback(user_callback: UserDIDHandler, channel, method, propertie
119
129
properties ([type]): Properties of the message
120
130
body ([type]): The body (json for us) of the message
121
131
file_prefix([str]): Prefix to put in front of file paths to enable use of Cache service
122
- '''
132
+ """
123
133
request_id = None # set this in case we get an exception while loading request
124
134
try :
125
135
# Unpack the message. Really bad if we fail up here!
126
136
did_request = json .loads (body )
127
- did = did_request ['did' ]
128
- request_id = did_request ['request_id' ]
129
- __logging .info (f'Received DID request { did_request } ' , extra = {'requestId' : request_id })
130
- servicex = ServiceXAdapter (did_request ['service-endpoint' ], file_prefix )
137
+ did = did_request ["did" ]
138
+ request_id = did_request ["request_id" ]
139
+ __logging .info (
140
+ f"Received DID request { did_request } " , extra = {"requestId" : request_id }
141
+ )
142
+ servicex = ServiceXAdapter (did_request ["service-endpoint" ], file_prefix )
131
143
servicex .post_status_update ("DID Request received" )
132
144
133
145
info = {
134
- ' request-id' : request_id ,
146
+ " request-id" : request_id ,
135
147
}
136
148
137
149
# Process the request and resolve the DID
@@ -140,23 +152,30 @@ def rabbit_mq_callback(user_callback: UserDIDHandler, channel, method, propertie
140
152
141
153
except Exception as e :
142
154
_ , exec_value , _ = sys .exc_info ()
143
- __logging .exception ('DID Request Failed' , extra = {'requestId' : request_id })
144
- servicex .post_status_update (f'DID Request Failed for id { request_id } : '
145
- f'{ str (e )} - { exec_value } ' ,
146
- severity = 'fatal' )
155
+ __logging .exception ("DID Request Failed" , extra = {"requestId" : request_id })
156
+ servicex .post_status_update (
157
+ f"DID Request Failed for id { request_id } : " f"{ str (e )} - { exec_value } " ,
158
+ severity = "fatal" ,
159
+ )
147
160
raise
148
161
149
162
except Exception as e :
150
- __logging .exception (f'DID request failed { str (e )} ' , extra = {'requestId' : request_id })
163
+ __logging .exception (
164
+ f"DID request failed { str (e )} " , extra = {"requestId" : request_id }
165
+ )
151
166
152
167
finally :
153
168
channel .basic_ack (delivery_tag = method .delivery_tag )
154
169
155
170
156
- def init_rabbit_mq (user_callback : UserDIDHandler ,
157
- rabbitmq_url : str , queue_name : str , retries : int ,
158
- retry_interval : float ,
159
- file_prefix : str = None ): # type: ignore
171
+ def init_rabbit_mq (
172
+ user_callback : UserDIDHandler ,
173
+ rabbitmq_url : str ,
174
+ queue_name : str ,
175
+ retries : int ,
176
+ retry_interval : float ,
177
+ file_prefix : str = None ,
178
+ ): # type: ignore
160
179
rabbitmq = None
161
180
retry_count = 0
162
181
@@ -168,28 +187,35 @@ def init_rabbit_mq(user_callback: UserDIDHandler,
168
187
169
188
__logging .info ("Connected to RabbitMQ. Ready to start consuming requests" )
170
189
171
- _channel .basic_consume (queue = queue_name ,
172
- auto_ack = False ,
173
- on_message_callback = lambda c , m , p , b :
174
- rabbit_mq_callback (user_callback , c , m , p , b , file_prefix ))
190
+ _channel .basic_consume (
191
+ queue = queue_name ,
192
+ auto_ack = False ,
193
+ on_message_callback = lambda c , m , p , b : rabbit_mq_callback (
194
+ user_callback , c , m , p , b , file_prefix
195
+ ),
196
+ )
175
197
_channel .start_consuming ()
176
198
177
199
except pika .exceptions .AMQPConnectionError : # type: ignore
178
200
rabbitmq = None
179
201
retry_count += 1
180
202
if retry_count <= retries :
181
- __logging .exception (f'Failed to connect to RabbitMQ at { rabbitmq_url } '
182
- f'(try #{ retry_count } ). Waiting { retry_interval } seconds '
183
- 'before trying again' )
203
+ __logging .exception (
204
+ f"Failed to connect to RabbitMQ at { rabbitmq_url } "
205
+ f"(try #{ retry_count } ). Waiting { retry_interval } seconds "
206
+ "before trying again"
207
+ )
184
208
time .sleep (retry_interval )
185
209
else :
186
- __logging .exception (f'Failed to connect to RabbitMQ. Giving Up after { retry_count } '
187
- ' tries' )
210
+ __logging .exception (
211
+ f"Failed to connect to RabbitMQ. Giving Up after { retry_count } "
212
+ " tries"
213
+ )
188
214
raise
189
215
190
216
191
217
def add_did_finder_cnd_arguments (parser : argparse .ArgumentParser ):
192
- ''' add_did_finder_cnd_arguments Add required arguments to a parser
218
+ """ add_did_finder_cnd_arguments Add required arguments to a parser
193
219
194
220
If you need to parse command line arguments for some special configuration, create your
195
221
own argument parser, and call this function to make sure the arguments needed
@@ -200,17 +226,26 @@ def add_did_finder_cnd_arguments(parser: argparse.ArgumentParser):
200
226
Args:
201
227
parser (argparse.ArgumentParser): The argument parser. Arguments needed for the
202
228
did finder/servicex communication will be added.
203
- '''
204
- parser .add_argument ('--rabbit-uri' , dest = "rabbit_uri" , action = 'store' , required = True )
205
- parser .add_argument ('--prefix' , dest = "prefix" , action = 'store' , required = False ,
206
- default = "" ,
207
- help = 'Prefix to add to use a caching proxy for URIs' )
229
+ """
230
+ parser .add_argument (
231
+ "--rabbit-uri" , dest = "rabbit_uri" , action = "store" , required = True
232
+ )
233
+ parser .add_argument (
234
+ "--prefix" ,
235
+ dest = "prefix" ,
236
+ action = "store" ,
237
+ required = False ,
238
+ default = "" ,
239
+ help = "Prefix to add to use a caching proxy for URIs" ,
240
+ )
208
241
209
242
210
- def start_did_finder (did_finder_name : str ,
211
- callback : UserDIDHandler ,
212
- parsed_args : Optional [argparse .Namespace ] = None ):
213
- '''start_did_finder Start the DID finder
243
+ def start_did_finder (
244
+ did_finder_name : str ,
245
+ callback : UserDIDHandler ,
246
+ parsed_args : Optional [argparse .Namespace ] = None ,
247
+ ):
248
+ """start_did_finder Start the DID finder
214
249
215
250
Top level method that starts the DID finder, hooking it up to rabbitmq queues, etc.,
216
251
and sets up the callback to be called each time ServiceX wants to render a DID into
@@ -231,7 +266,7 @@ def start_did_finder(did_finder_name: str,
231
266
Defaults to None (automatically
232
267
parses)
233
268
command line arguments, create
234
- '''
269
+ """
235
270
# Setup command line parsing
236
271
if parsed_args is None :
237
272
parser = argparse .ArgumentParser ()
@@ -242,8 +277,10 @@ def start_did_finder(did_finder_name: str,
242
277
initialize_root_logger (did_finder_name )
243
278
244
279
# Start up rabbit mq and also callbacks
245
- init_rabbit_mq (callback ,
246
- parsed_args .rabbit_uri ,
247
- f'{ did_finder_name } { QUEUE_NAME_POSTFIX } ' ,
248
- retries = 12 ,
249
- retry_interval = 10 )
280
+ init_rabbit_mq (
281
+ callback ,
282
+ parsed_args .rabbit_uri ,
283
+ f"{ did_finder_name } { QUEUE_NAME_POSTFIX } " ,
284
+ retries = 12 ,
285
+ retry_interval = 10 ,
286
+ )
0 commit comments