msmonitor 2.3.10__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.
Files changed (210) hide show
  1. Utils/CPMetrics.py +270 -0
  2. Utils/CertTools.py +62 -0
  3. Utils/EmailAlert.py +50 -0
  4. Utils/ExtendedUnitTestCase.py +62 -0
  5. Utils/FileTools.py +182 -0
  6. Utils/IteratorTools.py +80 -0
  7. Utils/MathUtils.py +31 -0
  8. Utils/MemoryCache.py +119 -0
  9. Utils/Patterns.py +24 -0
  10. Utils/Pipeline.py +137 -0
  11. Utils/PortForward.py +97 -0
  12. Utils/ProcessStats.py +103 -0
  13. Utils/PythonVersion.py +17 -0
  14. Utils/Signals.py +36 -0
  15. Utils/TemporaryEnvironment.py +27 -0
  16. Utils/Throttled.py +227 -0
  17. Utils/Timers.py +130 -0
  18. Utils/Timestamps.py +86 -0
  19. Utils/TokenManager.py +143 -0
  20. Utils/Tracing.py +60 -0
  21. Utils/TwPrint.py +98 -0
  22. Utils/Utilities.py +308 -0
  23. Utils/__init__.py +11 -0
  24. WMCore/Algorithms/Alarm.py +39 -0
  25. WMCore/Algorithms/MathAlgos.py +274 -0
  26. WMCore/Algorithms/MiscAlgos.py +67 -0
  27. WMCore/Algorithms/ParseXMLFile.py +115 -0
  28. WMCore/Algorithms/Permissions.py +27 -0
  29. WMCore/Algorithms/Singleton.py +58 -0
  30. WMCore/Algorithms/SubprocessAlgos.py +129 -0
  31. WMCore/Algorithms/__init__.py +7 -0
  32. WMCore/Cache/GenericDataCache.py +98 -0
  33. WMCore/Cache/WMConfigCache.py +572 -0
  34. WMCore/Cache/__init__.py +0 -0
  35. WMCore/Configuration.py +651 -0
  36. WMCore/DAOFactory.py +47 -0
  37. WMCore/DataStructs/File.py +177 -0
  38. WMCore/DataStructs/Fileset.py +140 -0
  39. WMCore/DataStructs/Job.py +182 -0
  40. WMCore/DataStructs/JobGroup.py +142 -0
  41. WMCore/DataStructs/JobPackage.py +49 -0
  42. WMCore/DataStructs/LumiList.py +734 -0
  43. WMCore/DataStructs/Mask.py +219 -0
  44. WMCore/DataStructs/MathStructs/ContinuousSummaryHistogram.py +197 -0
  45. WMCore/DataStructs/MathStructs/DiscreteSummaryHistogram.py +92 -0
  46. WMCore/DataStructs/MathStructs/SummaryHistogram.py +117 -0
  47. WMCore/DataStructs/MathStructs/__init__.py +0 -0
  48. WMCore/DataStructs/Pickleable.py +24 -0
  49. WMCore/DataStructs/Run.py +256 -0
  50. WMCore/DataStructs/Subscription.py +175 -0
  51. WMCore/DataStructs/WMObject.py +47 -0
  52. WMCore/DataStructs/WorkUnit.py +112 -0
  53. WMCore/DataStructs/Workflow.py +60 -0
  54. WMCore/DataStructs/__init__.py +8 -0
  55. WMCore/Database/CMSCouch.py +1349 -0
  56. WMCore/Database/ConfigDBMap.py +29 -0
  57. WMCore/Database/CouchUtils.py +118 -0
  58. WMCore/Database/DBCore.py +198 -0
  59. WMCore/Database/DBCreator.py +113 -0
  60. WMCore/Database/DBExceptionHandler.py +57 -0
  61. WMCore/Database/DBFactory.py +110 -0
  62. WMCore/Database/DBFormatter.py +177 -0
  63. WMCore/Database/Dialects.py +13 -0
  64. WMCore/Database/ExecuteDAO.py +327 -0
  65. WMCore/Database/MongoDB.py +241 -0
  66. WMCore/Database/MySQL/Destroy.py +42 -0
  67. WMCore/Database/MySQL/ListUserContent.py +20 -0
  68. WMCore/Database/MySQL/__init__.py +9 -0
  69. WMCore/Database/MySQLCore.py +132 -0
  70. WMCore/Database/Oracle/Destroy.py +56 -0
  71. WMCore/Database/Oracle/ListUserContent.py +19 -0
  72. WMCore/Database/Oracle/__init__.py +9 -0
  73. WMCore/Database/ResultSet.py +44 -0
  74. WMCore/Database/Transaction.py +91 -0
  75. WMCore/Database/__init__.py +9 -0
  76. WMCore/Database/ipy_profile_couch.py +438 -0
  77. WMCore/GroupUser/CouchObject.py +127 -0
  78. WMCore/GroupUser/Decorators.py +51 -0
  79. WMCore/GroupUser/Group.py +33 -0
  80. WMCore/GroupUser/Interface.py +73 -0
  81. WMCore/GroupUser/User.py +96 -0
  82. WMCore/GroupUser/__init__.py +11 -0
  83. WMCore/Lexicon.py +836 -0
  84. WMCore/MicroService/CherryPyThreads/HeartbeatMonitor.py +6 -0
  85. WMCore/MicroService/CherryPyThreads/__init__.py +0 -0
  86. WMCore/MicroService/DataStructs/DefaultStructs.py +101 -0
  87. WMCore/MicroService/DataStructs/__init__.py +0 -0
  88. WMCore/MicroService/MSCore/MSAuth.py +153 -0
  89. WMCore/MicroService/MSCore/MSCore.py +113 -0
  90. WMCore/MicroService/MSCore/MSManager.py +484 -0
  91. WMCore/MicroService/MSCore/TaskManager.py +218 -0
  92. WMCore/MicroService/MSCore/__init__.py +0 -0
  93. WMCore/MicroService/MSMonitor/MSMonitor.py +270 -0
  94. WMCore/MicroService/MSMonitor/__init__.py +0 -0
  95. WMCore/MicroService/Service/Data.py +225 -0
  96. WMCore/MicroService/Service/RestApiHub.py +46 -0
  97. WMCore/MicroService/Service/__init__.py +0 -0
  98. WMCore/MicroService/Tools/Common.py +579 -0
  99. WMCore/MicroService/Tools/PycurlRucio.py +419 -0
  100. WMCore/MicroService/Tools/__init__.py +0 -0
  101. WMCore/MicroService/WebGui/FrontPage.py +56 -0
  102. WMCore/MicroService/WebGui/__init__.py +0 -0
  103. WMCore/REST/Auth.py +202 -0
  104. WMCore/REST/CherryPyPeriodicTask.py +166 -0
  105. WMCore/REST/Error.py +333 -0
  106. WMCore/REST/Format.py +642 -0
  107. WMCore/REST/HeartbeatMonitorBase.py +90 -0
  108. WMCore/REST/Main.py +623 -0
  109. WMCore/REST/Server.py +2435 -0
  110. WMCore/REST/Services.py +24 -0
  111. WMCore/REST/Test.py +120 -0
  112. WMCore/REST/Tools.py +38 -0
  113. WMCore/REST/Validation.py +250 -0
  114. WMCore/REST/__init__.py +1 -0
  115. WMCore/ReqMgr/DataStructs/RequestStatus.py +209 -0
  116. WMCore/ReqMgr/DataStructs/RequestType.py +13 -0
  117. WMCore/ReqMgr/DataStructs/__init__.py +0 -0
  118. WMCore/ReqMgr/__init__.py +1 -0
  119. WMCore/Services/AlertManager/AlertManagerAPI.py +111 -0
  120. WMCore/Services/AlertManager/__init__.py +0 -0
  121. WMCore/Services/CRIC/CRIC.py +238 -0
  122. WMCore/Services/CRIC/__init__.py +0 -0
  123. WMCore/Services/DBS/DBS3Reader.py +1044 -0
  124. WMCore/Services/DBS/DBSConcurrency.py +44 -0
  125. WMCore/Services/DBS/DBSErrors.py +113 -0
  126. WMCore/Services/DBS/DBSReader.py +23 -0
  127. WMCore/Services/DBS/DBSUtils.py +139 -0
  128. WMCore/Services/DBS/DBSWriterObjects.py +381 -0
  129. WMCore/Services/DBS/ProdException.py +133 -0
  130. WMCore/Services/DBS/__init__.py +8 -0
  131. WMCore/Services/FWJRDB/FWJRDBAPI.py +118 -0
  132. WMCore/Services/FWJRDB/__init__.py +0 -0
  133. WMCore/Services/HTTPS/HTTPSAuthHandler.py +66 -0
  134. WMCore/Services/HTTPS/__init__.py +0 -0
  135. WMCore/Services/LogDB/LogDB.py +201 -0
  136. WMCore/Services/LogDB/LogDBBackend.py +191 -0
  137. WMCore/Services/LogDB/LogDBExceptions.py +11 -0
  138. WMCore/Services/LogDB/LogDBReport.py +85 -0
  139. WMCore/Services/LogDB/__init__.py +0 -0
  140. WMCore/Services/MSPileup/__init__.py +0 -0
  141. WMCore/Services/MSUtils/MSUtils.py +54 -0
  142. WMCore/Services/MSUtils/__init__.py +0 -0
  143. WMCore/Services/McM/McM.py +173 -0
  144. WMCore/Services/McM/__init__.py +8 -0
  145. WMCore/Services/MonIT/Grafana.py +133 -0
  146. WMCore/Services/MonIT/__init__.py +0 -0
  147. WMCore/Services/PyCondor/PyCondorAPI.py +154 -0
  148. WMCore/Services/PyCondor/PyCondorUtils.py +105 -0
  149. WMCore/Services/PyCondor/__init__.py +0 -0
  150. WMCore/Services/ReqMgr/ReqMgr.py +261 -0
  151. WMCore/Services/ReqMgr/__init__.py +0 -0
  152. WMCore/Services/ReqMgrAux/ReqMgrAux.py +419 -0
  153. WMCore/Services/ReqMgrAux/__init__.py +0 -0
  154. WMCore/Services/RequestDB/RequestDBReader.py +267 -0
  155. WMCore/Services/RequestDB/RequestDBWriter.py +39 -0
  156. WMCore/Services/RequestDB/__init__.py +0 -0
  157. WMCore/Services/Requests.py +624 -0
  158. WMCore/Services/Rucio/Rucio.py +1287 -0
  159. WMCore/Services/Rucio/RucioUtils.py +74 -0
  160. WMCore/Services/Rucio/__init__.py +0 -0
  161. WMCore/Services/RucioConMon/RucioConMon.py +128 -0
  162. WMCore/Services/RucioConMon/__init__.py +0 -0
  163. WMCore/Services/Service.py +400 -0
  164. WMCore/Services/StompAMQ/__init__.py +0 -0
  165. WMCore/Services/TagCollector/TagCollector.py +155 -0
  166. WMCore/Services/TagCollector/XMLUtils.py +98 -0
  167. WMCore/Services/TagCollector/__init__.py +0 -0
  168. WMCore/Services/UUIDLib.py +13 -0
  169. WMCore/Services/UserFileCache/UserFileCache.py +160 -0
  170. WMCore/Services/UserFileCache/__init__.py +8 -0
  171. WMCore/Services/WMAgent/WMAgent.py +63 -0
  172. WMCore/Services/WMAgent/__init__.py +0 -0
  173. WMCore/Services/WMArchive/CMSSWMetrics.py +526 -0
  174. WMCore/Services/WMArchive/DataMap.py +463 -0
  175. WMCore/Services/WMArchive/WMArchive.py +33 -0
  176. WMCore/Services/WMArchive/__init__.py +0 -0
  177. WMCore/Services/WMBS/WMBS.py +97 -0
  178. WMCore/Services/WMBS/__init__.py +0 -0
  179. WMCore/Services/WMStats/DataStruct/RequestInfoCollection.py +300 -0
  180. WMCore/Services/WMStats/DataStruct/__init__.py +0 -0
  181. WMCore/Services/WMStats/WMStatsPycurl.py +145 -0
  182. WMCore/Services/WMStats/WMStatsReader.py +445 -0
  183. WMCore/Services/WMStats/WMStatsWriter.py +273 -0
  184. WMCore/Services/WMStats/__init__.py +0 -0
  185. WMCore/Services/WMStatsServer/WMStatsServer.py +134 -0
  186. WMCore/Services/WMStatsServer/__init__.py +0 -0
  187. WMCore/Services/WorkQueue/WorkQueue.py +492 -0
  188. WMCore/Services/WorkQueue/__init__.py +0 -0
  189. WMCore/Services/__init__.py +8 -0
  190. WMCore/Services/pycurl_manager.py +574 -0
  191. WMCore/WMBase.py +50 -0
  192. WMCore/WMConnectionBase.py +164 -0
  193. WMCore/WMException.py +183 -0
  194. WMCore/WMExceptions.py +269 -0
  195. WMCore/WMFactory.py +76 -0
  196. WMCore/WMInit.py +228 -0
  197. WMCore/WMLogging.py +108 -0
  198. WMCore/Wrappers/JsonWrapper/JSONThunker.py +342 -0
  199. WMCore/Wrappers/JsonWrapper/__init__.py +7 -0
  200. WMCore/Wrappers/__init__.py +6 -0
  201. WMCore/__init__.py +10 -0
  202. msmonitor-2.3.10.data/data/bin/wmc-dist-patch +15 -0
  203. msmonitor-2.3.10.data/data/bin/wmc-dist-unpatch +8 -0
  204. msmonitor-2.3.10.data/data/bin/wmc-httpd +3 -0
  205. msmonitor-2.3.10.dist-info/LICENSE +202 -0
  206. msmonitor-2.3.10.dist-info/METADATA +21 -0
  207. msmonitor-2.3.10.dist-info/NOTICE +16 -0
  208. msmonitor-2.3.10.dist-info/RECORD +210 -0
  209. msmonitor-2.3.10.dist-info/WHEEL +5 -0
  210. msmonitor-2.3.10.dist-info/top_level.txt +2 -0
