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,438 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: ISO-8859-1 -*-
3
+ # pylint: disable=E1101,C0103,R0902,E0602
4
+ # E0602: sneakily importing a lot of stuff, turn off for false positives
5
+
6
+ """
7
+ Couch DB command line admin tool
8
+ """
9
+ from __future__ import print_function
10
+ from future import standard_library
11
+ standard_library.install_aliases()
12
+
13
+ import urllib.parse
14
+
15
+ __license__ = "GPL"
16
+ __maintainer__ = "Valentin Kuznetsov"
17
+ __email__ = "vkuznet@gmail.com"
18
+ __status__ = "Alpha"
19
+
20
+ # system modules
21
+ import os
22
+ import sys
23
+ import inspect
24
+ import traceback
25
+
26
+ # ipython modules
27
+ from IPython import Release
28
+ import IPython.ipapi
29
+ import __main__
30
+
31
+
32
+ class PrintManager:
33
+ def __init__(self):
34
+ from IPython import ColorANSI
35
+ self.term = ColorANSI.TermColors
36
+
37
+ def print_red(self, msg):
38
+ """print message using red color"""
39
+ print(self.msg_red(msg))
40
+
41
+ def print_green(self, msg):
42
+ """print message using blue color"""
43
+ print(self.msg_green(msg))
44
+
45
+ def print_blue(self, msg):
46
+ """print message using blue color"""
47
+ print(self.msg_blue(msg))
48
+
49
+ def msg_red(self, msg):
50
+ """yield message using red color"""
51
+ if not msg:
52
+ msg = ''
53
+ return self.term.Red + msg + self.term.Black
54
+
55
+ def msg_green(self, msg):
56
+ """yield message using green color"""
57
+ if not msg:
58
+ msg = ''
59
+ return self.term.Green + msg + self.term.Black
60
+
61
+ def msg_blue(self, msg):
62
+ """yield message using blue color"""
63
+ if not msg:
64
+ msg = ''
65
+ return self.term.Blue + msg + self.term.Black
66
+
67
+
68
+ def load_config(func_list=[]):
69
+ """
70
+ Defines default configuration for Couch DB. We need the following:
71
+ URI - the Couch DB URI
72
+ DB - the Couch DB name
73
+ DESIGN - the Couch DB design name
74
+ DEBUG - debug level, used to setup HTTPConnection debug level
75
+ """
76
+ msg = """
77
+ import os, re, sys, time, types, traceback, inspect
78
+ import urllib, urllib2, httplib
79
+ import json
80
+ from json import JSONDecoder, JSONEncoder
81
+ try:
82
+ from path import path
83
+ except ImportError:
84
+ pass
85
+ try:
86
+ from ipipe import *
87
+ except ImportError:
88
+ pass
89
+
90
+ # global variables
91
+ URI="http://localhost:5984"
92
+ DB="das"
93
+ DESIGN="dasadmin"
94
+ DEBUG=0
95
+ """
96
+ msg += "\n%s\n" % inspect.getsource(PrintManager)
97
+ msg += "PM = PrintManager()"
98
+ for func in func_list:
99
+ msg += "\n%s\n" % inspect.getsource(func)
100
+ return msg
101
+
102
+
103
+ def httplib_request(host, path, params, request='POST', debug=0):
104
+ """request method using provided HTTP request and httplib library"""
105
+ if debug:
106
+ httplib.HTTPConnection.debuglevel = 1
107
+ if not isinstance(params, str):
108
+ params = urllib.parse.urlencode(params, doseq=True)
109
+ if debug:
110
+ print("input parameters", params)
111
+ headers = {"Content-type": "application/x-www-form-urlencoded",
112
+ "Accept": "text/plain"}
113
+ if host.find('https://') != -1:
114
+ host = host.replace('https://', '')
115
+ conn = httplib.HTTPSConnection(host)
116
+ else:
117
+ host = host.replace('http://', '')
118
+ conn = httplib.HTTPConnection(host)
119
+ if request == 'GET':
120
+ conn.request(request, path)
121
+ else:
122
+ conn.request(request, path, params, headers)
123
+ response = conn.getresponse()
124
+
125
+ if response.reason != "OK":
126
+ print(response.status, response.reason, response.read())
127
+ res = None
128
+ else:
129
+ res = response.read()
130
+ conn.close()
131
+ return res
132
+
133
+
134
+ def print_data(data, lookup="value"):
135
+ """
136
+ Provides pretty print of json data based on lookup parameter
137
+ by default lookup=value. See couch db response for more info.
138
+ """
139
+ jsondict = json.loads(data)
140
+ PM.print_blue("Total %s documents" % len(jsondict['rows']))
141
+ maxl = 0
142
+ padding = ""
143
+ for row in jsondict['rows']:
144
+ values = row[lookup]
145
+ if isinstance(values, dict):
146
+ if not padding:
147
+ for key in values.keys():
148
+ if len(key) > maxl:
149
+ maxl = len(key)
150
+ for key, val in values.items():
151
+ padding = " " * (maxl - len(key))
152
+ print("%s%s: %s" % (padding, PM.msg_blue(key), val))
153
+ print()
154
+ else:
155
+ print(values)
156
+
157
+
158
+ def set_prompt(in1):
159
+ """Define shell prompt"""
160
+ if in1.find('|\#>') != -1:
161
+ in1 = in1.replace('|\#>', '').strip()
162
+ ip = __main__.__dict__['__IP']
163
+ prompt = getattr(ip.outputcache, 'prompt1')
164
+ prompt.p_template = in1 + " |\#> "
165
+ prompt.set_p_str()
166
+
167
+
168
+ def couch_help(self, arg):
169
+ """
170
+ Provide simple help about available commands
171
+ """
172
+ pmgr = PrintManager()
173
+ global magic_list
174
+ msg = "\nAvailable commands:\n"
175
+ for name, func in magic_list:
176
+ msg += "%s\n%s\n" % (pmgr.msg_blue(name), pmgr.msg_green(func.__doc__))
177
+ msg += "List of pre-defined variables to control your interactions "
178
+ msg += "with CouchDB:\n"
179
+ msg += pmgr.msg_green(" URI, DB, DESIGN, DEBUG\n")
180
+ print(msg)
181
+
182
+
183
+ ### MAGIC COMMANDS ###
184
+ def db_info():
185
+ """
186
+ Provide information about Couch DB. Use DB parameter to setup
187
+ your couch DB name.
188
+ """
189
+ host = URI
190
+ path = '/%s' % DB
191
+ data = httplib_request(host, path, {}, 'GET', DEBUG)
192
+ if not data:
193
+ return data
194
+ return json.loads(data)
195
+
196
+
197
+ def couch_views():
198
+ """
199
+ List registered views in couch db.
200
+ """
201
+ qqq = 'startkey=%22_design%2F%22&endkey=%22_design0%22'
202
+ host = URI
203
+ path = '/%s/_all_docs?%s' % (DB, qqq)
204
+ results = httplib_request(host, path, {}, 'GET', DEBUG)
205
+ designdocs = json.loads(results)
206
+ results = {}
207
+ for item in designdocs['rows']:
208
+ doc = item['key']
209
+ print(PM.msg_blue("design: ") + doc)
210
+ path = '/%s/%s' % (DB, doc)
211
+ res = httplib_request(host, path, {}, 'GET', DEBUG)
212
+ rdict = json.loads(res)
213
+ for view_name, view_dict in rdict['views'].items():
214
+ print(PM.msg_blue("view name: ") + view_name)
215
+ print(PM.msg_blue("map:"))
216
+ print(PM.msg_green(view_dict['map']))
217
+ if 'reduce' in view_dict:
218
+ print(PM.msg_blue("reduce:"))
219
+ print(PM.msg_green(view_dict['reduce']))
220
+
221
+
222
+ def create_view(view_dict):
223
+ """
224
+ Create couch db view. The db and design names are controlled via
225
+ DB and DESIGN shell parameters, respectively.
226
+ Parameters: <view_dict>
227
+ Example of the view:
228
+ {"view_name": {"map" : "function(doc) { if(doc.hash) {emit(1, doc.hash);}}" }}
229
+ """
230
+ # get existing views
231
+ host = URI
232
+ path = '/%s/_design/%s' % (DB, DESIGN)
233
+ data = httplib_request(host, path, {}, 'GET', DEBUG)
234
+ jsondict = json.loads(data)
235
+ for view_name, view_def in view_dict.items():
236
+ jsondict['views'][view_name] = view_def
237
+
238
+ # update views
239
+ encoder = JSONEncoder()
240
+ params = encoder.encode(jsondict)
241
+ request = 'PUT'
242
+ debug = DEBUG
243
+ data = httplib_request(host, path, params, request, debug)
244
+ if not data:
245
+ return data
246
+ return json.loads(data)
247
+
248
+
249
+ def delete_view(view_name):
250
+ """
251
+ Delete couch db view. The db and design names are controlled via
252
+ DB and DESIGN shell parameters, respectively.
253
+ Parameters: <view_name>
254
+ """
255
+ # get existing views
256
+ host = URI
257
+ path = '/%s/_design/%s' % (DB, DESIGN)
258
+ data = httplib_request(host, path, {}, 'GET', DEBUG)
259
+ if not data:
260
+ return data
261
+ jsondict = json.loads(data)
262
+
263
+ # delete requested view in view dict document
264
+ try:
265
+ del jsondict['views'][view_name]
266
+ # update view dict document in a couch
267
+ encoder = JSONEncoder()
268
+ params = encoder.encode(jsondict)
269
+ request = 'PUT'
270
+ debug = DEBUG
271
+ data = httplib_request(host, path, params, request, debug)
272
+ except:
273
+ traceback.print_exc()
274
+
275
+
276
+ def delete_all_views(design):
277
+ """
278
+ Delete all views in particular design document.
279
+ The db and design names are controlled via
280
+ DB and DESIGN shell parameters, respectively.
281
+ Parameters: <design_name, e.g. dasadmin>
282
+ """
283
+ host = URI
284
+ path = '/%s/_design/%s' % (DB, design)
285
+ data = httplib_request(host, path, {}, 'DELETE', DEBUG)
286
+ if not data:
287
+ return data
288
+ return json.loads(data)
289
+
290
+
291
+ def create_db(db_name):
292
+ """
293
+ Create a new DB in couch.
294
+ Parameters: <db_name>
295
+ """
296
+ host = URI
297
+ path = '/%s' % db_name
298
+ data = httplib_request(host, path, {}, 'PUT', DEBUG)
299
+ if not data:
300
+ return data
301
+ return json.loads(data)
302
+
303
+
304
+ def delete_db(db_name):
305
+ """
306
+ Delete DB in couch.
307
+ Parameters: <db_name>
308
+ """
309
+ host = URI
310
+ path = '/%s' % db_name
311
+ data = httplib_request(host, path, {}, 'DELETE', DEBUG)
312
+ if not data:
313
+ return data
314
+ return json.loads(data)
315
+
316
+
317
+ def get_all_docs(idx=0, limit=0, pretty_print=False):
318
+ """
319
+ Retrieve all documents from CouchDB.
320
+ Parameters: <idx=0> <limit=0> <pretty_print=False>
321
+ """
322
+ host = URI
323
+ path = '/%s/_all_docs' % DB
324
+ kwds = {}
325
+ if idx:
326
+ kwds['skip'] = idx
327
+ if limit:
328
+ kwds['limit'] = limit
329
+ data = httplib_request(host, path, kwds, 'GET', DEBUG)
330
+ if not data:
331
+ return data
332
+ if pretty_print:
333
+ print_data(data, lookup='id')
334
+ else:
335
+ return json.loads(data)
336
+
337
+
338
+ def get_doc(id):
339
+ """
340
+ Retrieve document with given id from CouchDB.
341
+ Parameters: <id, e.g. 1323764f7a6af1b37b72119920cbaa08>
342
+ """
343
+ host = URI
344
+ path = '/%s/%s' % (DB, id)
345
+ kwds = {}
346
+ data = httplib_request(host, path, kwds, 'GET', DEBUG)
347
+ if not data:
348
+ return data
349
+ return json.loads(data)
350
+
351
+
352
+ def load_module(arg):
353
+ """
354
+ Load custom admin module. Name it as <module>_ipython.py and place in
355
+ your PYTHONPATH. Implement a <module>_load() function to load your stuff.
356
+ Parameters: <module>
357
+
358
+ Example:
359
+ def mycmd():
360
+ pass # do something here
361
+ def mymodule_load():
362
+ ip = IPython.ipapi.get()
363
+ ip.expose_magic('mycmd', mycmd)
364
+ """
365
+ # try to load custom modules
366
+ stm = "from %s_ipython import %s_load\n" % (arg, arg)
367
+ stm += "%s_load()" % arg
368
+ obj = compile(str(stm), '<string>', 'exec')
369
+ try:
370
+ eval(obj)
371
+ msg = "Loaded %s module. " % arg
372
+ msg += "Use " + PM.msg_blue("%s_help" % arg) + \
373
+ " for concrete module help if it's implemented"
374
+ print(msg)
375
+ except:
376
+ traceback.print_exc()
377
+ pass
378
+
379
+
380
+ # keep magic list as global since it's used in couch_help
381
+ magic_list = [
382
+ ('db_info', db_info),
383
+ ('couch_views', couch_views),
384
+ ('create_view', create_view),
385
+ ('delete_view', delete_view),
386
+ ('delete_all_views', delete_all_views),
387
+ ('get_all_docs', get_all_docs),
388
+ ('get_doc', get_doc),
389
+ ('create_db', create_db),
390
+ ('delete_db', delete_db),
391
+ ('load_module', load_module),
392
+ ]
393
+
394
+
395
+ def main():
396
+ """
397
+ Main function which defint ipython behavior
398
+ """
399
+ pmgr = PrintManager()
400
+
401
+ # global IP API
402
+ ip = IPython.ipapi.get()
403
+
404
+ o = ip.options
405
+ ip.expose_magic('couch_help', couch_help)
406
+ # load commands and expose them to the shell
407
+ for m in magic_list:
408
+ ip.ex(inspect.getsource(m[1]))
409
+
410
+ # load configuration for couch-sh, supply a names of functions to
411
+ # be loaded
412
+ ip.ex(load_config([httplib_request, print_data]))
413
+
414
+ # autocall to "full" mode (smart mode is default, I like full mode)
415
+ o.autocall = 2
416
+
417
+ # Set dbsh prompt
418
+ o.prompt_in1 = 'couch-sh |\#> '
419
+ o.prompt_in2 = 'couch-sh> '
420
+ o.system_verbose = 0
421
+
422
+ # define couch-sh banner
423
+ pyver = sys.version.split('\n')[0]
424
+ ipyver = Release.version
425
+ msg = "Welcome to couch-sh \n[python %s, ipython %s]\n%s\n" \
426
+ % (pyver, ipyver, os.uname()[3])
427
+ msg += "For couch-sh help use "
428
+ msg += pmgr.msg_blue("couch_help")
429
+ msg += ", for python help use help commands\n"
430
+ o.banner = msg
431
+ o.prompts_pad_left = "1"
432
+ # Remove all blank lines in between prompts, like a normal shell.
433
+ o.separate_in = "0"
434
+ o.separate_out = "0"
435
+ o.separate_out2 = "0"
436
+
437
+
438
+ main()
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+ """
4
+ CouchObject.py
5
+
6
+ Created by Dave Evans on 2010-07-14.
7
+ Copyright (c) 2010 Fermilab. All rights reserved.
8
+ """
9
+ from __future__ import print_function
10
+
11
+ from builtins import str
12
+ import json as jsonlib
13
+
14
+ import WMCore.Database.CMSCouch as CMSCouch
15
+ import WMCore.GroupUser.Decorators as Decorators
16
+
17
+
18
+ class CouchConnectionError(Exception):
19
+ """docstring for CouchConnectionError"""
20
+
21
+ def __init__(self, arg):
22
+ super(CouchConnectionError, self).__init__()
23
+ self.arg = arg
24
+
25
+
26
+ class CouchObject(dict):
27
+ """
28
+ Base class for dictionary derived couch documents for this package.
29
+ (May even be generally useful...)
30
+
31
+ Essentially a specialised dict class that has attributes needed to talk to Couch
32
+ via the CMSCouch API.
33
+
34
+ This class is expected to be overridden and the derived class must override the document_id
35
+ property to generate the document id from the data within the dictionary.
36
+ This class assumes some simple mapping is used to generate the document ID as a property, rather
37
+ on doing anything too fancy
38
+ """
39
+
40
+ def __init__(self):
41
+ dict.__init__(self)
42
+ self.couch = None
43
+ self.cdb_server = None
44
+ self.cdb_database = None
45
+ self.cdb_url = None
46
+ self.cdb_document_id = None
47
+ self.cdb_document_data = "CouchObject"
48
+
49
+ connected = property(lambda x: x.couch is not None)
50
+ json = property(lambda x: jsonlib.dumps(dict(x)))
51
+ # doc_id default returns None, which signals use couch-generated doc id
52
+ document_id = property(lambda x: None)
53
+
54
+ def setCouch(self, url, database):
55
+ """
56
+ _setCouch_
57
+
58
+ Set the contant info for the couch database
59
+ """
60
+ self.cdb_url = url
61
+ self.cdb_database = database
62
+
63
+ def connect(self):
64
+ """
65
+ _connect_
66
+
67
+ Initialise the couch database connection for this object.
68
+ This gets called automagically by the requireConnected decorator
69
+ """
70
+ if self.connected:
71
+ return
72
+ if self.cdb_url is None:
73
+ msg = "url for couch service not provided"
74
+ raise CouchConnectionError(msg)
75
+ if self.cdb_database is None:
76
+ msg = "database name for couch service not provided"
77
+ raise CouchConnectionError(msg)
78
+ try:
79
+ self.cdb_server = CMSCouch.CouchServer(self.cdb_url)
80
+ self.couch = self.cdb_server.connectDatabase(self.cdb_database)
81
+ except Exception as ex:
82
+ msg = "Exception instantiating couch services for :\n"
83
+ msg += " url = %s\n database = %s\n" % (self.cdb_url, self.cdb_database)
84
+ msg += " Exception: %s" % str(ex)
85
+ print(msg)
86
+ raise CouchConnectionError(msg)
87
+
88
+ @Decorators.requireConnection
89
+ def create(self):
90
+ """
91
+ _create_
92
+
93
+ Create the couch document for this object.
94
+ """
95
+ if not self.couch.documentExists(self.document_id):
96
+ couchDoc = CMSCouch.Document(self.document_id, {self.cdb_document_data: dict(self)})
97
+ self.couch.commitOne(couchDoc)
98
+
99
+ @Decorators.requireConnection
100
+ def get(self):
101
+ """
102
+ _get_
103
+
104
+ given the doc_id generated from the derived class, get the document and update
105
+ the data in the dictionary from it
106
+
107
+ """
108
+ if not self.couch.documentExists(self.document_id):
109
+ raise RuntimeError("Document: %s not found" % self.document_id)
110
+
111
+ doc = self.couch.document(self.document_id)
112
+ data = doc.get(self.cdb_document_data, {})
113
+ dict.update(self, data)
114
+ return
115
+
116
+ @Decorators.requireConnection
117
+ def drop(self):
118
+ """
119
+ _drop_
120
+
121
+ remove the doc representing this object, possibly with a chained wipeout
122
+ of all other docs referencing it by owner or group or whatever, if thats
123
+ needed, override in the classes derived from this
124
+ """
125
+ if not self.couch.documentExists(self.document_id):
126
+ raise RuntimeError("Document: %s not found" % self.document_id)
127
+ self.couch.delete_doc(self.document_id)
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+ """
4
+ Decorators.py
5
+
6
+ Decorator Utils for GroupUser modules
7
+
8
+ Created by Dave Evans on 2010-07-20.
9
+ Copyright (c) 2010 Fermilab. All rights reserved.
10
+ """
11
+
12
+ def requireConnection(funcRef):
13
+ """
14
+ _requireConnection_
15
+
16
+ Decorator method to connect the function's class object to couch
17
+ """
18
+ def wrapper(self, *args, **opts):
19
+ if not self.connected:
20
+ self.connect()
21
+ return funcRef(self, *args, **opts)
22
+ return wrapper
23
+
24
+ def requireGroup(funcRef):
25
+ """
26
+ _requireGroup_
27
+
28
+ Decorator method to enforce setting a group attribute
29
+
30
+ """
31
+ def wrapper(self, *args, **opts):
32
+ if getattr(self, "group", None) == None:
33
+ msg = "Group Attribute not present/set"
34
+ raise RuntimeError(msg)
35
+ return funcRef(self, *args, **opts)
36
+ return wrapper
37
+
38
+
39
+ def requireUser(funcRef):
40
+ """
41
+ _requireUser_
42
+
43
+ Decorator method to enforce setting a user attribute for another
44
+ object
45
+ """
46
+ def wrapper(self, *args, **opts):
47
+ if getattr(self, "owner", None) == None:
48
+ msg = "Group Attribute not present/set"
49
+ raise RuntimeError(msg)
50
+ return funcRef(self, *args, **opts)
51
+ return wrapper
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+ """
4
+ Group.py
5
+
6
+ Created by Dave Evans on 2010-07-14.
7
+ Copyright (c) 2010 Fermilab. All rights reserved.
8
+ """
9
+
10
+
11
+
12
+ import json
13
+
14
+ from WMCore.GroupUser.CouchObject import CouchObject
15
+
16
+
17
+ class Group(CouchObject):
18
+ """
19
+ _Group_
20
+
21
+ Dictionary object containing attributes of a group
22
+
23
+ """
24
+ def __init__(self, **options):
25
+ CouchObject.__init__(self)
26
+ self.cdb_document_data = "group"
27
+ self.setdefault('name', None)
28
+ self.setdefault('administrators', [])
29
+ self.setdefault('associated_sites', {})
30
+ self.update(options)
31
+
32
+ document_id = property(lambda x : "group-%s" % x['name'] )
33
+ name = property(lambda x: x['name'])