-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathzenpacklib.py
More file actions
3382 lines (2646 loc) · 109 KB
/
zenpacklib.py
File metadata and controls
3382 lines (2646 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
#
# Copyright (C) Zenoss, Inc. 2013-2014, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
##############################################################################
"""zenpacklib - ZenPack API abstraction.
This module provides a single integration point for common ZenPacks.
"""
import logging
LOG = logging.getLogger('zen.zenpacklib')
# Suppresses "No handlers could be found for logger" errors if logging
# hasn't been configured.
LOG.addHandler(logging.NullHandler())
import collections
import imp
import importlib
import json
import operator
import os
import re
import sys
import math
from zope.browser.interfaces import IBrowserView
from zope.component import adapts, getGlobalSiteManager
from zope.event import notify
from zope.interface import classImplements, implements
from zope.interface.interface import InterfaceClass
from Products.AdvancedQuery import Eq, Or
from Products.AdvancedQuery.AdvancedQuery import _BaseQuery as BaseQuery
from Products.Five import zcml
from Products.ZenModel.Device import Device as BaseDevice
from Products.ZenModel.DeviceComponent import DeviceComponent as BaseDeviceComponent
from Products.ZenModel.HWComponent import HWComponent as BaseHWComponent
from Products.ZenModel.ManagedEntity import ManagedEntity as BaseManagedEntity
from Products.ZenModel.ZenossSecurity import ZEN_CHANGE_DEVICE
from Products.ZenModel.ZenPack import ZenPack as ZenPackBase
from Products.ZenRelations.RelSchema import ToMany, ToManyCont, ToOne
from Products.ZenRelations.ToManyContRelationship import ToManyContRelationship
from Products.ZenRelations.ToManyRelationship import ToManyRelationship
from Products.ZenRelations.ToOneRelationship import ToOneRelationship
from Products.ZenRelations.zPropertyCategory import setzPropertyCategory
from Products.ZenUI3.browser.interfaces import IMainSnippetManager
from Products.ZenUI3.utils.javascript import JavaScriptSnippet
from Products.ZenUtils.guid.interfaces import IGlobalIdentifier
from Products.ZenUtils.Search import makeFieldIndex, makeKeywordIndex
from Products.ZenUtils.Utils import monkeypatch, importClass
from Products import Zuul
from Products.Zuul.catalog.events import IndexingEvent
from Products.Zuul.catalog.global_catalog import ComponentWrapper as BaseComponentWrapper
from Products.Zuul.catalog.global_catalog import DeviceWrapper as BaseDeviceWrapper
from Products.Zuul.catalog.interfaces import IIndexableWrapper, IPathReporter
from Products.Zuul.catalog.paths import DefaultPathReporter, relPath
from Products.Zuul.decorators import info, memoize
from Products.Zuul.form import schema
from Products.Zuul.form.interfaces import IFormBuilder
from Products.Zuul.infos import InfoBase, ProxyProperty
from Products.Zuul.infos.component import ComponentInfo as BaseComponentInfo
from Products.Zuul.infos.component import ComponentFormBuilder as BaseComponentFormBuilder
from Products.Zuul.infos.device import DeviceInfo as BaseDeviceInfo
from Products.Zuul.interfaces import IInfo
from Products.Zuul.interfaces.component import IComponentInfo as IBaseComponentInfo
from Products.Zuul.interfaces.device import IDeviceInfo as IBaseDeviceInfo
from Products.Zuul.routers.device import DeviceRouter
from Products.Zuul.utils import ZuulMessageFactory as _t
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.viewlet.interfaces import IViewlet
# Exported symbols. These are the only symbols imported by wildcard.
__all__ = (
# Classes
'Device',
'Component',
'HardwareComponent',
'TestCase',
'ZenPackSpec',
# Functions.
'enableTesting',
'ucfirst',
'relname_from_classname',
'relationships_from_yuml',
'catalog_search',
)
# Must defer definition of TestCase. Otherwise it imports
# BaseTestCase which puts Zope into testing mode.
TestCase = None
# Required for registering ZCSA adapters.
GSM = getGlobalSiteManager()
# Public Classes ############################################################
class ZenPack(ZenPackBase):
"""
ZenPack loader that handles custom installation and removal tasks.
"""
# NEW_COMPONENT_TYPES AND NEW_RELATIONS will be monkeypatched in
# via zenpacklib when this class is instantiated.
def _buildDeviceRelations(self):
for d in self.dmd.Devices.getSubDevicesGen():
d.buildRelations()
def install(self, app):
for dcname, dcspec in self.device_classes.iteritems():
if dcspec.create:
try:
self.dmd.Devices.getOrganizer(dcspec.path)
except KeyError:
LOG.info('Creating DeviceClass %s' % dcspec.path)
app.dmd.Devices.createOrganizer(dcspec.path)
dcObject = self.dmd.Devices.getOrganizer(dcspec.path)
for zprop, value in dcspec.zProperties.iteritems():
LOG.info('Setting zProperty %s on %s' % (zprop, dcspec.path))
dcObject.setZenProperty(zprop, value)
# Load objects.xml now
super(ZenPack, self).install(app)
if self.NEW_COMPONENT_TYPES:
LOG.info('Adding %s relationships to existing devices' % self.id)
self._buildDeviceRelations()
def remove(self, app, leaveObjects=False):
from Products.Zuul.interfaces import ICatalogTool
if not leaveObjects:
dc = app.Devices
for catalog in self.GLOBAL_CATALOGS:
catObj = getattr(dc, catalog, None)
if catObj:
LOG.info('Removing Catalog %s' % catalog)
dc._delObject(catalog)
if self.NEW_COMPONENT_TYPES:
LOG.info('Removing %s components' % self.id)
cat = ICatalogTool(app.zport.dmd)
for brain in cat.search(types=self.NEW_COMPONENT_TYPES):
component = brain.getObject()
component.getPrimaryParent()._delObject(component.id)
# Remove our Device relations additions.
from Products.ZenUtils.Utils import importClass
for device_module_id in self.NEW_RELATIONS:
Device = importClass(device_module_id)
Device._relations = tuple([x for x in Device._relations
if x[0] not in self.NEW_RELATIONS[device_module_id]])
LOG.info('Removing %s relationships from existing devices.' % self.id)
self._buildDeviceRelations()
for dcname, dcspec in self.device_classes.iteritems():
if dcspec.remove:
LOG.info('Removing DeviceClass %s' % dcspec.path)
app.dmd.Devices.manage_deleteOrganizer(dcspec.path)
super(ZenPack, self).remove(app, leaveObjects=leaveObjects)
class CatalogBase(object):
"""Base class that implements cataloging a property"""
# By Default there is no default catalog created.
_catalogs = {}
def get_catalog_name(self, name, scope):
if scope == 'device':
return '{}Search'.format(name)
else:
name = self.__module__.replace('.', '_')
return '{}Search'.format(name)
def get_catalog(self, name, scope, create=True):
"""Return catalog by name."""
spec = self._get_catalog_spec(name)
if not spec:
return
if scope == 'device':
try:
return getattr(self.device(), self.get_catalog_name(name, scope))
except AttributeError:
if create:
return self._create_catalog(name, 'device')
else:
try:
return getattr(self.dmd.Device, self.get_catalog_name(name, scope))
except AttributeError:
if create:
return self._create_catalog(name, 'global')
return
def get_catalog_scopes(self, name):
"""Return catalog scopes by name."""
spec = self._get_catalog_spec(name)
if not spec:
[]
scopes = [spec['indexes'][x].get('scope', 'device') for x in spec['indexes']]
if 'both' in scopes:
scopes = [x for x in scopes if x != 'both']
scopes.append('device')
scopes.append('global')
return set(scopes)
def get_catalogs(self, whiteList=None):
"""Return all catalogs for this class."""
catalogs = []
for name in self._catalogs:
for scope in self.get_catalog_scopes(name):
if not whiteList:
catalogs.append(self.get_catalog(name, scope))
else:
if scope in whiteList:
catalogs.append(self.get_catalog(name, scope, create=False))
return catalogs
def _get_catalog_spec(self, name):
if not hasattr(self, '_catalogs'):
LOG.error("%s has no catalogs defined", self.id)
return
spec = self._catalogs.get(name)
if not spec:
LOG.error("%s catalog definition is missing", name)
return
if not isinstance(spec, dict):
LOG.error("%s catalog definition is not a dict", name)
return
if not spec.get('indexes'):
LOG.error("%s catalog definition has no indexes", name)
return
return spec
def _create_catalog(self, name, scope='device'):
"""Create and return catalog defined by name."""
from Products.ZCatalog.Catalog import CatalogError
from Products.ZCatalog.ZCatalog import manage_addZCatalog
from Products.Zuul.interfaces import ICatalogTool
spec = self._get_catalog_spec(name)
if not spec:
return
if scope == 'device':
catalog_name = self.get_catalog_name(name, scope)
device = self.device()
if not hasattr(device, catalog_name):
manage_addZCatalog(device, catalog_name, catalog_name)
zcatalog = device._getOb(catalog_name)
else:
catalog_name = self.get_catalog_name(name, scope)
deviceClass = self.dmd.Devices
if not hasattr(deviceClass, catalog_name):
manage_addZCatalog(deviceClass, catalog_name, catalog_name)
zcatalog = deviceClass._getOb(catalog_name)
catalog = zcatalog._catalog
classname = spec.get(
'class', 'Products.ZenModel.DeviceComponent.DeviceComponent')
for propname, propdata in spec['indexes'].items():
index_type = propdata.get('type')
if not index_type:
LOG.error("%s index has no type", propname)
return
index_factory = {
'field': makeFieldIndex,
'keyword': makeKeywordIndex,
}.get(index_type.lower())
if not index_factory:
LOG.error("%s is not a valid index type", index_type)
return
try:
catalog.addIndex(propname, index_factory(propname))
catalog.addColumn(propname)
except CatalogError:
# Index already exists.
pass
else:
if scope == 'device':
results = ICatalogTool(device).search(types=(classname,))
else:
results = ICatalogTool(deviceClass).search(types=(classname,))
for result in results:
if hasattr(result.getObject(), 'index_object'):
result.getObject().index_object()
return zcatalog
def index_object(self, idxs=None):
"""Index in all configured catalogs."""
for catalog in self.get_catalogs():
if catalog:
catalog.catalog_object(self, self.getPrimaryId())
def unindex_object(self):
"""Unindex from all configured catalogs."""
for catalog in self.get_catalogs():
if catalog:
catalog.uncatalog_object(self.getPrimaryId())
class ModelBase(CatalogBase):
"""Base class for ZenPack model classes."""
def getIconPath(self):
"""Return relative URL path for class' icon."""
return getattr(self, 'icon_url', '/zport/dmd/img/icons/noicon.png')
class DeviceBase(ModelBase):
"""First superclass for zenpacklib types created by DeviceTypeFactory.
Contains attributes that should be standard on all ZenPack Device
types.
"""
def search(self, name, *args, **kwargs):
return catalog_search(self, name, *args, **kwargs)
class ComponentBase(ModelBase):
"""First superclass for zenpacklib types created by ComponentTypeFactory.
Contains attributes that should be standard on all ZenPack Component
types.
"""
factory_type_information = ({
'actions': ({
'id': 'perfConf',
'name': 'Template',
'action': 'objTemplates',
'permissions': (ZEN_CHANGE_DEVICE,),
},),
},)
_catalogs = {
'ComponentBase': {
'indexes': {
'id': {'type': 'field'},
}
}
}
def device(self):
"""Return device under which this component/device is contained."""
obj = self
for i in xrange(200):
if isinstance(obj, BaseDevice):
return obj
try:
obj = obj.getPrimaryParent()
except AttributeError:
# While it is generally not normal to have devicecomponents
# that are not part of a device, it CAN occur in certain
# non-error situations, such as when it is in the process of
# being deleted. In that case, the DeviceComponentProtobuf
# (Products.ZenMessaging.queuemessaging.adapters) implementation
# expects device() to return None, not to throw an exception.
return None
def getIdForRelationship(self, relationship):
"""Return id in ToOne relationship or None."""
obj = relationship()
if obj:
return obj.id
def setIdForRelationship(self, relationship, id_):
"""Update ToOne relationship given relationship and id."""
old_obj = relationship()
# Return with no action if the relationship is already correct.
if (old_obj and old_obj.id == id_) or (not old_obj and not id_):
return
# Remove current object from relationship.
if old_obj:
relationship.removeRelation()
# Index old object. It might have a custom path reporter.
notify(IndexingEvent(old_obj.primaryAq(), 'path', False))
# If there is no new ID to add, we're done.
if id_ is None:
return
# Find and add new object to relationship.
for result in self.device().search('ComponentBase', id=id_):
new_obj = result.getObject()
relationship.addRelation(new_obj)
# Index remote object. It might have a custom path reporter.
notify(IndexingEvent(new_obj.primaryAq(), 'path', False))
# For componentSearch. Would be nice if we could target
# idxs=['getAllPaths'], but there's a chance that it won't exist
# yet.
new_obj.index_object()
return
LOG.error("setIdForRelationship (%s): No target found matching id=%s", relationship, id_)
def getIdsInRelationship(self, relationship):
"""Return a list of object ids in relationship.
relationship must be of type ToManyContRelationship or
ToManyRelationship. Raises ValueError for any other type.
"""
if isinstance(relationship, ToManyContRelationship):
return relationship.objectIds()
elif isinstance(relationship, ToManyRelationship):
return [x.id for x in relationship.objectValuesGen()]
try:
type_name = type(relationship.aq_self).__name__
except AttributeError:
type_name = type(relationship).__name__
raise ValueError(
"invalid type '%s' for getIdsInRelationship()" % type_name)
def setIdsInRelationship(self, relationship, ids):
"""Update ToMany relationship given relationship and ids."""
new_ids = set(ids)
current_ids = set(o.id for o in relationship.objectValuesGen())
changed_ids = new_ids.symmetric_difference(current_ids)
query = Or(*[Eq('id', x) for x in changed_ids])
obj_map = {}
for result in self.device().search('ComponentBase', query):
obj_map[result.id] = result.getObject()
for id_ in new_ids.symmetric_difference(current_ids):
obj = obj_map.get(id_)
if not obj:
LOG.error(
"setIdsInRelationship (%s): No targets found matching "
"id=%s", relationship, id_)
continue
if id_ in new_ids:
LOG.debug("Adding %s to %s" % (obj, relationship))
relationship.addRelation(obj)
# Index remote object. It might have a custom path reporter.
notify(IndexingEvent(obj, 'path', False))
else:
LOG.debug("Removing %s from %s" % (obj, relationship))
relationship.removeRelation(obj)
# If the object was not deleted altogether..
if not isinstance(relationship, ToManyContRelationship):
# Index remote object. It might have a custom path reporter.
notify(IndexingEvent(obj, 'path', False))
# For componentSearch. Would be nice if we could target
# idxs=['getAllPaths'], but there's a chance that it won't exist
# yet.
obj.index_object()
@property
def containing_relname(self):
"""Return name of containing relationship."""
return self.get_containing_relname()
@memoize
def get_containing_relname(self):
"""Return name of containing relationship."""
for relname, relschema in self._relations:
if issubclass(relschema.remoteType, ToManyCont):
return relname
@property
def faceting_relnames(self):
"""Return non-containing relationship names for faceting."""
return self.get_faceting_relnames()
@memoize
def get_faceting_relnames(self):
"""Return non-containing relationship names for faceting."""
faceting_relnames = []
for relname, relschema in self._relations:
if relname in FACET_BLACKLIST:
continue
if issubclass(relschema.remoteType, ToMany):
faceting_relnames.append(relname)
return faceting_relnames
def get_facets(self, seen=None):
"""Generate non-containing related objects for faceting."""
if seen is None:
seen = set()
for relname in self.get_faceting_relnames():
rel = getattr(self, relname, None)
if not rel or not callable(rel):
continue
relobjs = rel()
if not relobjs:
continue
if isinstance(rel, ToOneRelationship):
# This is really a single object.
relobjs = [relobjs]
for obj in relobjs:
if obj in seen:
continue
yield obj
seen.add(obj)
for facet in obj.get_facets(seen=seen):
yield facet
def rrdPath(self):
"""Return filesystem path for RRD files for this component.
Overrides RRDView to flatten component RRD files into a single
subdirectory per-component per-device. This allows for the
possibility of a component changing its contained path within
the device without losing historical performance data.
This requires that each component have a unique id within the
device's namespace.
"""
original = super(ComponentBase, self).rrdPath()
try:
# Zenoss 5 returns a JSONified dict from rrdPath.
json.loads(original)
except ValueError:
# Zenoss 4 and earlier return a string that starts with "Devices/"
return os.path.join('Devices', self.device().id, self.id)
else:
return original
def getRRDTemplateName(self):
"""Return name of primary template to bind to this component."""
if self._templates:
return self._templates[0]
return ''
def getRRDTemplates(self):
"""Return list of templates to bind to this component.
Enhances RRDView.getRRDTemplates by supporting both acquisition
and inhertence template binding. Additionally supports user-
defined *-replacement and *-addition monitoring templates that
can replace or augment the standard templates respectively.
"""
templates = []
for template_name in self._templates:
replacement = self.getRRDTemplateByName(
'{}-replacement'.format(template_name))
if replacement:
templates.append(replacement)
else:
template = self.getRRDTemplateByName(template_name)
if template:
templates.append(template)
addition = self.getRRDTemplateByName(
'{}-addition'.format(template_name))
if addition:
templates.append(addition)
return templates
class DeviceIndexableWrapper(BaseDeviceWrapper):
"""Indexing wrapper for ZenPack devices.
This is required to make sure that key classes are returned by
objectImplements even if their depth within the inheritence tree
would otherwise exclude them. Certain searches in Zenoss expect
objectImplements to contain Device.
"""
implements(IIndexableWrapper)
adapts(DeviceBase)
def objectImplements(self):
"""Return list of implemented interfaces and classes.
Extends DeviceWrapper by ensuring that Device will always be
part of the returned list.
"""
dottednames = super(DeviceIndexableWrapper, self).objectImplements()
return list(set(dottednames).union([
'Products.ZenModel.Device.Device',
]))
GSM.registerAdapter(DeviceIndexableWrapper, (DeviceBase,), IIndexableWrapper)
class ComponentIndexableWrapper(BaseComponentWrapper):
"""Indexing wrapper for ZenPack components.
This is required to make sure that key classes are returned by
objectImplements even if their depth within the inheritence tree
would otherwise exclude them. Certain searches in Zenoss expect
objectImplements to contain DeviceComponent and ManagedEntity where
applicable.
"""
implements(IIndexableWrapper)
adapts(ComponentBase)
def objectImplements(self):
"""Return list of implemented interfaces and classes.
Extends ComponentWrapper by ensuring that DeviceComponent will
always be part of the returned list.
"""
dottednames = super(ComponentIndexableWrapper, self).objectImplements()
return list(set(dottednames).union([
'Products.ZenModel.DeviceComponent.DeviceComponent',
]))
GSM.registerAdapter(ComponentIndexableWrapper, (ComponentBase,), IIndexableWrapper)
class ComponentPathReporter(DefaultPathReporter):
"""Global catalog path reporter adapter factory for components."""
implements(IPathReporter)
adapts(ComponentBase)
def getPaths(self):
paths = super(ComponentPathReporter, self).getPaths()
for facet in self.context.get_facets():
rp = relPath(facet, facet.containing_relname)
paths.extend(rp)
return paths
GSM.registerAdapter(ComponentPathReporter, (ComponentBase,), IPathReporter)
class ComponentFormBuilder(BaseComponentFormBuilder):
"""Base class for all custom FormBuilders.
Adds support for renderers in the Component Details form.
"""
implements(IFormBuilder)
adapts(IInfo)
def render(self, **kwargs):
rendered = super(ComponentFormBuilder, self).render(kwargs)
self.zpl_decorate(rendered)
return rendered
def zpl_decorate(self, item):
if 'items' in item:
for item in item['items']:
self.zpl_decorate(item)
return
if 'xtype' in item and 'name' in item and item['xtype'] != 'linkfield':
if item['name'] in self.renderer:
renderer = self.renderer[item['name']]
if renderer:
item['xtype'] = 'ZPLRenderableDisplayField'
item['renderer'] = renderer
def DeviceTypeFactory(name, bases):
"""Return a "ZenPackified" device class given bases tuple."""
all_bases = (DeviceBase,) + bases
def index_object(self, idxs=None, noips=False):
for base in all_bases:
if hasattr(base, 'index_object'):
try:
base.index_object(self, idxs=idxs, noips=noips)
except TypeError:
base.index_object(self)
def unindex_object(self):
for base in all_bases:
if hasattr(base, 'unindex_object'):
base.unindex_object(self)
attributes = {
'index_object': index_object,
'unindex_object': unindex_object,
}
return type(name, all_bases, attributes)
Device = DeviceTypeFactory(
'Device', (BaseDevice,))
def ComponentTypeFactory(name, bases):
"""Return a "ZenPackified" component class given bases tuple."""
all_bases = (ComponentBase,) + bases
def index_object(self, idxs=None):
for base in all_bases:
if hasattr(base, 'index_object'):
try:
base.index_object(self, idxs=idxs)
except TypeError:
base.index_object(self)
def unindex_object(self):
for base in all_bases:
if hasattr(base, 'unindex_object'):
base.unindex_object(self)
attributes = {
'index_object': index_object,
'unindex_object': unindex_object,
}
return type(name, all_bases, attributes)
Component = ComponentTypeFactory(
'Component', (BaseDeviceComponent, BaseManagedEntity))
HardwareComponent = ComponentTypeFactory(
'HardwareComponent', (BaseHWComponent,))
class IHardwareComponentInfo(IBaseComponentInfo):
"""Info interface for ZenPackHardwareComponent.
This exists because Zuul has no HWComponent info interface.
"""
manufacturer = schema.Entity(title=u'Manufacturer')
product = schema.Entity(title=u'Model')
class HardwareComponentInfo(BaseComponentInfo):
"""Info adapter factory for ZenPackHardwareComponent.
This exists because Zuul has no HWComponent info adapter.
"""
implements(IHardwareComponentInfo)
adapts(HardwareComponent)
@property
@info
def manufacturer(self):
"""Return Info for hardware product class' manufacturer."""
product_class = self._object.productClass()
if product_class:
return product_class.manufacturer()
@property
@info
def product(self):
"""Return Info for hardware product class."""
return self._object.productClass()
# ZenPack Configuration #####################################################
FACET_BLACKLIST = (
'dependencies',
'dependents',
'maintenanceWindows',
'pack',
'productClass',
)
class Spec(object):
"""Abstract base class for specifications."""
def specs_from_param(self, spec_type, param_name, param_dict):
"""Return a normalized dictionary of spec_type instances."""
if param_dict is None:
param_dict = {}
elif not isinstance(param_dict, dict):
raise TypeError(
"{!r} argument must be dict or None, not {!r}"
.format(
'{}.{}'.format(spec_type.__name__, param_name),
type(param_dict).__name__))
else:
apply_defaults(param_dict)
return {
k: spec_type(self, k, **(fix_kwargs(v)))
for k, v in param_dict.iteritems()}
class ZenPackSpec(Spec):
"""Representation of a ZenPack's desired configuration.
Intended to be used to build a ZenPack declaratively as in the
following example in a ZenPack's __init__.py:
from . import zenpacklib
CFG = zenpacklib.ZenPackSpec(
name=__name__,
zProperties={
'zCiscoAPICHost': {
'category': 'Cisco APIC',
'type': 'string',
},
'zCiscoAPICPort': {
'category': 'Cisco APIC',
'default': '80',
},
},
classes={
'APIC': {
'base': zenpacklib.Device,
},
'FabricPod': {
'meta_type': 'Cisco APIC Fabric Pod',
'base': zenpacklib.Component,
},
'FvTenant': {
'meta_type': 'Cisco APIC Tenant',
'base': zenpacklib.Component,
},
},
class_relationships=zenpacklib.relationships_from_yuml((
"[APIC]++-[FabricPod]",
"[APIC]++-[FvTenant]",
))
)
CFG.create()
"""
def __init__(
self,
name,
zProperties=None,
classes=None,
class_relationships=None,
device_classes=None):
"""TODO."""
self.name = name
self.NEW_COMPONENT_TYPES = []
self.NEW_RELATIONS = collections.defaultdict(list)
# zProperties
self.zProperties = self.specs_from_param(
ZPropertySpec, 'zProperties', zProperties)
# Classes
if classes:
for classname, classdata in classes.items():
if 'relationships' not in classdata:
classdata['relationships'] = {}
# Merge class_relationships.
if class_relationships:
update(
classdata['relationships'],
class_relationships.get(classname, {}))
self.classes = self.specs_from_param(ClassSpec, 'classes', classes)
self.imported_classes = {}
for classname, classdata in classes.iteritems():
relationships = classdata['relationships']
for relationship in relationships:
try:
if 'schema' in relationships[relationship]:
className = relationships[relationship]['schema'].remoteClass
if '.' in className and className.split('.')[-1] not in self.classes:
module = ".".join(className.split('.')[0:-1])
kls = importClass(module)
self.imported_classes[className] = kls
else:
LOG.error('%s: relationship %s has no schema' % (self.name, relationship))
except ImportError:
pass
for class_ in self.classes.values():
for relationship in class_.relationships.values():
if relationship.schema.remoteClass in self.imported_classes.keys():
remoteClass = relationship.schema.remoteClass # Products.ZenModel.Device.Device
relname = relationship.schema.remoteName # coolingFans
modname = relationship.class_.model_class.__module__ # ZenPacks.zenoss.HP.Proliant.CoolingFan
className = relationship.class_.model_class.__name__ # CoolingFan
remoteClassObj = self.imported_classes[remoteClass] # Device_obj
remoteType = relationship.schema.remoteType # ToManyCont
localType = relationship.schema.__class__ # ToOne
remote_relname = relationship.zenrelations_tuple[0] # products_zenmodel_device_device
if relname not in (x[0] for x in remoteClassObj._relations):
remoteClassObj._relations += ((relname, remoteType(localType, modname, remote_relname)),)
remote_module_id = remoteClassObj.__module__
if relname not in self.NEW_RELATIONS[remote_module_id]:
self.NEW_RELATIONS[remote_module_id].append(relname)
component_type = '.'.join((modname, className))
if component_type not in self.NEW_COMPONENT_TYPES:
self.NEW_COMPONENT_TYPES.append(component_type)
# Device Classes
self.device_classes = self.specs_from_param(
DeviceClassSpec, 'device_classes', device_classes)
@property
def ordered_classes(self):
"""Return ordered list of ClassSpec instances."""
return sorted(self.classes.values(), key=operator.attrgetter('order'))
def create(self):
"""Implement specification."""
self.create_zenpack_class()
for spec in self.zProperties.itervalues():
spec.create()
for spec in self.classes.itervalues():
spec.create()