-
Notifications
You must be signed in to change notification settings - Fork 22
/
zendoc_zenpack
executable file
·314 lines (254 loc) · 9.21 KB
/
zendoc_zenpack
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/usr/bin/env python
__doc__ = """zendoc_zenpack
Create an XML file showing the items in the ZenPack.
"""
import os
import os.path
import datetime
import zope.component
from optparse import OptionParser
from Products.ZCatalog.ZCatalog import ZCatalog
from Products.ZenUtils.ZenScriptBase import ZenScriptBase
from Products.ZenUtils.Utils import importClass, zenPath
from Products.ZenRelations.RelationshipBase import RelationshipBase
from Products.ZenModel.interfaces import IZenDocProvider
from Products.ZenModel.DataPointGraphPoint import DataPointGraphPoint
from Products.ZenModel.RRDDataSource import RRDDataSource
from Products.ZenModel.RRDDataPoint import RRDDataPoint
from Products.ZenModel.RRDTemplate import RRDTemplate
from Products.ZenModel.RRDGraph import RRDGraph
from Products.ZenModel.GraphDefinition import GraphDefinition
from transaction import commit
class XMLContainer:
id = ''
description = ''
path = ''
meta_type = ''
def __init__(self, id='', meta_type=''):
self.id = id
self.meta_type = meta_type
def getPrimaryPath(self):
return self.path
threshie = XMLContainer('threshold', 'ThresholdContainer')
plugin_container = XMLContainer('modeler_plugin_container',
'ModelerPluginContainer')
class ModelerPlugin:
id = ''
description = ''
path = ''
meta_type = 'ModelerPlugin'
def getPrimaryPath(self):
return self.path.split('/')
def print_cdata( content, indent=0 ):
print " " * indent + """<![CDATA[%s]]>""" % content
def print_xml_tree(tree, indent=0):
if '__id' in tree:
header = " " * indent + """<%(__meta_type)s id="%(__id)s" location="%(__location)s" """ % tree
if '__class' in tree and tree['__class']:
header += 'class="%s"' % tree['__class']
if '__hasTransform' in tree:
header += ' hasTransform="%s"' % tree['__hasTransform']
print header + " >"
desc = tree['__description']
if desc:
print_cdata( desc, indent )
for obj in sorted(tree.keys()):
if obj.startswith('__'): continue
print_xml_tree(tree[obj], indent + 1 )
if '__id' in tree:
print " " * indent + "</%(__meta_type)s>" % tree
def add_object(root, obj):
zendocObj = zope.component.queryAdapter(obj, IZenDocProvider)
if zendocObj is None: return
root['__id'] = obj.id
root['__description'] = zendocObj.getZendoc()
root['__location'] = '/'.join(obj.getPrimaryPath())
root['__meta_type'] = obj.meta_type.replace(' ', '_')
root['__class'] = obj.__class__.__name__
if obj.__class__.__name__ == 'EventClass':
if obj.transform:
root['__hasTransform'] = 'yes'
else:
root['__hasTransform'] = 'no'
def get_modeler_description(path, file):
location = path.replace(zenPath(), '')
# Start from the ZenPack location
location = location.split('/')[3:]
name = file.replace('.py', '')
location.append(name)
location = '.'.join(location)
# Location will be something like
# ZenPacks.zenoss.AixMonitor.modeler.plugins.zenoss.cmd.aix.netstat_na
try:
mod = __import__(location, globals(), locals(), name)
desc = mod.__doc__
except:
desc = 'Unable to load plugin %s' % location
return desc
def add_plugin(root, file, path):
plugin = ModelerPlugin()
plugin.id = file.replace('.py', '')
plugin.path = path
plugin.description = get_modeler_description(path, file)
add_object(root, plugin)
def modelerSearch(root, plugin_dir):
if not os.path.exists(plugin_dir):
return
# Yes, you're right -- the following should be equivalent
# root = root['']['zport']['dmd']
# But it's not. Move along.
for loc in root: # Dereference ''
root = root[loc]
for loc in root: # Dereference 'zport'
root = root[loc]
for loc in root: # Dereference 'dmd'
root = root[loc]
# Back to sanity. Yay!
madeOrganizer = False
for path, unused, files in os.walk(plugin_dir):
for file in files:
if not file.endswith('.py') or file == '__init__.py':
continue
if not madeOrganizer:
root['Modelers'] = {}
new_root = root['Modelers']
add_object(new_root, plugin_container)
madeOrganizer = True
new_root[file] = {}
add_plugin(new_root[file], file, path)
def describeDevClass(obj, tree):
root = tree
obj_path = obj.getPrimaryPath()
for i, loc in enumerate(obj_path):
if loc not in root:
root[loc] = {}
# Graphs don't have their own node
if i > 0 and obj_path[i-1] == 'graphDefs':
graph_path = '/'.join(obj_path[:i+1])
graph_obj = dmd.getObjByPath(graph_path)
add_object(root[loc], graph_obj)
# Thresholds don't have a container
if loc == 'thresholds':
add_object(root[loc], threshie)
root = root[loc]
add_object(root, obj)
def getDefaultModelers(dmdObj):
defaultDirs = [
zenPath('Products', 'DataCollector', 'plugins', 'zenoss'),
]
tree = { '':{'zport':{'dmd':{}}}}
for dir in defaultDirs:
modelerSearch(tree, dir)
print_xml_tree(tree)
_FILTER_CLASSES = (RelationshipBase,ZCatalog)
def _filter(object):
if getattr( object, 'pack', False ) and object.pack() is not None:
return False
for clazz in _FILTER_CLASSES:
if isinstance(object, clazz):
return False
return True
def processDevClass(dmdObj):
tree = {}
describeDevClass(dmdObj, tree)
for template in dmdObj.rrdTemplates.getSubObjects( _filter ):
describeDevClass(template, tree)
print_xml_tree(tree)
# for obj in dmdObj.objectValues():
# if obj.meta_type == 'DeviceClass':
# processDevClass(obj)
def zenpack_header( id, version, author, dependencies ):
print "<zenpack id='%s' version='%s' author='%s' dependencies='%s' >" % (
id, version, author, dependencies)
def zenpack_trailer():
print "</zenpack>"
def zenpack2XML(dmd, zp):
dependencies = ', '.join( [' '.join([x,y]) for x, y in sorted(zp.dependencies.items()) ] )
zenpack_header( zp.id, zp.version, zp.author, dependencies )
zendocObj = zope.component.queryAdapter(zp, IZenDocProvider)
if zendocObj:
zenpackZendoc = zendocObj.getZendoc()
if zenpackZendoc:
print_cdata( zenpackZendoc )
# Since the packables aren't arranged hierarchically,
# we need to build our own tree.
tree = {}
for obj in zp.packables():
root = tree
obj_path = obj.getPrimaryPath()
for i, loc in enumerate(obj_path):
if loc not in root:
root[loc] = {}
# Graphs don't have their own node
if i > 0 and obj_path[i-1] == 'graphDefs':
graph_path = '/'.join(obj_path[:i+1])
graph_obj = dmd.getObjByPath(graph_path)
add_object(root[loc], graph_obj)
# Thresholds don't have a container
if loc == 'thresholds':
add_object(root[loc], threshie)
root = root[loc]
add_object(root, obj)
modelerPath = zp.path('modeler', 'plugins')
modelerSearch(tree, modelerPath)
# Print out the tree
print_xml_tree(tree)
zenpack_trailer()
def xml_header():
print """<?xml version="1.0" encoding="UTF-8"?>
"""
def zenbase_header( export_date ):
print """
<!-- Base Zenoss information generated on %s -->
<zenbase >
""" % (export_date)
def zenbase_trailer():
print """
</zenbase>
"""
def zenpacks_header( export_date ):
print """
<!-- ZenPack information generated on %s -->
<zenpacks >
""" % (export_date)
def zenpacks_trailer():
print """
</zenpacks>
"""
class ZendocScript( ZenScriptBase ):
def buildOptions(self):
ZenScriptBase.buildOptions(self)
self.parser.add_option( "-z", "--zenpacks", dest="zenpacks",
help="Comma-separated list of ZenPacks to be documented (can include 'Core')" )
if __name__ == '__main__':
script = ZendocScript(connect=True)
dmd = script.dmd
zenpackOption = getattr( script.options,'zenpacks', None )
if zenpackOption:
zenpack_list = zenpackOption.split(',')
else:
zenpack_list = []
export_date = datetime.datetime.now()
zenpacks_header( export_date )
def doCore(dmd):
zenpack_header('Core','Zenoss','None','None')
getDefaultModelers(dmd.Devices)
processDevClass(dmd.Devices)
zenpack_trailer()
def doZenPack(dmd,zp):
zenpack2XML(dmd,zp)
if not zenpack_list:
doCore(dmd)
for zp in dmd.ZenPackManager.packs():
zenpack2XML(dmd, zp)
else:
if 'Core' in zenpack_list:
doCore(dmd)
for zenpack in ( zenpackId for zenpackId in zenpack_list if zenpackId != 'Core' ):
try:
zenpackOb = dmd.ZenPackManager.packs._getOb( zenpack )
except Exception, e:
print "Did not find zenpack %s" % zenpack
raise
zenpack2XML( dmd, zenpackOb )
zenpacks_trailer()