1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
|
#!/usr/bin/env python3
"""Usage: dqm-ls [-s SERVER] [-n CONNECTIONS]
Parse ROOT file contents listings on a DQM GUI server.
In order to authenticate to the target server, standard grid certificate
environment must be available. Typically this would be X509_CERT_DIR and
either X509_USER_PROXY or X509_USER_CERT and X509_USER_KEY environment
variables. If these variables are not set, the following defaults are
checked for existence. Note that if the script falls back on using a
key rather than a proxy, it will prompt for the key password.
- $X509_CERT_DIR: /etc/grid-security/certificates
- $X509_USER_KEY: $HOME/.globus/userkey.pem
- $X509_USER_CERT: $HOME/.globus/usercert.pem
"""
from DQMServices.Components.HTTP import RequestManager
from DQMServices.Components.X509 import SSLOptions
import os, sys, re, pycurl, urllib
from optparse import OptionParser
from time import time, strptime, strftime, gmtime
from calendar import timegm
from datetime import datetime
from urllib.parse import urlparse, quote
from tempfile import mkstemp
from traceback import print_exc
from functools import cmp_to_key
# Object types.
DIR = 0
FILE = 1
# HTTP protocol `User-agent` identification string.
ident = "DQMLS/1.0 python/%s.%s.%s" % sys.version_info[:3]
# SSL/X509 options.
ssl_opts = None
# HTTP request manager for content requests.
reqman = None
# Number of HTTP requests made for content.
nfetched = 0
# Found objects.
found = []
def logme(msg, *args):
"""Generate agent log message."""
procid = "[%s/%d]" % (__file__.rsplit("/", 1)[-1], os.getpid())
print(datetime.now(), procid, msg % args)
def myumask():
"""Get the current process umask."""
val = os.umask(0)
os.umask(val)
return val
def handle_init(c):
"""Prepare custom properties on download handles."""
c.temp_file = None
c.temp_path = None
c.local_path = None
def request_init(c, options, path, kind):
"""`RequestManager` callback to initialise directory contents request."""
c.setopt(pycurl.URL, options.server + quote(path) + ((path != "/" and "/") or ""))
assert c.temp_file == None
assert c.temp_path == None
assert c.local_path == None
# If this is file, prepare temporary destination file in the target
# directory for possible download. parse_dir_and_files() will finish this off.
if kind == FILE and options.download:
try:
(fd, tmp) = mkstemp()
fp = os.fdopen(fd, 'wb')
c.setopt(pycurl.WRITEFUNCTION, fp.write)
c.temp_file = fp
c.temp_path = tmp
c.local_path = path.strip('/')
c.buffer = None
except Exception as e:
logme("ERROR: %s: %s", path, str(e))
print_exc()
def cleanup(c):
"""Clean up file copy operation, usually after any failures."""
if c.temp_file:
try: c.temp_file.close()
except: pass
if c.temp_path:
try: os.remove(c.temp_path)
except: pass
if c.local_path:
try: os.remove(c.local_path)
except: pass
c.temp_file = None
c.temp_path = None
c.local_path = None
c.buffer = None
def report_error(c, task, errmsg, errno):
"""`RequestManager` callback to report directory contents request errors."""
print("FAILED to retrieve %s: %s (%d)" % (task, errmsg, errno), file=sys.stderr)
global nfetched; nfetched += 1
def parse_dir_and_files(c):
"""`RequestManager` callback to handle directory content response.
This gets called once per every directory which has been successfully
retrieved from the server. It parses the HTML response and turns it
into object listing with all the file meta information.
If verbosity has been requested, also shows simple progress bar on the
search progress, one dot for every ten directories retrieved."""
options, path, kind = c.task
root_url = urlparse(options.server).path.rstrip('/')
if kind == FILE and options.download:
assert c.local_path, "Expected local path property to be set"
assert c.temp_file, "Exepected temporary file property to be set"
try:
c.setopt(pycurl.WRITEFUNCTION, lambda *args: None)
c.temp_file.close()
c.temp_file = None
os.chmod(c.temp_path, 0o0666 & ~UMASK)
os.system('mv %s %s' % (c.temp_path, c.local_path))
c.local_path = None
logme("INFO: downloaded %s", path)
except Exception as e:
logme("ERROR: downloading %s into %s failed: %s",
path, c.local_path, str(e))
print_exc()
finally:
cleanup(c)
elif kind == DIR:
items = re.findall(r"<tr><td><a href='(.*?)'>(.*?)</a></td><td>(\d+| |-)</td>"
r"<td>( |\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d UTC)</td>",
c.buffer.getvalue().decode('utf-8'))
for path, name, size, date in items:
assert path.startswith(root_url)
path = path[len(root_url):]
if date == " ":
date = -1
else:
date = timegm(strptime(date, "%Y-%m-%d %H:%M:%S %Z"))
if size == " " or size == "-":
size = -1
else:
size = int(size)
if path.endswith("/"):
assert size == -1
path = path[:-1]
obj = {'task': c.task,
'kind': DIR,
'name': name,
'size': size,
'date': date,
'path': path}
found.append(obj)
if options.recursive:
reqman.put((options, path, DIR))
else:
assert size >= 0
obj = {'task': c.task,
'kind': FILE,
'name': name,
'size': size,
'date': date,
'path': path}
if options.match_file:
if name == options.match_file:
found.append(obj)
if options.download:
reqman.put((options, path, FILE))
else:
found.append(obj)
if options.download:
reqman.put((options, path, FILE))
global nfetched
nfetched += 1
if options.verbose and nfetched % 10 == 0:
sys.stdout.write(".")
sys.stdout.flush()
if nfetched % 750 == 0:
print()
def objcmp(a, b):
diff = 0
diff = a['date'] - b['date']
if diff:
return diff
diff = a['size'] - b['size']
if diff:
return diff
return diff
# Parse command line options.
op = OptionParser(usage = __doc__)
op.add_option("-s", "--server", dest = "server",
type = "string", action = "store", metavar = "SERVER",
default = "https://cmsweb.cern.ch/dqm/offline/data/browse",
help = "Pull content from SERVER")
op.add_option("-n", "--connections", dest = "connections",
type = "int", action = "store", metavar = "NUM",
default = 10, help = "Use NUM concurrent connections")
op.add_option("-v", "--verbose", dest = "verbose",
action = "store_true", default = False,
help = "Show verbose scan information")
op.add_option("-r", "--recursive", dest = "recursive",
action = "store_true", default = False,
help = "Perform a recursive scan starting from the root directory.")
op.add_option("-d", "--download", dest = "download",
action = "store_true", default = False,
help = "Download all touched ROOT files locally. To be used with extreme care.")
op.add_option("-m", "--match_file", dest = "match_file",
type= "string", action = "store", default = "",
help = "Filter results based on exact file name matching.")
options, args = op.parse_args()
if args:
print("Too many arguments", file=sys.stderr)
sys.exit(1)
if not options.server:
print("Server contact string required", sys.stderr)
sys.exit(1)
UMASK = myumask()
# In case a user specifies a root file as address, remove it from the
# address and return results that match only that name.
gr = re.match("(.*)/(DQM_V.*\.root)$", options.server)
if gr:
options.server = gr.group(1)
options.match_file = gr.group(2)
# Get SSL X509 parametres.
ssl_opts = SSLOptions()
if options.verbose:
print("Using SSL cert dir", ssl_opts.ca_path)
print("Using SSL private key", ssl_opts.key_file)
print("Using SSL public key", ssl_opts.cert_file)
# Start a request manager for contents.
reqman = RequestManager(num_connections = options.connections,
ssl_opts = ssl_opts,
user_agent = ident,
request_init = request_init,
request_respond = parse_dir_and_files,
request_error = report_error,
handle_init = handle_init)
# Process from root directory.
start = time()
reqman.put((options, "/", DIR))
reqman.process()
end = time()
for x in sorted(found, key=cmp_to_key(objcmp)):
print("%20s\t%s\t%s" % (x['size'],
strftime("%Y-%m-%d %H:%M:%S %Z", gmtime(x['date'])),
((options.recursive and x['path']) or x['name'])))
if options.verbose:
print("\nFound %d directories, %d objects in %.3f seconds" % (nfetched, len(found), end - start))
|