-
Notifications
You must be signed in to change notification settings - Fork 5
/
GUI.py
1738 lines (1528 loc) · 66.9 KB
/
GUI.py
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from stat import *
from copy import deepcopy
from html import escape
from threading import Lock
from Monitoring.DQM import Accelerator
from Monitoring.Core.Utils.Common import _logerr, _logwarn, _loginfo, ParameterManager
from cherrypy import (
expose,
HTTPError,
HTTPRedirect,
tree,
request,
response,
engine,
url,
tools,
)
from cherrypy.lib.static import serve_file
from cherrypy.lib import cptools, httputil
import os, re, time, socket, shutil, tempfile, cgi, json, hmac, hashlib
DEF_DQM_PORT = 9090
# Validate DQM file paths.
RX_SAFE_PATH = re.compile(r"^[A-Za-z0-9][-A-Za-z0-9_]*(?:\.(?:root|zip|ig))?$")
tools.params = ParameterManager()
# --------------------------------------------------------------------
# DQM uploads utility class to properly set headers, status and to
# check arguments meant to be used by upload methods.
class DQMUpload:
STATUS_OK = 100 # Requested operation succeeded
STATUS_BAD_REQUEST = 200 # The request is malformed
STATUS_ERROR_PARAMETER = 300 # Request parameter value is unacceptable.
STATUS_ERROR_EXISTS = 301 # Cannot overwrite an existing object.
STATUS_ERROR_NOT_EXISTS = 302 # Requested file does not exist.
STATUS_FAIL_EXECUTE = 400 # Failed to execute the request.
STATUS_ERROR_NOT_AUTHORIZED = (
401 # Unauthorized, user is not allowed to submit requests
)
def __init__(self):
pass
def refresh(self, *args):
pass
# Set response headers to indicate our status data.
def _status(self, code, message, detail=None):
response.headers["dqm-status-code"] = str(code)
response.headers["dqm-status-message"] = message
response.headers["dqm-status-detail"] = detail
# Set response headers to indicate an error, then get out.
def _error(self, code, message, detail=None):
_logerr("code=%d, message=%s, detail=%s" % (code, message, detail))
self._status(code, message, detail)
raise HTTPError(500, message)
# Check that a required parameter has been given just once,
# and the value matches the given regular expression.
def _check(self, name, arg, rx):
if name == "filename":
arg = str(arg)
if not arg or not isinstance(arg, str):
self._error(
self.STATUS_ERROR_EXISTS,
"Parameter %s of value %s" % (name, arg),
" is of type %s" % str(type(arg)),
)
self._error(
self.STATUS_BAD_REQUEST,
"Incorrect or missing %s parameter" % name,
"Must provide single argument",
)
if not re.match(rx, arg):
self._error(
self.STATUS_BAD_REQUEST,
"Malformed %s argument" % name,
"Argument must match regular expression '%s'" % rx,
)
# Check the current request is into a directory, and if not,
# redirect to add a trailing slash.
def _prepdir(self, time):
pi = request.path_info
if not pi.endswith("/"):
raise HTTPRedirect(url(pi + "/", request.query_string))
request.is_index = True
response.headers["Content-Type"] = "text/html"
response.headers["Last-Modified"] = httputil.HTTPDate(time)
cptools.validate_since()
def _check_authentication(self):
"""Read and verify the front-end headers. Return the result of
the verification."""
headers = request.headers
prefix = suffix = ""
hkeys = headers.keys()
for hk in sorted(hkeys):
hk = hk.lower()
if hk[0:9] in ["cms-authn", "cms-authz"] and hk != "cms-authn-hmac":
prefix += "h%xv%x" % (len(hk), len(headers[hk]))
suffix += "%s%s" % (hk, headers[hk])
vfy = hmac.new(
self.key, f"{prefix}#{suffix}".encode(), hashlib.sha1
).hexdigest()
return vfy == headers["cms-authn-hmac"]
def _log_authentication_failure_and_exit(self):
"""Log all authentication failures to be able to investigate any
troubles more easily."""
_logerr("Authentication Failure, details follow.")
headers = request.headers
hkeys = headers.keys()
for hk in sorted(hkeys):
hk = hk.lower()
_logerr("%s --> %s" % (hk, headers[hk]))
raise HTTPError(self.STATUS_ERROR_NOT_AUTHORIZED, "Unauthorized upload.")
# --------------------------------------------------------------------
# DQM extension to manage DQM file uploads.
class DQMFileAccess(DQMUpload):
def __init__(self, server, aclfile, uploads, roots):
self.lock = Lock()
self.server = server
self.uploads = uploads
self.roots = roots
self.key = b""
if uploads and not os.path.exists(uploads):
os.makedirs(uploads)
if aclfile and os.path.exists(aclfile):
try:
with open(aclfile, "rb") as f:
self.key = f.read()
except:
_logerr("Keyfile %s could not be read." % aclfile)
tree.mount(
self,
script_name=server.baseUrl + "/data",
config={"/": {"request.show_tracebacks": False}},
)
# ------------------------------------------------------------------
# Store a file to the server. Validates all the parameters, then
# attempts to save the file safely. Sets headers in the response
# to indicate what happened, either an error or success.
# FIXME: Verify the request was submitted securely and is permitted.
# FIXME: Determine producer from certificate information.
@expose
@tools.params()
def put(self, size=None, checksum=None, file=None, *args, **kwargs):
headers = request.headers
# Bail out if upload is not supported.
if not self.uploads:
raise HTTPError(404, "Not found")
# Authenticate user in case the authentication happend via a Limited Proxy.
if "cms-auth-status" in headers:
if not self._check_authentication():
self._log_authentication_failure_and_exit()
if headers["Cms-Authn-Method"] == "X509LimitedProxy":
if (
"Cms-Authz-t0-operator" not in headers
and "Cms-Authz-production-operator" not in headers
):
self._log_authentication_failure_and_exit()
if "Cms-Authz-t0-operator" in headers:
if "group:dataops" not in headers["Cms-Authz-t0-operator"].split(
" "
):
self._log_authentication_failure_and_exit()
if "Cms-Authz-production-operator" in headers:
if "group:dataops" not in headers[
"Cms-Authz-production-operator"
].split(" "):
self._log_authentication_failure_and_exit()
# Argument validation.
if (
file == None
or not getattr(file, "file", None)
or not getattr(file, "filename", None)
):
self._error(
self.STATUS_BAD_REQUEST,
"Incorrect or missing file argument",
"Must provide a single file-type argument",
)
self._check("size", size, r"^\d+$")
self._check("checksum", checksum, r"^(md5:[A-Za-z0-9]+|crc32:\d+)$")
self._check("filename", file.filename, r"^[-A-Za-z0-9_]+\.root$")
m = re.match(
r"^(DQM)_V\d+(_[A-Za-z0-9]+)?_R(\d+)(__.*)?\.root", str(file.filename)
)
if not m:
self._error(
self.STATUS_ERROR_PARAMETER,
"File name does not match the expected convention",
)
size = int(size)
runnr = int(m.group(3))
if m.group(2) and m.group(4):
self._error(
self.STATUS_ERROR_PARAMETER,
"File cannot have both online system and dataset names",
)
elif m.group(4):
self._check(
"workflow", m.group(4).replace("__", "/"), r"^(/[-A-Za-z0-9_]+){3}$"
)
# Determine where we would save this file. Update file version
# until we find a version that doesn't yet exist. This permits
# multiple concurrent upload versions of the same file. We need
# to lock around this so multiple concurrent uploads can't yield
# the same version number for two separate uploads.
try:
self.lock.acquire()
version = 1
while True:
dir = "%s/%04d" % (self.uploads, version)
fname = "%s/%s" % (dir, file.filename)
if not os.path.exists(fname) and not os.path.exists(fname + ".origin"):
break
version += 1
tmp = None
if fname.find("..") >= 0 or fname.find("./") >= 0 or fname.find("/.") >= 0:
self._error(
self.STATUS_ERROR_PARAMETER,
"Invalid file path name",
"Path name cannot refer to '.' or '..'",
)
# Try saving the file safely. First we write the file to a
# temporary directory, with a fake name, to the same directory as
# the final file would be. We then move it in place atomically
# and write a metadata descriptor file. If anything goes wrong,
# clean up so the upload can be re-attempted later.
if not os.path.exists(dir):
os.makedirs(dir)
(fd, tmp) = tempfile.mkstemp(".upload", "", dir)
nsaved = 0
first = b""
while True:
data = file.file.read(8 * 1024 * 1024)
if len(data) < 1:
break
if len(first) < 5:
first += data[0:5]
os.write(fd, data)
nsaved += len(data)
os.close(fd)
os.chmod(tmp, 0o644)
if first[0:5] != b"root\x00":
self._error(
self.STATUS_ERROR_PARAMETER,
"Not a ROOT file",
"File data contents do not represent a ROOT file",
)
if nsaved != size:
self._error(
self.STATUS_FAIL_EXECUTE,
"Failed to save file data",
"Wrote %d bytes, expected to write %d" % (nsaved, size),
)
shutil.move(tmp, fname)
with open(fname + ".origin", "w") as _f:
_f.write("%s %d %s\n" % (checksum, size, fname))
self.lock.release()
except Exception as e:
self.lock.release()
if os.path.exists(fname):
os.remove(fname)
if os.path.exists(fname + ".origin"):
os.remove(fname + ".origin")
if tmp and os.path.exists(tmp):
os.remove(tmp)
if isinstance(e, HTTPError):
raise e
self._error(
self.STATUS_FAIL_EXECUTE,
"Failed to save file data",
str(e).replace("\n", "; "),
)
# Indicate success.
self._status(self.STATUS_OK, "File saved", "Wrote %d bytes" % nsaved)
_loginfo("saved file %s size %d checksum %s" % (fname, size, checksum))
message = (
"Thanks.\n"
"The server received your file. However this does not mean "
"that the file was indexed successfully.\n"
"A different server process will now check the filename to "
"determine in which folder to archive it.\n"
"After that, another process will attempt to index it. This "
"might take some minutes.\n"
"In case of doubt, please check the server logs of the receive-"
"daemon and import-daemon."
)
return message
# ------------------------------------------------------------------
# Retrieve files from the server. Pretends to be somewhat like the
# apache mod_dir file browsing scheme. Serves only files with valid
# and safe path references. FIXME: Bandwidth limiting and ACLs?
@expose
@tools.params()
def browse(self, *path, **kwargs):
rooturl = self.server.baseUrl + "/data/browse"
if not self.roots or len(self.roots) == 0:
raise HTTPError(404, "Not found")
for x in path:
if not re.match(RX_SAFE_PATH, x):
raise HTTPError(404, "Not found")
# If no path was given, provide list of top level roots.
if len(path) == 0:
self._prepdir(self.server.stamp)
return (
"<html><head><title>Index of %(index)s</title></head><body>"
"<h1>%(index)s</h1><table border='0' valign='top' cellpadding='3'>"
"%(files)s</table></body></html>"
% {
"index": escape("DQM files"),
"files": "\n".join(
[
"<tr><td><a href='%(root)s/%(name)s/'>%(name)s"
"</a></td><td> </td><td> </td>"
% {"root": rooturl, "name": escape(x)}
for x in sorted(self.roots.keys())
]
),
}
)
# We have a path, check under the given root
root = path[0]
if root not in self.roots:
raise HTTPError(404, "Not found")
pathname = "/".join([self.roots[root]] + list(path[1:]))
if not os.path.exists(pathname):
raise HTTPError(404, "Not found")
if os.path.isdir(pathname):
try:
st = os.stat(pathname)
if not S_ISDIR(st.st_mode):
raise HTTPError(404, "Not found")
except OSError:
raise HTTPError(404, "Not found")
self._prepdir(st.st_mtime)
files = [
(x, pathname + "/" + x)
for x in os.listdir(pathname)
if re.match(RX_SAFE_PATH, x)
]
files = [
(x[0], x[1], os.path.isdir(x[1]), os.stat(x[1]))
for x in files
if not os.path.islink(x[1])
]
return (
"<html><head><title>Index of %(index)s</title></head><body>"
"<h1>%(index)s</h1><p style='padding-left:5px'>"
"<a href='%(root)s/%(parent)s'>Up</a></p>"
"<table border='0' valign='top' cellpadding='3'>"
"%(files)s</table></body></html>"
% {
"index": escape("/".join(path)),
"parent": escape("/".join(path[:-1])),
"root": rooturl,
"files": "\n".join(
[
"<tr><td><a href='%(root)s/%(path)s/%(name)s%(slash)s'>"
"%(name)s%(slash)s</a></td><td>%(size)s</td>"
"<td>%(mtime)s UTC</td></tr>"
% {
"root": rooturl,
"path": escape("/".join(path)),
"name": escape(x[0]),
"slash": (x[2] and "/") or "",
"size": (x[2] and "-") or x[3].st_size,
"mtime": time.strftime(
"%Y-%m-%d %H:%M:%S", time.gmtime(x[3].st_mtime)
),
}
for x in sorted(files)[::-1]
]
),
}
)
else:
return serve_file(pathname, content_type="application/octet-stream")
# --------------------------------------------------------------------
# DQM extension to manage DQM layout uploads.
class DQMLayoutAccess(DQMUpload):
LAYOUTSFILE = "layouts.json"
def __init__(self, server, aclfile, uploads, allowedUsers):
self.lock = Lock()
self.server = server
self.uploads = uploads
self.allowedUsers = allowedUsers
self.key = ""
if uploads and not os.path.exists(uploads):
os.makedirs(uploads)
tree.mount(
self,
script_name=server.baseUrl + "/layout",
config={"/": {"request.show_tracebacks": False}},
)
# ------------------------------------------------------------------
# Store a file to the server. Validates all the parameters, then
# attempts to save the file safely. Sets headers in the response
# to indicate what happened, either an error or success.
@expose
@tools.params()
def put(self, file=None, *args, **kwargs):
# Bail out if upload is not supported.
if not self.uploads:
raise HTTPError(404, "Not found")
# Authenticate user against the list of authorized users specified
# in the server configuration.
if request.headers.get("CMS-Auth-Cert", "-") not in self.allowedUsers:
raise HTTPError(
self.STATUS_ERROR_NOT_AUTHORIZED,
"You are not allowed to upload layouts.",
)
# Argument validation.
if (
file == None
or not getattr(file, "file", None)
or not getattr(file, "filename", None)
):
self._error(
self.STATUS_BAD_REQUEST,
"Incorrect or missing file argument",
"Must provide a single file-type argument",
)
try:
self.lock.acquire()
dir = "%s" % (self.uploads)
fname = "%s/%s" % (dir, self.LAYOUTSFILE)
# Try saving the file safely. If anything goes wrong,
# clean up so the upload can be re-attempted later.
if not os.path.exists(dir):
os.makedirs(dir)
with open(fname, "w") as f:
nsaved = 0
first = ""
while True:
data = file.file.read(8 * 1024 * 1024)
if not data:
break
if len(first) < 5:
first += data[0:5]
f.write(data)
nsaved += len(data)
f.close()
# Reads in the uploaded JSON file that describes the layout,
# decodes it as python dictionary.
layouts = json.loads((open(fname, "r").read()))
self.lock.release()
except Exception as e:
self.lock.release()
if os.path.exists(fname):
os.remove(fname)
if isinstance(e, HTTPError):
raise e
self._error(
self.STATUS_FAIL_EXECUTE,
"Failed to save file data",
str(e).replace("\n", "; "),
)
# Indicate success.
self._status(self.STATUS_OK, "Layouts saved", "Wrote %d bytes" % nsaved)
_loginfo("saved layouts %s size %d" % (fname, nsaved))
# Now inject the layout into the server via the registered
# visDQMLayoutSource, if any.
for ext in self.server.sources:
if isinstance(ext, DQMLayoutSource):
ext._pushLayouts(layouts)
return "Thanks.\n"
# --------------------------------------------------------------------
# DQM extension to manage DQM file uploads.
class DQMToJSON(Accelerator.DQMToJSON):
def refresh(self, *args):
pass
def __init__(self, server):
Accelerator.DQMToJSON.__init__(self)
self.server = server
tree.mount(
self,
script_name=server.baseUrl + "/data/json",
config={"/": {"request.show_tracebacks": False}},
)
@expose
@tools.params()
@tools.gzip()
def samples(self, *args, **options):
sources = dict(
(s.plothook, s) for s in self.server.sources if getattr(s, "plothook", None)
)
(stamp, result) = self._samples(list(sources.values()), options)
response.headers["Content-Type"] = "text/plain"
response.headers["Last-Modified"] = httputil.HTTPDate(stamp)
return result
@expose
@tools.params()
def default(self, srcname, runnr, dsP, dsW, dsT, *path, **options):
sources = dict(
(s.plothook, s) for s in self.server.sources if getattr(s, "plothook", None)
)
layoutSrc = None
for s in self.server.sources:
if isinstance(s, DQMLayoutSource):
layoutSrc = s
if srcname in sources:
(stamp, result) = self._list(
layoutSrc,
sources[srcname],
int(runnr),
"/".join(("", dsP, dsW, dsT)),
"/".join(path),
options,
)
response.headers["Content-Type"] = "text/plain"
response.headers["Last-Modified"] = httputil.HTTPDate(stamp)
return result
else:
response.headers["Content-Type"] = "text/plain"
response.headers["Last-Modified"] = httputil.HTTPDate(self.server.stamp)
return "{}"
# --------------------------------------------------------------------
# Management interface for talking to the ROOT rendering process.
class DQMRenderLink(Accelerator.DQMRenderLink):
def __init__(self, server, plugin, nproc=8, debug=False):
Accelerator.DQMRenderLink.__init__(
self,
server.sessiondir.rsplit("/", 1)[0],
server.logdir,
plugin,
nproc,
debug,
)
engine.subscribe("start", lambda *args: self._start(), priority=1)
engine.subscribe("stop", lambda *args: self._stop(), priority=1)
# --------------------------------------------------------------------
# Source for plotting non-existent DQM objects. Feeds the names of
# missing objects the visDQMRender for "missing in action" image.
class DQMUnknownSource(Accelerator.DQMUnknownSource):
def __init__(self, server, statedir):
Accelerator.DQMUnknownSource.__init__(self)
# Generate a "missing in action" image for an unknown object.
def plot(self, *path, **options):
a = self._plot("/".join(path[4:]), options)
return (a[0], bytes(a[1]))
# --------------------------------------------------------------------
# Source for plotting overlaid DQM objects. Requests the object from
# all other sources and sends them over for rendering.
class DQMOverlaySource(Accelerator.DQMOverlaySource):
def __init__(self, server, statedir):
Accelerator.DQMOverlaySource.__init__(self)
self.server = server
# Generate an overlaid image. Finds all the servers sources
# and generates final list of (source, runnr, dataset, path, label)
# tuples to pass to C++ layer to process.
def plot(self, *junk, **options):
sources = dict(
(s.plothook, s) for s in self.server.sources if getattr(s, "plothook", None)
)
objs = options.get("obj", [])
labels = options.get("reflabel", [])
if isinstance(objs, str):
objs = [objs]
if isinstance(labels, str):
labels = [labels]
# Prepend a fake label for the first object which is not a reference, but
# the real one. Standard reference objects are never passed via the URL,
# but are extracted directly from the underlying database. If the user
# selected "Standard", therefore, no obj parameter will be added to the URL
# and the symmetry will be kept between obj and reflabel (modulo the insert
# below).
# Old URL pointing directly to plots via plotfairy will stop working, since
# they are missing the reflabel parameters. For this reason, in order to
# keep them functional, we artificially keep on adding reflabels until
# needed.
final = []
for i, o in enumerate(objs):
(srcname, runnr, dsP, dsW, dsT, path) = o.split("/", 5)
if srcname in sources and srcname != "unknown":
if i == 0:
labels.insert(0, "Ignore")
elif i >= len(labels):
labels.append(runnr)
final.append(
(
sources[srcname],
int(runnr),
"/%s/%s/%s" % (dsP, dsW, dsT),
path,
labels[i],
)
)
assert len(labels) == len(objs)
a = self._plot(final, options)
return (a[0], bytes(a[1]))
# --------------------------------------------------------------------
# Source for plotting strip charts of DQM objects.
class DQMStripChartSource(Accelerator.DQMStripChartSource):
def __init__(self, server, statedir):
Accelerator.DQMStripChartSource.__init__(self)
self.server = server
# Generate a strip chart. Passes list of server sources, an
# optional source for the "current" object choice, object path
# and the render options to the C++ layer to process.
def plot(self, *path, **options):
if "trend" not in options:
raise HTTPError(500, "Missing trend argument")
sources = dict(
(s.plothook, s) for s in self.server.sources if getattr(s, "plothook", None)
)
info = None
current = options.get("current", None)
if current != None:
if not isinstance(current, str):
raise HTTPError(500, "Incorrect current option")
(srcname, runnr, dataset) = current.split("/", 2)
if srcname in sources and srcname != "unknown":
info = (sources[srcname], int(runnr), "/" + dataset)
a = self._plot(list(sources.values()), info, "/".join(path), options)
return (a[0], bytes(a[1]))
# --------------------------------------------------------------------
# Source for plotting byLumi Certification Results of DQM.
class DQMCertificationSource(Accelerator.DQMCertificationSource):
def __init__(self, server, statedir):
Accelerator.DQMCertificationSource.__init__(self)
self.server = server
# Generate a bylumi certification strip chart. Pass the source for
# the "current" object choice, path and the render options to the
# C++ layer to process.
def plot(self, *path, **options):
sources = dict(
(s.plothook, s) for s in self.server.sources if getattr(s, "plothook", None)
)
info = None
current = options.get("current", None)
if current != None:
if not isinstance(current, str):
raise HTTPError(500, "Incorrect current option")
(srcname, runnr, dataset) = current.split("/", 2)
if srcname in sources and srcname != "unknown":
info = (sources[srcname], int(runnr), "/" + dataset)
a = self._plot(info, ".".join(path), "/".join(path[:-1]), path[-1], options)
return (a[0], bytes(a[1]))
# --------------------------------------------------------------------
# DQM data source which provides layout content from python
# configuration files. There is no backend process attached to this
# data source.
#
# Takes a python dictionary as the configuration parameter. The
# dictionary contains layout definitions.
#
# Once the layout definitions are parsed by the C++ back-end, simply
# returns the list of known layouts. No checks are made to ensure the
# listed monitor elements actually exist; non-existent ones will
# simply generate a warning when rendered.
#
# This source does not produce plots. Plots are provided by the
# sources which provide the objects the layouts refer to. All the
# real functionality is implemented in the C++ layer.
class DQMLayoutSource(Accelerator.DQMLayoutSource):
def __init__(self, server, statedir):
# Pass the layout dictionary directly to C++ Accelerator.
Accelerator.DQMLayoutSource.__init__(self)
d = statedir.replace("/dqmlayout", "")
if os.path.exists("%s/layouts.json" % d):
Accelerator.DQMLayoutSource._pushLayouts(
self, json.loads(open("%s/layouts.json" % d).read())
)
# --------------------------------------------------------------------
# DQM data source providing content from DQM data delivered over
# network from upstream "DQMCollector".
#
# Takes as parameter the options for the "visDQMRender" process. This
# GUI server side object decodes those arguments and determines the
# host and port to connect to reach the backend processes.
#
# All the monitoring and processing is done in the C++ accelerator
# class this python class inherits from. The python layer is just
# a glue layer to pass data between the two.
#
# This source works with visDQMRender to make object images: we get
# the object data via DQMCollector and pass it to visDQMRender which
# returns back the PNG image. The image requests block until the
# render process returns the image data. Each HTTP server thread
# has a semi-persistent socket to the render process; cf. ROOTImage.
# Note that there is no time out on retrieving image data from the
# upstream source, the DQM network layer will automatically time out
# after a while. If the image rendering gets stuck, the process will
# automatically commit a suicide and restart.
#
# .opts Configuration parameters
# dataset - Dataset name for online datasets (fixed)
# verbose - Flag to cause DQM net to be chatty or quiet (fixed)
# dqmhost - DQMCollector host name, taken from --collector option.
# dqmport - DQMCollector port, taken from --collector option.
# plotport - Port at which visDQMRender is listening, taken from --listen option.
class DQMLiveSource(Accelerator.DQMLiveSource):
# Start off the live backend and hook up to server transitions.
def __init__(self, server, statedir, collector, *params):
self.opts = {
"dataset": "/Global/Online/ALL",
"verbose": False,
"dqmhost": "localhost",
"dqmport": DEF_DQM_PORT,
}
m = re.match(r"((\S+):)?(\d+)", collector)
if m:
if m.group(2) != "":
self.opts["dqmhost"] = m.group(2)
self.opts["dqmport"] = int(m.group(3))
Accelerator.DQMLiveSource.__init__(self, server, self.opts)
engine.subscribe("exit", lambda *args: self._exit(), priority=100)
# Generate an object image given an object path and options.
def plot(self, runnr, dsP, dsW, dsT, *path, **options):
a = self._plot("/".join(path), options)
return (a[0], bytes(a[1]))
# --------------------------------------------------------------------
# DQM data source providing content from archived DQM data files.
# All the real functionality is implemented in the C++ layer. This
# source works with visDQMRender to make object images: we ship the
# streamer info and streamed objects to the backend and it returns
# back the PNG image.
#
# .opts Configuration parameters
# plotport - Port at which visDQMRender is listening.
# rxonline - Regexp to recognise online dataset name.
# index - Path to the index directory.
class DQMArchiveSource(Accelerator.DQMArchiveSource):
def __init__(self, server, statedir, indexdir, rxonline, *params):
self.opts = {"index": indexdir, "rxonline": rxonline}
Accelerator.DQMArchiveSource.__init__(self, server, self.opts)
engine.subscribe("exit", lambda *args: self._exit(), priority=100)
# Generate an object image given an object type ('scalar' or
# 'rootobj'), the run number, dataset path, object name and render
# options. See ROOTImage for details about image generation.
def plot(self, runnr, dsP, dsW, dsT, *path, **options):
a = self._plot(
int(runnr), "/".join(("", dsP, dsW, dsT)), "/".join(path), options
)
return (a[0], bytes(a[1]))
# Generate a json describtion given an object type ('scalar' or
# 'rootobj'), the run number, dataset path, object name and render
# options.
def getJson(self, runnr, dsP, dsW, dsT, *path, **options):
return self._getJson(
int(runnr), "/".join(("", dsP, dsW, dsT)), "/".join(path), options
)
# --------------------------------------------------------------------
# .sessiondef
# .gui
# .rank
# .category
# .name
# .match
# .warnings Recent warnings printed to the logs.
class DQMWorkspace:
sessiondef = {
"dqm.sample.vary": "any",
"dqm.sample.order": "dataset",
"dqm.sample.prevws": "",
"dqm.sample.pattern": "",
"dqm.sample.dynsearch": "yes",
#'dqm.sample.type': 0,
#'dqm.sample.runnr': 0,
#'dqm.sample.dataset': "",
"dqm.play.prevws": "",
"dqm.play.interval": 5,
"dqm.play.pos": 0,
#'dqm.panel.tools.show': 1,
#'dqm.panel.tools.x': -1,
#'dqm.panel.tools.y': -1,
#'dqm.panel.help.show': 1,
#'dqm.panel.help.x': -1,
#'dqm.panel.help.y': -1,
#'dqm.panel.custom.show': 1,
#'dqm.panel.custom.x': -1,
#'dqm.panel.custom.y': -1,
"dqm.qplot": "",
"dqm.search": "",
"dqm.filter": "all",
"dqm.strip.type": "object",
"dqm.strip.omit": "none",
"dqm.strip.axis": "run",
"dqm.strip.n": "",
"dqm.showstats": "1",
"dqm.showerrbars": "0",
"dqm.reference": {
"show": "customise",
"position": "overlay",
"norm": "True",
"param": [
{"type": "refobj", "run": "", "dataset": "", "label": "", "ktest": ""},
{"type": "none", "run": "", "dataset": "", "label": "", "ktest": ""},
{"type": "none", "run": "", "dataset": "", "label": "", "ktest": ""},
{"type": "none", "run": "", "dataset": "", "label": "", "ktest": ""},
],
},
"dqm.submenu": "data",
"dqm.size": "M",
"dqm.root": {},
"dqm.focus": {},
"dqm.drawopts": {},
"dqm.myobjs": {},
}
def __init__(self, gui, rank, category, name):
# gui._addCSSFragment("%s/fonts/fonts.css" % gui._yui)
gui._addCSSFragment("%s/resources/css/ext-all.css" % gui._extjs)
gui._addCSSFragment("%s/container/assets/skins/sam/container.css" % gui._yui)
gui._addCSSFragment("%s/resize/assets/skins/sam/resize.css" % gui._yui)
gui._addJSFragment("%s/adapter/ext/ext-base.js" % gui._extjs, False)
gui._addJSFragment("%s/ext-all.js" % gui._extjs, False)
gui._addJSFragment("%s/utilities/utilities.js" % gui._yui, False)
gui._addJSFragment("%s/container/container-min.js" % gui._yui, False)
gui._addJSFragment("%s/resize/resize-min.js" % gui._yui, False)
gui.css = [
x for x in gui.css if x[0] != "%s/css/Core/style.css" % gui.contentpath
]
gui._addCSSFragment("%s/css/DQM/style.css" % gui.contentpath)
for p in (
"Canvas",
"Header",
"Quality",
"Sample",
"Summary",
"Play",
"Certification",
):
gui._addJSFragment("%s/javascript/DQM/%s.js" % (gui.contentpath, p))
self.gui = gui
self.rank = rank
self.category = category
self.name = name
self.warnings = {}
# Customise server on start-up. Force hidden internal workspaces.
def customise(self):
if "Sample" not in (w.name for w in self.gui.workspaces):
self.gui.workspaces.append(DQMSampleWorkspace(self.gui))
if "Play" not in (w.name for w in self.gui.workspaces):
self.gui.workspaces.append(DQMPlayWorkspace(self.gui))
# Initialise a new session.
def initialiseSession(self, session):
for var, value in self.sessiondef.items():
if var not in session:
session[var] = deepcopy(value)
# Make sure the accessed object name is valid.
def _checkObjectName(self, o):
if not re.match(r"^[-+=_()/# A-Za-z0-9]*$", o):
if o not in self.warnings:
_logwarn("attempt to access unsafe object or version '%s'" % o)
self.warnings[o] = 1
raise HTTPError(500, "Attempt to access unsafe object")
return o
# Set session parameters, checking them for validity.
def _set(
self,
session,
samplevary=None,
sampleorder=None,
sampleprevws=None,
samplepat=None,
sampledynsearch=None,
sampletype=None,
sampleimportversion=None,
dataset=None,
runnr=None,
qplot=None,
filter=None,
showstats=None,
showerrbars=None,
referencepos=None,
referenceshow=None,
referencenorm=None,
referenceobj1=None,
referenceobj2=None,
referenceobj3=None,
referenceobj4=None,
striptype=None,
stripruns=None,
stripaxis=None,
stripomit=None,
search=None,
submenu=None,
size=None,
playprevws=None,
playinterval=None,
playpos=None,
root=None,
focus=None,
reset=None,
add=None,
zoom=None,
certzoom=None,
**kwargs,
):
if samplevary != None:
if not isinstance(samplevary, str) or samplevary not in (
"any",
"run",
"dataset",
):
raise HTTPError(500, "Incorrect sample vary parameter")
session["dqm.sample.vary"] = samplevary
if sampleorder != None:
if not isinstance(sampleorder, str) or sampleorder not in (
"run",
"dataset",
):
raise HTTPError(500, "Incorrect sample order parameter")
session["dqm.sample.order"] = sampleorder
if sampleprevws != None:
if not isinstance(sampleprevws, str) or sampleprevws not in (
x.name for x in self.gui.workspaces