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,419 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Module based on the pycurl_manager module, implementing a few
5
+ functions to call to the Rucio RESTful APIs, leveraging the
6
+ pycurl concurrency.
7
+ """
8
+ from __future__ import print_function, division, absolute_import
9
+
10
+ from builtins import str
11
+ from future.utils import viewitems
12
+
13
+ from future import standard_library
14
+ standard_library.install_aliases()
15
+
16
+ import datetime
17
+ import json
18
+ import logging
19
+ import re
20
+
21
+ from urllib.parse import quote, unquote
22
+
23
+ from Utils.CertTools import cert, ckey
24
+ from WMCore.Services.pycurl_manager import RequestHandler
25
+ from WMCore.Services.pycurl_manager import getdata as multi_getdata
26
+
27
+ ### Amount of days that we wait for stuck rules to be sorted
28
+ ### After that, the rule is not considered and a new rule is created
29
+ STUCK_LIMIT = 7 # 7 days
30
+
31
+
32
+ def parseNewLineJson(stream):
33
+ """
34
+ Parse newline delimited json streaming data
35
+ """
36
+ for line in stream.split("\n"):
37
+ if line:
38
+ yield json.loads(line)
39
+
40
+
41
+ def stringDateToEpoch(strDate):
42
+ """
43
+ Given a date/time in the format of:
44
+ 'Thu, 29 Apr 2021 13:15:42 UTC'
45
+ it returns an integer with the equivalent EPOCH time
46
+ :param strDate: a string with the date and time
47
+ :return: the equivalent EPOCH time (integer)
48
+ """
49
+ timestamp = datetime.datetime.strptime(strDate, "%a, %d %b %Y %H:%M:%S %Z")
50
+ return int(timestamp.strftime('%s'))
51
+
52
+
53
+ def getRucioToken(rucioAuthUrl, rucioAcct):
54
+ """
55
+ Provided a Rucio account, fetch a token from the authentication server
56
+ :param rucioAuthUrl: url to the rucio authentication server
57
+ :param rucioAcct: rucio account to be used
58
+ :return: an integer with the expiration time in EPOCH
59
+ """
60
+ params = {}
61
+ headers = {"X-Rucio-Account": rucioAcct}
62
+
63
+ url = '%s/auth/x509' % rucioAuthUrl
64
+ logging.info("Requesting a token to Rucio for account: %s, against url: %s", rucioAcct, rucioAuthUrl)
65
+ mgr = RequestHandler()
66
+ res = mgr.getheader(url, params=params, headers=headers, ckey=ckey(), cert=cert())
67
+ if res.getReason() == "OK":
68
+ userToken = res.getHeaderKey('X-Rucio-Auth-Token')
69
+ tokenExpiration = res.getHeaderKey('X-Rucio-Auth-Token-Expires')
70
+ logging.info("Retrieved Rucio token valid until: %s", tokenExpiration)
71
+ # convert the human readable expiration time to EPOCH time
72
+ tokenExpiration = stringDateToEpoch(tokenExpiration)
73
+ return userToken, tokenExpiration
74
+
75
+ raise RuntimeError("Failed to acquire a Rucio token. Error: {}".format(res.getReason()))
76
+
77
+
78
+ def renewRucioToken(rucioAuthUrl, userToken):
79
+ """
80
+ Provided a user Rucio token, check it's lifetime and extend it by another hour
81
+ :param rucioAuthUrl: url to the rucio authentication server
82
+ :param rucioAcct: rucio account to be used
83
+ :return: a datetime.datetime object with the new token lifetime
84
+ """
85
+ params = {}
86
+ headers = {"X-Rucio-Auth-Token": userToken}
87
+
88
+ url = '%s/auth/validate' % rucioAuthUrl
89
+ logging.info("Renewing the Rucio token...")
90
+ mgr = RequestHandler()
91
+ res = mgr.getdata(url, params=params, headers=headers, ckey=ckey(), cert=cert())
92
+ try:
93
+ newExpiration = eval(res)['lifetime']
94
+ except Exception as exc:
95
+ raise RuntimeError("Failed to renew Rucio token. Response: {} Error: {}".format(res, str(exc)))
96
+ return newExpiration
97
+
98
+
99
+ def getPileupContainerSizesRucio(containers, rucioUrl, rucioToken, scope="cms"):
100
+ """
101
+ Given a list of containers, find their total size in Rucio
102
+ :param containers: list of container names
103
+ :param rucioUrl: a string with the Rucio URL
104
+ :param rucioToken: a string with the user rucio token
105
+ :param scope: a string with the Rucio scope of our data
106
+ :return: a flat dictionary of container and their respective sizes
107
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
108
+ NOTE: Rucio version of getPileupDatasetSizes()
109
+ """
110
+ sizeByDset = {}
111
+ if not containers:
112
+ return sizeByDset
113
+
114
+ headers = {"X-Rucio-Auth-Token": rucioToken}
115
+
116
+ urls = ['{}/dids/{}/{}?dynamic=anything'.format(rucioUrl, scope, cont) for cont in containers]
117
+ logging.info("Executing %d requests against Rucio for the container size", len(urls))
118
+ data = multi_getdata(urls, ckey(), cert(), headers=headers)
119
+
120
+ for row in data:
121
+ container = row['url'].split('/dids/{}/'.format(scope))[1]
122
+ container = container.replace("?dynamic=anything", "")
123
+ if row['data'] is None:
124
+ msg = "Failure in getPileupContainerSizesRucio for container {}. Response: {}".format(container, row)
125
+ logging.error(msg)
126
+ sizeByDset.setdefault(container, None)
127
+ continue
128
+ response = json.loads(row['data'])
129
+ try:
130
+ sizeByDset.setdefault(container, response['bytes'])
131
+ except KeyError:
132
+ msg = "getPileupContainerSizesRucio function did not return a valid response for container: %s. Error: %s"
133
+ logging.error(msg, container, response)
134
+ sizeByDset.setdefault(container, None)
135
+ continue
136
+ return sizeByDset
137
+
138
+
139
+ def listReplicationRules(containers, rucioAccount, grouping,
140
+ rucioUrl, rucioToken, scope="cms"):
141
+ """
142
+ List all the replication rules for the input filters provided.
143
+ It builds a dictionary of container name and the locations where
144
+ they have a rule locking data on, with some additional rule state
145
+ logic in the code.
146
+ :param containers: list of container names
147
+ :param rucioAccount: string with the rucio account
148
+ :param grouping: rule grouping string, only "A" or "D" are allowed
149
+ :param rucioUrl: string with the Rucio url
150
+ :param rucioToken: string with the Rucio token
151
+ :param scope: string with the data scope
152
+ :return: a flat dictionary key'ed by the container name, with a list of RSE
153
+ expressions that still need to be resolved
154
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
155
+ NOTE-2: Available rule states can be found at:
156
+ https://github.com/rucio/rucio/blob/16f39dffa1608caa0a1af8bbc0fcff2965dccc50/lib/rucio/db/sqla/constants.py#L180
157
+ """
158
+ locationByContainer = {}
159
+ if not containers:
160
+ return locationByContainer
161
+ if grouping not in ["A", "D"]:
162
+ raise RuntimeError("Replication rule grouping value provided ({}) is not allowed!".format(grouping))
163
+
164
+ headers = {"X-Rucio-Auth-Token": rucioToken}
165
+ urls = []
166
+ for cont in containers:
167
+ urls.append('{}/rules/?scope={}&account={}&grouping={}&name={}'.format(rucioUrl, scope, rucioAccount,
168
+ grouping, quote(cont, safe="")))
169
+ logging.info("Executing %d requests against Rucio to list replication rules", len(urls))
170
+ data = multi_getdata(urls, ckey(), cert(), headers=headers)
171
+
172
+ for row in data:
173
+ container = unquote(row['url'].split("name=")[1])
174
+ if "200 OK" not in row['headers']:
175
+ msg = "Failure in listReplicationRules for container {}. Response: {}".format(container, row)
176
+ logging.error(msg)
177
+ locationByContainer.setdefault(container, None)
178
+ continue
179
+ try:
180
+ locationByContainer.setdefault(container, [])
181
+ for item in parseNewLineJson(row['data']):
182
+ if item['state'] in ["U", "SUSPENDED", "R", "REPLICATING", "I", "INJECT"]:
183
+ msg = "Container %s has a rule ID %s in state %s. Will try to create a new rule."
184
+ logging.warning(msg, container, item['id'], item['state'])
185
+ continue
186
+ elif item['state'] in ["S", "STUCK"]:
187
+ if item['error'] == 'NO_SOURCES:NO_SOURCES':
188
+ msg = "Container {} has a STUCK rule with NO_SOURCES.".format(container)
189
+ msg += " Data could be lost forever... Rule info is: {}".format(item)
190
+ logging.warning(msg)
191
+ continue
192
+
193
+ # then calculate for how long it's been stuck
194
+ utcTimeNow = int(datetime.datetime.utcnow().strftime('%s'))
195
+ if item['stuck_at']:
196
+ stuckAt = stringDateToEpoch(item['stuck_at'])
197
+ else:
198
+ # consider it to be stuck since its creation
199
+ stuckAt = stringDateToEpoch(item['created_at'])
200
+
201
+ daysStuck = (utcTimeNow - stuckAt) // (24 * 60 * 60)
202
+ if daysStuck > STUCK_LIMIT:
203
+ msg = "Container {} has a STUCK rule for {} days (limit set to: {}).".format(container,
204
+ daysStuck,
205
+ STUCK_LIMIT)
206
+ msg += " Not going to use it! Rule info: {}".format(item)
207
+ logging.warning(msg)
208
+ continue
209
+ else:
210
+ msg = "Container {} has a STUCK rule for only {} days.".format(container, daysStuck)
211
+ msg += " Considering it for the pileup location"
212
+ logging.info(msg)
213
+ else:
214
+ logging.info("Container %s has rule ID %s in state %s, using it.",
215
+ container, item['id'], item['state'])
216
+
217
+ ### NOTE: this is not an RSE name, but an RSE expression that still needs to be resolved
218
+ locationByContainer[container].append(item['rse_expression'])
219
+ except Exception as exc:
220
+ msg = "listReplicationRules function did not return a valid response for container: %s."
221
+ msg += "Server responded with: %s\nError: %s"
222
+ logging.exception(msg, container, str(exc), row['data'])
223
+ locationByContainer.setdefault(container, None)
224
+ continue
225
+ return locationByContainer
226
+
227
+
228
+ def getPileupSubscriptionsRucio(datasets, rucioUrl, rucioToken, scope="cms"):
229
+ """
230
+ Provided a list of datasets, find dataset level subscriptions where it's
231
+ as complete as `percent_min`.
232
+ :param datasets: list of dataset names
233
+ :param rucioUrl: a string with the Rucio URL
234
+ :param rucioToken: a string with the user rucio token
235
+ :param scope: a string with the Rucio scope of our data
236
+ :return: a dictionary of datasets and a list of their location.
237
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
238
+ """
239
+ # FIXME: we should definitely make a feature request to Rucio...
240
+ # so much, just to get the final RSEs for a container!!!
241
+ locationByDset = {}
242
+ if not datasets:
243
+ return locationByDset
244
+
245
+ headers = {"X-Rucio-Auth-Token": rucioToken}
246
+ # first, resolve the dataset into blocks
247
+ blocksByDset = getContainerBlocksRucio(datasets, rucioUrl, rucioToken, scope)
248
+ urls = []
249
+ for _dset, blocks in viewitems(blocksByDset):
250
+ if blocks:
251
+ for block in blocks:
252
+ urls.append('{}/replicas/{}/{}/datasets'.format(rucioUrl, scope, quote(block)))
253
+
254
+ # this is going to be bloody expensive in terms of HTTP requests
255
+ logging.info("Executing %d requests against Rucio replicas API for blocks", len(urls))
256
+ data = multi_getdata(urls, ckey(), cert(), headers=headers)
257
+ for row in data:
258
+ block = row['url'].split("/{}/".format(scope))[1]
259
+ block = unquote(re.sub("/datasets$", "", block, 1))
260
+ container = block.split("#")[0]
261
+ locationByDset.setdefault(container, set())
262
+ if row['data'] is None:
263
+ msg = "Failure in getPileupSubscriptionsRucio container {} and block {}.".format(container, block)
264
+ msg += " Response: {}".format(row)
265
+ logging.error(msg)
266
+
267
+ locationByDset[container] = None
268
+ continue
269
+ if locationByDset[container] is None:
270
+ # then one of the block requests failed, skip the whole dataset
271
+ continue
272
+ thisBlockRSEs = set()
273
+ for item in parseNewLineJson(row['data']):
274
+ if item['state'] == "AVAILABLE":
275
+ thisBlockRSEs.add(item["rse"])
276
+ logging.info("Block: %s is available at: %s", block, thisBlockRSEs)
277
+ # now we have the final block location
278
+ if not locationByDset[container]:
279
+ # then this is the first block of this dataset
280
+ locationByDset[container] = thisBlockRSEs
281
+ else:
282
+ # otherwise, make an intersection of them
283
+ locationByDset[container] = locationByDset[container] & thisBlockRSEs
284
+ return locationByDset
285
+
286
+
287
+ def getBlocksAndSizeRucio(containers, rucioUrl, rucioToken, scope="cms"):
288
+ """
289
+ Given a list of containers, find all their correspondent blocks and their sizes.
290
+ :param containers: list of container names
291
+ :param rucioUrl: a string with the Rucio URL
292
+ :param rucioToken: a string with the user rucio token
293
+ :param scope: a string with the Rucio scope of our data
294
+ :return: a dictionary in the form of:
295
+ {"dataset":
296
+ {"block":
297
+ {"blockSize": 111, "locations": ["x", "y"]}
298
+ }
299
+ }
300
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
301
+ NOTE2: meant to return an output similar to Common.getBlockReplicasAndSize
302
+ """
303
+ contBlockSize = {}
304
+ if not containers:
305
+ return contBlockSize
306
+
307
+ headers = {"X-Rucio-Auth-Token": rucioToken}
308
+ urls = []
309
+ for cont in containers:
310
+ urls.append('{}/dids/{}/dids/search?type=dataset&long=True&name={}'.format(rucioUrl, scope, quote(cont + "#*")))
311
+ logging.info("Executing %d requests against Rucio DIDs search API for containers", len(urls))
312
+ data = multi_getdata(urls, ckey(), cert(), headers=headers)
313
+ for row in data:
314
+ container = row['url'].split("name=")[1]
315
+ container = unquote(container).replace("#*", "")
316
+ contBlockSize.setdefault(container, {})
317
+ if row['data'] in [None, ""]:
318
+ msg = "Failure in getBlocksAndSizeRucio function for container {}. Response: {}".format(container, row)
319
+ logging.error(msg)
320
+ contBlockSize[container] = None
321
+ continue
322
+
323
+ for item in parseNewLineJson(row['data']):
324
+ # NOTE: we do not care about primary block location in Rucio
325
+ contBlockSize[container][item['name']] = {"blockSize": item['bytes'], "locations": []}
326
+ return contBlockSize
327
+
328
+
329
+ ### NOTE: likely not going to be used for a while
330
+ def getContainerBlocksRucio(containers, rucioUrl, rucioToken, scope="cms"):
331
+ """
332
+ Provided a list of containers, find all their blocks.
333
+ :param containers: list of container names
334
+ :param rucioUrl: a string with the Rucio URL
335
+ :param rucioToken: a string with the user rucio token
336
+ :param scope: a string with the Rucio scope of our data
337
+ :return: a dictionary key'ed by the datasets with a list of blocks.
338
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
339
+ """
340
+ blocksByDset = {}
341
+ if not containers:
342
+ return blocksByDset
343
+
344
+ headers = {"X-Rucio-Auth-Token": rucioToken}
345
+ urls = ['{}/dids/{}/{}/dids'.format(rucioUrl, scope, cont) for cont in containers]
346
+ logging.info("Executing %d requests against Rucio DIDs API for blocks in containers", len(urls))
347
+ data = multi_getdata(urls, ckey(), cert(), headers=headers)
348
+ for row in data:
349
+ container = row['url'].split("/{}/".format(scope))[1]
350
+ container = re.sub("/dids$", "", container, 1)
351
+ if not row['data']:
352
+ logging.warning("Dataset: %s has no blocks in Rucio", container)
353
+ blocksByDset.setdefault(container, [])
354
+ for item in parseNewLineJson(row['data']):
355
+ blocksByDset[container].append(item["name"])
356
+ return blocksByDset
357
+
358
+
359
+ ### NOTE: likely not going to be used for a while
360
+ def getBlockReplicasAndSizeRucio(datasets, rucioUrl, rucioToken, scope="cms"):
361
+ """
362
+ Given a list of datasets, find all their blocks with replicas
363
+ available.
364
+ :param datasets: list of dataset names
365
+ :param rucioUrl: a string with the Rucio URL
366
+ :param rucioToken: a string with the user rucio token
367
+ :param scope: a string with the Rucio scope of our data
368
+ :return: a dictionary in the form of:
369
+ {"dataset":
370
+ {"block":
371
+ {"blockSize": 111, "locations": ["x", "y"]}
372
+ }
373
+ }
374
+ NOTE: Value `None` is returned in case the data-service failed to serve a given request.
375
+ """
376
+ dsetBlockSize = {}
377
+ if not datasets:
378
+ return dsetBlockSize
379
+
380
+ headers = {"X-Rucio-Auth-Token": rucioToken}
381
+ # first, figure out their block names
382
+ blocksByDset = getContainerBlocksRucio(datasets, rucioUrl, rucioToken, scope=scope)
383
+ urls = []
384
+ for _dset, blocks in viewitems(blocksByDset):
385
+ for block in blocks:
386
+ urls.append('{}/replicas/{}/{}/datasets'.format(rucioUrl, scope, quote(block)))
387
+
388
+ # next, query the replicas API for the block location
389
+ # this is going to be bloody expensive in terms of HTTP requests
390
+ logging.info("Executing %d requests against Rucio replicas API for blocks", len(urls))
391
+ data = multi_getdata(urls, ckey(), cert(), headers=headers)
392
+ for row in data:
393
+ block = row['url'].split("/{}/".format(scope))[1]
394
+ block = unquote(re.sub("/datasets$", "", block, 1))
395
+ container = block.split("#")[0]
396
+ dsetBlockSize.setdefault(container, dict())
397
+ if row['data'] is None:
398
+ msg = "Failure in getBlockReplicasAndSizeRucio for container {} and block {}.".format(container, block)
399
+ msg += " Response: {}".format(row)
400
+ logging.error(msg)
401
+
402
+ dsetBlockSize[container] = None
403
+ continue
404
+ if dsetBlockSize[container] is None:
405
+ # then one of the block requests failed, skip the whole dataset
406
+ continue
407
+
408
+ thisBlockRSEs = []
409
+ blockBytes = 0
410
+ for item in parseNewLineJson(row['data']):
411
+ blockBytes = item['bytes']
412
+ if item['state'] == "AVAILABLE":
413
+ thisBlockRSEs.append(item["rse"])
414
+ # now we have the final block location
415
+ if not blockBytes and not thisBlockRSEs:
416
+ logging.warning("Block: %s has no replicas and no size", block)
417
+ else:
418
+ dsetBlockSize[container][block] = {"locations": thisBlockRSEs, "blockSize": blockBytes}
419
+ return dsetBlockSize
File without changes
@@ -0,0 +1,56 @@
1
+ """
2
+ File : FrontPage.py
3
+ Author : Valentin Kuznetsov <vkuznet AT gmail dot com>
4
+ Description: MicroService front page module which defines its web UI.
5
+ """
6
+
7
+ # futures
8
+ from __future__ import print_function, division
9
+
10
+ # system modules
11
+ import os
12
+ import re
13
+
14
+ # WMCore modules
15
+ from WMCore.REST.Server import RESTFrontPage
16
+
17
+
18
+ class FrontPage(RESTFrontPage):
19
+ """MicroService front page.
20
+ MicroService provides only one web page, the front page. The page just
21
+ loads the javascript user interface, complete with CSS and all JS
22
+ code embedded into it.
23
+
24
+ The JavaScript code performs all the app functionality via the REST
25
+ interface defined by the :class:`~.Data` class.
26
+ """
27
+
28
+ def __init__(self, app, config, mount):
29
+ """
30
+ :arg app: reference to the application object.
31
+ :arg config: reference to the configuration.
32
+ :arg str mount: URL mount point."""
33
+ mainroot = 'microservice' # entry point in access URL
34
+ wpath = os.getenv('MS_STATIC_ROOT', '')
35
+ print(wpath)
36
+ if not wpath:
37
+ content = os.path.abspath(__file__).rsplit('/', 5)[0]
38
+ xlib = (__file__.find("/xlib/") >= 0 and "x") or ""
39
+ wpath = "%s/%sdata/" % (content, xlib)
40
+ if not wpath.endswith('/'):
41
+ wpath += '/'
42
+ print(self.__class__.__name__, "static content: %s" % wpath)
43
+ mdict = {"root": wpath, "rx": re.compile(r"^[a-z]+/[-a-z0-9]+\.(?:html)$")}
44
+ tdict = {"root": wpath + "templates/",
45
+ "rx": re.compile(r"^([a-zA-Z]+/)*[-a-z0-9_]+\.(?:html|tmpl)$")}
46
+ jdict = {"root": wpath + "js/",
47
+ "rx": re.compile(r"^([a-zA-Z]+/)*[-a-z0-9_]+\.(?:js)$")}
48
+ cdict = {"root": wpath + "css/",
49
+ "rx": re.compile(r"^([a-zA-Z]+/)*[-a-z0-9_]+\..*(?:css)$")}
50
+ idict = {"root": wpath + "images/",
51
+ "rx": re.compile(r"^([a-zA-Z]+/)*[-a-z0-9_]+\.(?:png|gif|jpg)$")}
52
+ roots = {mainroot: mdict, "templates": tdict,
53
+ "js": jdict, "css": cdict, "images": idict}
54
+ # location of frontpage in the root, e.g. microservice
55
+ frontpage = "%s/templates/index.html" % mainroot
56
+ RESTFrontPage.__init__(self, app, config, mount, frontpage, roots)
File without changes
WMCore/REST/Auth.py ADDED
@@ -0,0 +1,202 @@
1
+ from builtins import map, str, bytes
2
+ from future.utils import viewitems
3
+
4
+ import cherrypy
5
+ import hashlib
6
+ import hmac
7
+ import re
8
+
9
+ from Utils.Utilities import lowerCmsHeaders, encodeUnicodeToBytes
10
+ from Utils.PythonVersion import PY3
11
+
12
+ def get_user_info():
13
+ "Helper function to return user based information of the request"
14
+ return cherrypy.request.user
15
+
16
+
17
+ def user_info_from_headers(key, verbose=False):
18
+ """Read the user information HTTP request headers added by front-end.
19
+ Validates the HMAC on them to check for tampering, and if all is ok,
20
+ returns user info object with the data from the headers."""
21
+ # Set initial user information for this request
22
+ log = cherrypy.log
23
+ headers = lowerCmsHeaders(cherrypy.request.headers)
24
+ user = {'dn': None, 'method': None, 'login': None, 'name': None, 'roles': {}}
25
+
26
+ # Reject if request was not authenticated.
27
+ if 'cms-auth-status' not in headers:
28
+ if headers.get('Remote-Addr', '') == '127.0.0.1':
29
+ # since we are using localhost access we can skip authentication
30
+ log("DEBUG: non-authenticated request performed on localhost")
31
+ return
32
+ log("ERROR: authz denied, front-end headers not present")
33
+ raise cherrypy.HTTPError(403, "You are not allowed to access this resource.")
34
+
35
+ # If authentication is optional and wasn't done, accept.
36
+ if headers['cms-auth-status'] == 'NONE':
37
+ if verbose: log("DEBUG: authn optional and missing")
38
+ return
39
+
40
+ # Extract user information from the headers. Collect data required
41
+ # for HMAC validation while processing headers.
42
+ prefix = suffix = ""
43
+ hkeys = sorted(headers.keys())
44
+ for hk in hkeys:
45
+ hk = hk.lower()
46
+ if hk[0:9] in ("cms-authn", "cms-authz") and hk != "cms-authn-hmac":
47
+ prefix += "h%xv%x" % (len(hk), len(headers[hk]))
48
+ suffix += "%s%s" % (hk, headers[hk])
49
+ hkname = hk.split('-', 2)[-1]
50
+ if hk.startswith("cms-authn"):
51
+ val = headers[hk]
52
+ if hk in ("cms-authn-name", "cms-authn-dn"):
53
+ val = str(val) if PY3 else str(val, "utf-8")
54
+ user[hkname] = val
55
+ if hk.startswith("cms-authz"):
56
+ user['roles'][hkname] = {'site': set(), 'group': set()}
57
+ for r in headers[hk].split():
58
+ site_or_group, name = r.split(':')
59
+ user['roles'][hkname][site_or_group].add(name)
60
+
61
+ # Check HMAC over authn/z headers with server key. If differs, reject.
62
+ msg = prefix + "#" + suffix
63
+ if PY3:
64
+ key = encodeUnicodeToBytes(key)
65
+ msg = encodeUnicodeToBytes(msg)
66
+ cksum = hmac.new(key, msg, hashlib.sha1).hexdigest()
67
+ if cksum != headers["cms-authn-hmac"]:
68
+ log("ERROR: authz hmac mismatch, %s vs. %s" % (cksum, headers["cms-authn-hmac"]))
69
+ raise cherrypy.HTTPError(403, "You are not allowed to access this resource.")
70
+
71
+ # Authn/z is legal, accept
72
+ if verbose:
73
+ log("DEBUG: authn accepted for user %s" % user)
74
+ return user
75
+
76
+
77
+ def authz_canonical(val):
78
+ """Make a name canonical."""
79
+ return re.sub(r"[^a-z0-9]+", "-", val.lower())
80
+
81
+
82
+ def authz_match(role=None, group=None, site=None, verbose=False):
83
+ """Match user against authorisation requirements."""
84
+ role = role or []
85
+ group = group or []
86
+ site = site or []
87
+ user = get_user_info()
88
+ log = cherrypy.log
89
+
90
+ # If role, group or site are strings, convert to list first.
91
+ role = (role and isinstance(role, (str, bytes)) and [role]) or role
92
+ group = (group and isinstance(group, (str, bytes)) and [group]) or group
93
+ site = (site and isinstance(site, (str, bytes)) and [site]) or site
94
+
95
+ # Reformat all items into canonical format.
96
+ role = role and list(map(authz_canonical, role))
97
+ group = group and list(map(authz_canonical, group))
98
+ site = site and list(map(authz_canonical, site))
99
+
100
+ # If role, group and site are all empty, no authz requirements: pass
101
+ if not (role or group or site):
102
+ if verbose:
103
+ log("DEBUG: authz accepted nil requirements for user %s" % user)
104
+ return
105
+
106
+ # Otherwise determine set intersection of requirements.
107
+ for r, authz in viewitems((user and user['roles']) or {}):
108
+ if (not role) or (r in role):
109
+ if not (group or site):
110
+ if verbose:
111
+ log("DEBUG: authz accepted role '%s' for user %s" % (r, user))
112
+ return
113
+ if set(group) & authz['group']:
114
+ if verbose:
115
+ log("DEBUG: authz accepted role '%s' group %s for user %s" % (r, group, user))
116
+ return
117
+ if set(site) & authz['site']:
118
+ if verbose:
119
+ log("DEBUG: authz accepted role '%s' site %s for user %s" % (r, site, user))
120
+ return
121
+
122
+ # Deny access, requirements weren't fulfilled
123
+ log("ERROR: authz denied role %s group %s site %s for user %s" % (role, group, site, user))
124
+ raise cherrypy.HTTPError(403, "You are not allowed to access this resource.")
125
+
126
+
127
+ def authz_user(role=None, group=None, site=None, key=None, verbose=False):
128
+ """Default authorisation implementation: returns True for an authorised
129
+ user, one with any of the requested roles for the given sites or groups.
130
+
131
+ If no roles are specified, belonging to any of the requested sites or
132
+ groups is sufficient."""
133
+ role = role or []
134
+ group = group or []
135
+ site = site or []
136
+ # Get user information from request headers, then run real matcher.
137
+ assert getattr(cherrypy.request, "user", None) == None
138
+ cherrypy.request.user = user_info_from_headers(key, verbose)
139
+ authz_match(role, group, site, verbose)
140
+
141
+
142
+ _fake_warned = False
143
+
144
+
145
+ def authz_fake(role=None, group=None, site=None, verbose=False):
146
+ """Fake authorisation routine."""
147
+ role = role or []
148
+ group = group or []
149
+ site = site or []
150
+ log = cherrypy.log
151
+ global _fake_warned
152
+ if not _fake_warned:
153
+ if cherrypy.server.environment == 'production':
154
+ log("ERROR: authz faking denied in production server")
155
+ raise Exception("authz faking denied in production server")
156
+ if cherrypy.server.socket_host not in ("127.0.0.1", "::1"):
157
+ log("ERROR: authz faking denied on non-local interface")
158
+ raise Exception("authz faking denied on non-local interface")
159
+ log("WARNING: authz faking activated, only test use is permitted")
160
+ _fake_warned = True
161
+ cherrypy.request.user = {
162
+ 'method': 'fake',
163
+ 'login': 'fake_insecure_auth',
164
+ 'name': 'Fake Insecure Auth',
165
+ 'dn': '/CN=Fake Insecure Auth',
166
+ 'roles': {'fake': {'site': set(['fake']), 'group': set(['fake'])}}
167
+ }
168
+
169
+ if verbose:
170
+ log("DEBUG: authz accepted bypass role %s group %s site %s for user %s"
171
+ % (role, group, site, cherrypy.request.user))
172
+
173
+
174
+ class RESTAuth(cherrypy.Tool):
175
+ """Restrict access based on CMSWEB authn/z information."""
176
+ _key = None
177
+
178
+ def __init__(self):
179
+ cherrypy.Tool.__init__(self, 'before_request_body', authz_user, priority=60)
180
+
181
+ def _setup(self):
182
+ """Hook this tool into cherrypy request."""
183
+ log = cherrypy.log
184
+ hooks = cherrypy.request.hooks
185
+ conf = self._merged_args()
186
+
187
+ # Install authz policy. Load front-end hmac key on first use.
188
+ prio = conf.pop("priority", self._priority)
189
+ policy = conf.pop("policy", "user")
190
+ if policy == "user":
191
+ key_file = conf.pop("key_file")
192
+ if not self._key:
193
+ with open(key_file, "rb") as fd:
194
+ self._key = fd.read()
195
+ conf["key"] = self._key
196
+
197
+ hooks.attach(self._point, self.callable, priority=prio, **conf)
198
+ elif policy == "dangerously_insecure":
199
+ conf.pop("key_file", None)
200
+ hooks.attach(self._point, authz_fake, priority=prio, **conf)
201
+ else:
202
+ raise Exception('unknown authz policy "%s"' % policy)