@@ -0,0 +1,579 @@
1
+ """
2
+ Set of common utilities for Unified service.
3
+
4
+ Author: Valentin Kuznetsov <vkuznet [AT] gmail [DOT] com>
5
+ Original code: https://github.com/CMSCompOps/WmAgentScripts/Unified
6
+ """
7
+
8
+ # futures
9
+ from __future__ import division, print_function, absolute_import
10
+
11
+ from future import standard_library
12
+ standard_library.install_aliases()
13
+
14
+ # system modules
15
+ import json
16
+ import logging
17
+ import math
18
+ import re
19
+ import time
20
+ from urllib.parse import quote, unquote
21
+
22
+ # WMCore modules
23
+ from Utils.IteratorTools import grouper
24
+ from Utils.CertTools import ckey, cert
25
+ from WMCore.Services.pycurl_manager import RequestHandler
26
+ from WMCore.Services.pycurl_manager import getdata as multi_getdata
27
+
28
+ # static variables
29
+ STEP_PAT = re.compile(r'Step[0-9]')
30
+ TASK_PAT = re.compile(r'Task[0-9]')
31
+
32
+
33
+ def hasHTTPFailed(row):
34
+ """
35
+ Evaluates whether the HTTP request through PyCurl failed or not.
36
+
37
+ :param row: dictionary data returned from pycurl_manager module
38
+ :return: a boolean confirming failure or not
39
+ """
40
+ if 'data' not in row:
41
+ return True
42
+ if int(row.get('code', 200)) == 200:
43
+ return False
44
+ return True
45
+
46
+
47
+ def getMSLogger(verbose, logger=None):
48
+ """
49
+ _getMSLogger_
50
+
51
+ Return a logger object using the standard WMCore formatter
52
+ :param verbose: boolean setting debug or not
53
+ :return: a logger object
54
+ """
55
+ if logger:
56
+ return logger
57
+
58
+ verbose = logging.DEBUG if verbose else logging.INFO
59
+ logger = logging.getLogger()
60
+ logging.basicConfig(format="%(asctime)s:%(levelname)s:%(module)s: %(message)s",
61
+ level=verbose)
62
+ return logger
63
+
64
+
65
+ def isRelVal(reqDict):
66
+ """
67
+ Helper function to evaluate whether the workflow is RelVal or not.
68
+ :param reqDict: dictionary with the workflow description
69
+ :return: True if it's a RelVal workflow, otherwise False
70
+ """
71
+ return reqDict.get("SubRequestType", "") in ['RelVal', 'HIRelVal']
72
+
73
+
74
+ def dbsInfo(datasets, dbsUrl):
75
+ "Provides DBS info about dataset blocks"
76
+ datasetBlocks = {}
77
+ datasetSizes = {}
78
+ datasetTransfers = {}
79
+ if not datasets:
80
+ return datasetBlocks, datasetSizes, datasetTransfers
81
+
82
+ urls = ['%s/blocks?detail=True&dataset=%s' % (dbsUrl, d) for d in datasets]
83
+ logging.info("Executing %d requests against DBS 'blocks' API, with details", len(urls))
84
+ data = multi_getdata(urls, ckey(), cert())
85
+
86
+ for row in data:
87
+ dataset = row['url'].split('=')[-1]
88
+ if hasHTTPFailed(row):
89
+ print("FAILURE: dbsInfo for %s. Error: %s %s" % (dataset, row.get('code'), row.get('error')))
90
+ continue
91
+ rows = json.loads(row['data'])
92
+ blocks = []
93
+ size = 0
94
+ datasetTransfers.setdefault(dataset, {}) # flat dict in the format of blockName: blockSize
95
+ for item in rows:
96
+ blocks.append(item['block_name'])
97
+ size += item['block_size']
98
+ datasetTransfers[dataset].update({item['block_name']: item['block_size']})
99
+ datasetBlocks[dataset] = blocks
100
+ datasetSizes[dataset] = size
101
+
102
+ return datasetBlocks, datasetSizes, datasetTransfers
103
+
104
+
105
+ def getPileupDatasetSizes(datasets, phedexUrl):
106
+ """
107
+ Given a list of datasets, find all their blocks with replicas
108
+ available, i.e., blocks that have valid files to be processed,
109
+ and calculate the total dataset size
110
+ :param datasets: list of dataset names
111
+ :param phedexUrl: a string with the PhEDEx URL
112
+ :return: a dictionary of datasets and their respective sizes
113
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
114
+ """
115
+ sizeByDset = {}
116
+ if not datasets:
117
+ return sizeByDset
118
+
119
+ urls = ['%s/blockreplicas?dataset=%s' % (phedexUrl, dset) for dset in datasets]
120
+ logging.info("Executing %d requests against PhEDEx 'blockreplicas' API", len(urls))
121
+ data = multi_getdata(urls, ckey(), cert())
122
+
123
+ for row in data:
124
+ dataset = row['url'].split('=')[-1]
125
+ if row['data'] is None:
126
+ print("Failure in getPileupDatasetSizes for dataset %s. Error: %s %s" % (dataset,
127
+ row.get('code'),
128
+ row.get('error')))
129
+ sizeByDset.setdefault(dataset, None)
130
+ continue
131
+ rows = json.loads(row['data'])
132
+ sizeByDset.setdefault(dataset, 0)
133
+ try:
134
+ for item in rows['phedex']['block']:
135
+ sizeByDset[dataset] += item['bytes']
136
+ except Exception as exc:
137
+ print("Failure in getPileupDatasetSizes for dataset %s. Error: %s" % (dataset, str(exc)))
138
+ sizeByDset[dataset] = None
139
+ return sizeByDset
140
+
141
+
142
+ def getBlockReplicasAndSize(datasets, phedexUrl, group=None):
143
+ """
144
+ Given a list of datasets, find all their blocks with replicas
145
+ available (thus blocks with at least 1 valid file), completed
146
+ and subscribed.
147
+ If PhEDEx group is provided, make sure it's subscribed under that
148
+ same group.
149
+ :param datasets: list of dataset names
150
+ :param phedexUrl: a string with the PhEDEx URL
151
+ :param group: optional PhEDEx group name
152
+ :return: a dictionary in the form of:
153
+ {"dataset":
154
+ {"block":
155
+ {"blockSize": 111, "locations": ["x", "y"]}
156
+ }
157
+ }
158
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
159
+ """
160
+ dsetBlockSize = {}
161
+ if not datasets:
162
+ return dsetBlockSize
163
+
164
+ urls = ['%s/blockreplicas?dataset=%s' % (phedexUrl, dset) for dset in datasets]
165
+ logging.info("Executing %d requests against PhEDEx 'blockreplicas' API", len(urls))
166
+ data = multi_getdata(urls, ckey(), cert())
167
+
168
+ for row in data:
169
+ dataset = row['url'].split('=')[-1]
170
+ if row['data'] is None:
171
+ print("Failure in getBlockReplicasAndSize for dataset %s. Error: %s %s" % (dataset,
172
+ row.get('code'),
173
+ row.get('error')))
174
+ dsetBlockSize.setdefault(dataset, None)
175
+ continue
176
+ rows = json.loads(row['data'])
177
+ dsetBlockSize.setdefault(dataset, {})
178
+ try:
179
+ for item in rows['phedex']['block']:
180
+ block = {item['name']: {'blockSize': item['bytes'], 'locations': []}}
181
+ for repli in item['replica']:
182
+ if repli['complete'] == 'y' and repli['subscribed'] == 'y':
183
+ if not group:
184
+ block[item['name']]['locations'].append(repli['node'])
185
+ elif repli['group'] == group:
186
+ block[item['name']]['locations'].append(repli['node'])
187
+ dsetBlockSize[dataset].update(block)
188
+ except Exception as exc:
189
+ print("Failure in getBlockReplicasAndSize for dataset %s. Error: %s" % (dataset, str(exc)))
190
+ dsetBlockSize[dataset] = None
191
+ return dsetBlockSize
192
+
193
+
194
+ def getPileupSubscriptions(datasets, phedexUrl, group=None, percentMin=99):
195
+ """
196
+ Provided a list of datasets, find dataset level subscriptions where it's
197
+ as complete as `percent_min`.
198
+ :param datasets: list of dataset names
199
+ :param phedexUrl: a string with the PhEDEx URL
200
+ :param group: optional string with the PhEDEx group
201
+ :param percent_min: only return subscriptions that are this complete
202
+ :return: a dictionary of datasets and a list of their location.
203
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
204
+ """
205
+ locationByDset = {}
206
+ if not datasets:
207
+ return locationByDset
208
+
209
+ if group:
210
+ url = "%s/subscriptions?group=%s" % (phedexUrl, group)
211
+ url += "&percent_min=%s&dataset=%s"
212
+ else:
213
+ url = "%s/subscriptions?" % phedexUrl
214
+ url += "percent_min=%s&dataset=%s"
215
+ urls = [url % (percentMin, dset) for dset in datasets]
216
+
217
+ logging.info("Executing %d requests against PhEDEx 'subscriptions' API", len(urls))
218
+ data = multi_getdata(urls, ckey(), cert())
219
+
220
+ for row in data:
221
+ dataset = row['url'].rsplit('=')[-1]
222
+ if row['data'] is None:
223
+ print("Failure in getPileupSubscriptions for dataset %s. Error: %s %s" % (dataset,
224
+ row.get('code'),
225
+ row.get('error')))
226
+ locationByDset.setdefault(dataset, None)
227
+ continue
228
+ rows = json.loads(row['data'])
229
+ locationByDset.setdefault(dataset, [])
230
+ try:
231
+ for item in rows['phedex']['dataset']:
232
+ for subs in item['subscription']:
233
+ locationByDset[dataset].append(subs['node'])
234
+ except Exception as exc:
235
+ print("Failure in getPileupSubscriptions for dataset %s. Error: %s" % (dataset, str(exc)))
236
+ locationByDset[dataset] = None
237
+ return locationByDset
238
+
239
+
240
+ def getBlocksByDsetAndRun(datasetName, runList, dbsUrl):
241
+ """
242
+ Given a dataset name and a list of runs, find all the blocks
243
+ :return: flat list of blocks
244
+ """
245
+ blocks = set()
246
+ if isinstance(runList, set):
247
+ runList = list(runList)
248
+
249
+ urls = []
250
+ for runSlice in grouper(runList, 50):
251
+ urls.append('%s/blocks?run_num=%s&dataset=%s' % (dbsUrl, str(runSlice).replace(" ", ""), datasetName))
252
+ logging.info("Executing %d requests against DBS 'blocks' API, with run_num list", len(urls))
253
+ data = multi_getdata(urls, ckey(), cert())
254
+
255
+ for row in data:
256
+ dataset = row['url'].rsplit('=')[-1]
257
+ if hasHTTPFailed(row):
258
+ msg = "Failure in getBlocksByDsetAndRun for %s. Error: %s %s" % (dataset,
259
+ row.get('code'),
260
+ row.get('error'))
261
+ raise RuntimeError(msg)
262
+ rows = json.loads(row['data'])
263
+ for item in rows:
264
+ blocks.add(item['block_name'])
265
+
266
+ return list(blocks)
267
+
268
+
269
+ def getFileLumisInBlock(blocks, dbsUrl, validFileOnly=1):
270
+ """
271
+ Given a list of blocks, find their file run lumi information
272
+ in DBS for up to 10 blocks concurrently
273
+ :param blocks: list of block names
274
+ :param dbsUrl: string with the DBS URL
275
+ :param validFileOnly: integer flag for valid files only or not
276
+ :return: a dict of blocks with list of file/run/lumi info
277
+ """
278
+ # importing dbs3-client only in the functions where it is used so that
279
+ # we do not need to add it to the docker images of microservices that do
280
+ # not use it.
281
+ from dbs.apis.dbsClient import aggFileLumis
282
+
283
+ runLumisByBlock = {}
284
+ urls = ['%s/filelumis?validFileOnly=%d&block_name=%s' % (dbsUrl, validFileOnly, quote(b)) for b in blocks]
285
+ # limit it to 10 concurrent calls not to overload DBS
286
+ logging.info("Executing %d requests against DBS 'filelumis' API, concurrency limited to 10", len(urls))
287
+ data = multi_getdata(urls, ckey(), cert(), num_conn=10)
288
+
289
+ for row in data:
290
+ blockName = unquote(row['url'].rsplit('=')[-1])
291
+ if hasHTTPFailed(row):
292
+ msg = "Failure in getFileLumisInBlock for block %s. Error: %s %s" % (blockName,
293
+ row.get('code'),
294
+ row.get('error'))
295
+ raise RuntimeError(msg)
296
+ rows = json.loads(row['data'])
297
+ rows = aggFileLumis(rows) # adjust to DBS Go server output
298
+ runLumisByBlock.setdefault(blockName, [])
299
+ for item in rows:
300
+ runLumisByBlock[blockName].append(item)
301
+ return runLumisByBlock
302
+
303
+
304
+ def findBlockParents(blocks, dbsUrl):
305
+ """
306
+ Helper function to find block parents given a list of block names.
307
+ Return a dictionary in the format of:
308
+ {"child dataset name": {"child block": ["parent blocks"],
309
+ "child block": ["parent blocks"], ...}}
310
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
311
+ """
312
+ parentsByBlock = {}
313
+ urls = ['%s/blockparents?block_name=%s' % (dbsUrl, quote(b)) for b in blocks]
314
+ logging.info("Executing %d requests against DBS 'blockparents' API", len(urls))
315
+ data = multi_getdata(urls, ckey(), cert())
316
+ for row in data:
317
+ blockName = unquote(row['url'].rsplit('=')[-1])
318
+ dataset = blockName.split("#")[0]
319
+ if hasHTTPFailed(row):
320
+ print("Failure in findBlockParents for block %s. Error: %s %s" % (blockName,
321
+ row.get('code'),
322
+ row.get('error')))
323
+ parentsByBlock.setdefault(dataset, None)
324
+ continue
325
+ rows = json.loads(row['data'])
326
+ try:
327
+ if dataset in parentsByBlock and parentsByBlock[dataset] is None:
328
+ # then one of the block calls has failed, keep it failed!
329
+ continue
330
+ parentsByBlock.setdefault(dataset, {})
331
+ for item in rows:
332
+ parentsByBlock[dataset].setdefault(item['this_block_name'], set())
333
+ parentsByBlock[dataset][item['this_block_name']].add(item['parent_block_name'])
334
+ except Exception as exc:
335
+ print("Failure in findBlockParents for block %s. Error: %s" % (blockName, str(exc)))
336
+ parentsByBlock[dataset] = None
337
+ return parentsByBlock
338
+
339
+
340
+ def getRunsInBlock(blocks, dbsUrl):
341
+ """
342
+ Provided a list of block names, find their run numbers
343
+ :param blocks: list of block names
344
+ :param dbsUrl: string with the DBS URL
345
+ :return: a dictionary of block names and a list of run numbers
346
+ """
347
+ # importing dbs3-client only in the functions where it is used so that
348
+ # we do not need to add it to the docker images of microservices that do
349
+ # not use it.
350
+ from dbs.apis.dbsClient import aggRuns
351
+
352
+ runsByBlock = {}
353
+ urls = ['%s/runs?block_name=%s' % (dbsUrl, quote(b)) for b in blocks]
354
+ logging.info("Executing %d requests against DBS 'runs' API", len(urls))
355
+ data = multi_getdata(urls, ckey(), cert())
356
+ for row in data:
357
+ blockName = unquote(row['url'].rsplit('=')[-1])
358
+ if hasHTTPFailed(row):
359
+ msg = "Failure in getRunsInBlock for block %s. Error: %s %s" % (blockName,
360
+ row.get('code'),
361
+ row.get('error'))
362
+ raise RuntimeError(msg)
363
+ rows = json.loads(row['data'])
364
+ rows = aggRuns(rows) # adjust to DBS Go server output
365
+ runsByBlock[blockName] = rows[0]['run_num']
366
+ return runsByBlock
367
+
368
+
369
+ def getWorkflow(requestName, reqMgrUrl):
370
+ "Get list of workflow info from ReqMgr2 data-service for given request name"
371
+ headers = {'Accept': 'application/json'}
372
+ params = {}
373
+ url = '%s/data/request/%s' % (reqMgrUrl, requestName)
374
+ mgr = RequestHandler()
375
+ res = mgr.getdata(url, params=params, headers=headers, ckey=ckey(), cert=cert())
376
+ data = json.loads(res)
377
+ return data.get('result', [])
378
+
379
+
380
+ def getDetoxQuota(url):
381
+ "Get list of workflow info from ReqMgr2 data-service for given request name"
382
+ headers = {}
383
+ params = {}
384
+ mgr = RequestHandler()
385
+ res = mgr.getdata(url, params=params, headers=headers, ckey=ckey(), cert=cert())
386
+ res = res.split('\n')
387
+ return res
388
+
389
+
390
+ def eventsLumisInfo(inputs, dbsUrl, validFileOnly=0, sumOverLumi=0):
391
+ "Get information about events and lumis for given set of inputs: blocks or datasets"
392
+ what = 'dataset'
393
+ eventsLumis = {}
394
+ if not inputs:
395
+ return eventsLumis
396
+ if '#' in inputs[0]: # inputs are list of blocks
397
+ what = 'block_name'
398
+ urls = ['%s/filesummaries?validFileOnly=%s&sumOverLumi=%s&%s=%s'
399
+ % (dbsUrl, validFileOnly, sumOverLumi, what, quote(i)) for i in inputs]
400
+ data = multi_getdata(urls, ckey(), cert())
401
+ for row in data:
402
+ data = unquote(row['url'].split('=')[-1])
403
+ if hasHTTPFailed(row):
404
+ print("FAILURE: eventsLumisInfo for %s. Error: %s %s" % (data,
405
+ row.get('code'),
406
+ row.get('error')))
407
+ continue
408
+ rows = json.loads(row['data'])
409
+ for item in rows:
410
+ eventsLumis[data] = item
411
+ return eventsLumis
412
+
413
+
414
+ def getEventsLumis(dataset, dbsUrl, blocks=None, eventsLumis=None):
415
+ "Helper function to return number of events/lumis for given dataset or blocks"
416
+ nevts = nlumis = 0
417
+ if blocks:
418
+ missingBlocks = [b for b in blocks if b not in eventsLumis]
419
+ if missingBlocks:
420
+ eLumis = eventsLumisInfo(missingBlocks, dbsUrl)
421
+ eventsLumis.update(eLumis)
422
+ for block in blocks:
423
+ data = eventsLumis[block]
424
+ nevts += data['num_event']
425
+ nlumis += data['num_lumi']
426
+ return nevts, nlumis
427
+ if eventsLumis and dataset in eventsLumis:
428
+ data = eventsLumis[dataset]
429
+ return data['num_event'], data['num_lumi']
430
+ eLumis = eventsLumisInfo([dataset], dbsUrl)
431
+ data = eLumis.get(dataset, {'num_event': 0, 'num_lumi': 0})
432
+ return data['num_event'], data['num_lumi']
433
+
434
+
435
+ def getComputingTime(workflow, eventsLumis=None, unit='h', dbsUrl=None, logger=None):
436
+ "Return computing time per give workflow"
437
+ logger = getMSLogger(verbose=True, logger=logger)
438
+ cput = None
439
+
440
+ if 'InputDataset' in workflow:
441
+ dataset = workflow['InputDataset']
442
+ if 'BlockWhitelist' in workflow and workflow['BlockWhitelist']:
443
+ nevts, _ = getEventsLumis(dataset, dbsUrl, workflow['BlockWhitelist'], eventsLumis)
444
+ else:
445
+ nevts, _ = getEventsLumis(dataset, dbsUrl, eventsLumis=eventsLumis)
446
+ tpe = workflow['TimePerEvent']
447
+ cput = nevts * tpe
448
+ elif 'Chain' in workflow['RequestType']:
449
+ base = workflow['RequestType'].replace('Chain', '')
450
+ itask = 1
451
+ cput = 0
452
+ carryOn = {}
453
+ while True:
454
+ t = '%s%d' % (base, itask)
455
+ itask += 1
456
+ if t in workflow:
457
+ task = workflow[t]
458
+ if 'InputDataset' in task:
459
+ dataset = task['InputDataset']
460
+ if 'BlockWhitelist' in task and task['BlockWhitelist']:
461
+ nevts, _ = getEventsLumis(dataset, dbsUrl, task['BlockWhitelist'], eventsLumis)
462
+ else:
463
+ nevts, _ = getEventsLumis(dataset, dbsUrl, eventsLumis=eventsLumis)
464
+ elif 'Input%s' % base in task:
465
+ nevts = carryOn[task['Input%s' % base]]
466
+ elif 'RequestNumEvents' in task:
467
+ nevts = float(task['RequestNumEvents'])
468
+ else:
469
+ logger.debug("this is not supported, making it zero cput")
470
+ nevts = 0
471
+ tpe = task.get('TimePerEvent', 1)
472
+ carryOn[task['%sName' % base]] = nevts
473
+ if 'FilterEfficiency' in task:
474
+ carryOn[task['%sName' % base]] *= task['FilterEfficiency']
475
+ cput += tpe * nevts
476
+ else:
477
+ break
478
+ else:
479
+ nevts = float(workflow.get('RequestNumEvents', 0))
480
+ feff = float(workflow.get('FilterEfficiency', 1))
481
+ tpe = workflow.get('TimePerEvent', 1)
482
+ cput = nevts / feff * tpe
483
+
484
+ if cput is None:
485
+ return 0
486
+
487
+ if unit == 'm':
488
+ cput = cput / (60.)
489
+ if unit == 'h':
490
+ cput = cput / (60. * 60.)
491
+ if unit == 'd':
492
+ cput = cput / (60. * 60. * 24.)
493
+ return cput
494
+
495
+
496
+ def sigmoid(x):
497
+ "Sigmoid function"
498
+ return 1. / (1 + math.exp(-x))
499
+
500
+
501
+ def getNCopies(cpuHours, minN=2, maxN=3, weight=50000, constant=100000):
502
+ "Calculate number of copies for given workflow"
503
+ func = sigmoid(-constant / weight)
504
+ fact = (maxN - minN) / (1 - func)
505
+ base = (func * maxN - minN) / (func - 1)
506
+ return int(base + fact * sigmoid((cpuHours - constant) / weight))
507
+
508
+
509
+ def teraBytes(size):
510
+ "Return size in TB (Terabytes)"
511
+ return size / (1000 ** 4)
512
+
513
+
514
+ def gigaBytes(size):
515
+ "Return size in GB (Gigabytes), rounded to 2 digits"
516
+ return round(size / (1000 ** 3), 2)
517
+
518
+
519
+ def elapsedTime(time0, msg='Elapsed time', ndigits=1):
520
+ "Helper function to return elapsed time message"
521
+ msg = "%s: %s sec" % (msg, round(time.time() - time0, ndigits))
522
+ return msg
523
+
524
+
525
+ def getRequest(url, params):
526
+ "Helper function to GET data from given URL"
527
+ mgr = RequestHandler()
528
+ headers = {'Accept': 'application/json'}
529
+ verbose = 0
530
+ if 'verbose' in params:
531
+ verbose = params['verbose']
532
+ del params['verbose']
533
+ data = mgr.getdata(url, params, headers, ckey=ckey(), cert=cert(), verbose=verbose)
534
+ return data
535
+
536
+
537
+ def postRequest(url, params):
538
+ "Helper function to POST request to given URL"
539
+ mgr = RequestHandler()
540
+ headers = {'Accept': 'application/json'}
541
+ verbose = 0
542
+ if 'verbose' in params:
543
+ verbose = params['verbose']
544
+ del params['verbose']
545
+ data = mgr.getdata(url, params, headers, ckey=ckey(), cert=cert(),
546
+ verb='POST', verbose=verbose)
547
+ return data
548
+
549
+
550
+ def findParent(datasets, dbsUrl):
551
+ """
552
+ Helper function to find the parent dataset.
553
+ It returns a dictionary key'ed by the child dataset
554
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
555
+ """
556
+ parentByDset = {}
557
+ if not datasets:
558
+ return parentByDset
559
+
560
+ urls = ['%s/datasetparents?dataset=%s' % (dbsUrl, d) for d in datasets]
561
+ logging.info("Executing %d requests against DBS 'datasetparents' API", len(urls))
562
+ data = multi_getdata(urls, ckey(), cert())
563
+
564
+ for row in data:
565
+ dataset = row['url'].split('=')[-1]
566
+ if hasHTTPFailed(row):
567
+ print("Failure in findParent for dataset %s. Error: %s %s" % (dataset,
568
+ row.get('code'),
569
+ row.get('error')))
570
+ parentByDset.setdefault(dataset, None)
571
+ continue
572
+ rows = json.loads(row['data'])
573
+ try:
574
+ for item in rows:
575
+ parentByDset[item['this_dataset']] = item['parent_dataset']
576
+ except Exception as exc:
577
+ print("Failure in findParent for dataset %s. Error: %s" % (dataset, str(exc)))
578
+ parentByDset[dataset] = None
579
+ return parentByDset