forked from zenoss/ZenPacks.zenoss.ZenPackLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzenpacklib.py
executable file
·6378 lines (5129 loc) · 227 KB
/
zenpacklib.py
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
#!/usr/bin/env python
##############################################################################
# This program is part of zenpacklib, the ZenPack API.
# Copyright (C) 2013-2015 Zenoss, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
##############################################################################
"""zenpacklib - ZenPack API.
This module provides a single integration point for common ZenPacks.
"""
# PEP-396 version. (https://www.python.org/dev/peps/pep-0396/)
__version__ = "1.1.0dev"
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 inspect
import json
import operator
import os
import re
import sys
import math
if __name__ == '__main__':
import Globals
from Products.ZenUtils.Utils import unused
unused(Globals)
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
import zope.proxy
from Acquisition import aq_base
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.ZenModel.CommentGraphPoint import CommentGraphPoint
from Products.ZenModel.ComplexGraphPoint import ComplexGraphPoint
from Products.ZenModel.ThresholdGraphPoint import ThresholdGraphPoint
from Products.ZenModel.GraphPoint import GraphPoint
from Products.ZenModel.DataPointGraphPoint import DataPointGraphPoint
from Products.ZenRelations.Exceptions import ZenSchemaError
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
try:
import yaml
import yaml.constructor
YAML_INSTALLED = True
except ImportError:
YAML_INSTALLED = False
OrderedDict = None
try:
# included in standard lib from Python 2.7
from collections import OrderedDict
except ImportError:
# try importing the backported drop-in replacement
# it's available on PyPI
try:
from ordereddict import OrderedDict
except ImportError:
OrderedDict = None
# 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.
"""
def __init__(self, *args, **kwargs):
super(ZenPack, self).__init__(*args, **kwargs)
# Emable logging to stderr if the user sets the ZPL_LOG_ENABLE environment
# variable to this zenpack's name. (defaults to 'DEBUG', but
# user may choose a different level with ZPL_LOG_LEVEL.
if self.id in os.environ.get('ZPL_LOG_ENABLE', ''):
levelName = os.environ.get('ZPL_LOG_LEVEL', 'DEBUG').upper()
logLevel = getattr(logging, levelName)
if logLevel:
# Reconfigure the logger to ensure it goes to stderr for the
# selected level or above.
LOG.propagate = False
LOG.setLevel(logLevel)
h = logging.StreamHandler(sys.stderr)
h.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(name)s: %(message)s'))
LOG.addHandler(h)
else:
LOG.error("Unrecognized ZPL_LOG_LEVEL '%s'" %
os.environ.get('ZPL_LOG_LEVEL'))
# 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):
# create device classes and set zProperties on them
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()
# load monitoring templates
for dcname, dcspec in self.device_classes.iteritems():
for mtname, mtspec in dcspec.templates.iteritems():
mtspec.create(self.dmd)
def remove(self, app, leaveObjects=False):
if self._v_specparams is None:
return
from Products.Zuul.interfaces import ICatalogTool
if leaveObjects:
# Check whether the ZPL-managed monitoring templates have
# been modified by the user. If so, those changes will
# be lost during the upgrade.
#
# Ideally, I would inspect self.packables() to find these
# objects, but we do not have access to that relationship
# at this point in the process.
for dcname, dcspec in self._v_specparams.device_classes.iteritems():
deviceclass = self.dmd.Devices.getOrganizer(dcname)
if deviceclass is None:
LOG.warning(
"DeviceClass %s has been removed at some point "
"after the %s ZenPack was installed. It will be "
"reinstated if this ZenPack is upgraded or reinstalled",
dcname, self.id)
continue
for orig_mtname, orig_mtspec in dcspec.templates.iteritems():
try:
template = deviceclass.rrdTemplates._getOb(orig_mtname)
except AttributeError:
template = None
if template is None:
LOG.warning(
"Monitoring template %s/%s has been removed at some point "
"after the %s ZenPack was installed. It will be "
"reinstated if this ZenPack is upgraded or reinstalled",
dcname, orig_mtname, self.id)
continue
installed = RRDTemplateSpecParams.fromObject(template)
if installed != orig_mtspec:
import time
import difflib
lines_installed = [x + '\n' for x in yaml.dump(installed, Dumper=Dumper).split('\n')]
lines_orig_mtspec = [x + '\n' for x in yaml.dump(orig_mtspec, Dumper=Dumper).split('\n')]
diff = ''.join(difflib.unified_diff(lines_orig_mtspec, lines_installed))
# installed is not going to have cycletime in it, because it's the default.
newname = "{}-upgrade-{}".format(orig_mtname, int(time.time()))
LOG.error(
"Monitoring template %s/%s has been modified "
"since the %s ZenPack was installed. These local "
"changes will be lost as this ZenPack is upgraded "
"or reinstalled. Existing template will be "
"renamed to '%s'. Please review and reconcile "
"local changes:\n%s",
dcname, orig_mtname, self.id, newname, diff)
deviceclass.rrdTemplates.manage_renameObject(template.id, newname)
else:
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)
def manage_exportPack(self, download="no", REQUEST=None):
"""Export ZenPack to $ZENHOME/export directory.
In order to control which objects are exported, we wrap the
entire zenpack object, and the zenpackable objects it contains,
in proxy objects, which allow us to override their behavior
without disrupting the original objects.
"""
import Acquisition
class FilteredZenPackable(zope.proxy.ProxyBase, Acquisition.Explicit):
@zope.proxy.non_overridable
def objectValues(self):
# proxy the remote objects on ToManyContRelationships
return [FilteredZenPackable(x).__of__(x.aq_parent) for x in self._objects.values()]
@zope.proxy.non_overridable
def exportXmlRelationships(self, ofile, ignorerels=[]):
for rel in self.getRelationships():
if rel.id in ignorerels:
continue
filtered_rel = FilteredZenPackable(rel).__of__(rel.aq_parent)
filtered_rel.exportXml(ofile, ignorerels)
@zope.proxy.non_overridable
def exportXml(self, *args, **kwargs):
original = zope.proxy.getProxiedObject(self).__class__.exportXml
path = '/'.join(self.getPrimaryPath())
if getattr(self, 'zpl_managed', False):
LOG.info("Excluding %s from export (ZPL-managed object)" % path)
return
original(self, *args, **kwargs)
class FilteredZenPack(zope.proxy.ProxyBase):
@zope.proxy.non_overridable
def packables(self):
packables = zope.proxy.getProxiedObject(self).packables()
return [FilteredZenPackable(x).__of__(x.aq_parent) for x in packables]
return ZenPackBase.manage_exportPack(
FilteredZenPack(self),
download=download,
REQUEST=REQUEST)
class CatalogBase(object):
"""Base class that implements cataloging a property"""
# By Default there is no default catalog created.
_catalogs = {}
def search(self, name, *args, **kwargs):
"""
Return iterable of matching brains in named catalog.
'name' is the catalog name (typically the name of a class)
"""
return catalog_search(self, name, *args, **kwargs)
@classmethod
def class_search(cls, dmd, name, *args, **kwargs):
"""
Return iterable of matching brains in named catalog.
'name' is the catalog name (typically the name of a class)
"""
name = cls.__module__.replace('.', '_')
return catalog_search(dmd.Devices, name, *args, **kwargs)
@classmethod
def get_catalog_name(cls, name, scope):
if scope == 'device':
return '{}Search'.format(name)
else:
name = cls.__module__.replace('.', '_')
return '{}Search'.format(name)
@classmethod
def class_get_catalog(cls, dmd, name, scope, create=True):
"""Return catalog by name."""
spec = cls._get_catalog_spec(name)
if not spec:
return
if scope == 'device':
raise ValueError("device scoped catalogs are only available from device or component objects, not classes")
else:
try:
return getattr(dmd.Devices, cls.get_catalog_name(name, scope))
except AttributeError:
if create:
return cls._class_create_catalog(dmd, name, 'global')
return
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.Devices, self.get_catalog_name(name, scope))
except AttributeError:
if create:
return self._create_catalog(name, 'global')
return
@classmethod
def get_catalog_scopes(cls, name):
"""Return catalog scopes by name."""
spec = cls._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)
@classmethod
def class_get_catalogs(cls, dmd, whiteList=None):
"""Return all catalogs for this class."""
catalogs = []
for name in cls._catalogs:
for scope in cls.get_catalog_scopes(name):
if scope == 'device':
# device scoped catalogs are not available at the class level
continue
if not whiteList:
catalogs.append(cls.class_get_catalog(dmd, name, scope))
else:
if scope in whiteList:
catalogs.append(cls.class_get_catalog(dmd, name, scope, create=False))
return catalogs
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
@classmethod
def _get_catalog_spec(cls, name):
if not hasattr(cls, '_catalogs'):
LOG.error("%s has no catalogs defined", cls)
return
spec = cls._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
@classmethod
def _class_create_catalog(cls, dmd, name, scope='device'):
"""Create and return catalog defined by name."""
from Products.ZCatalog.ZCatalog import manage_addZCatalog
spec = cls._get_catalog_spec(name)
if not spec:
return
if scope == 'device':
raise ValueError("device scoped catalogs may only be created from the device or component object, not classes")
else:
catalog_name = cls.get_catalog_name(name, scope)
deviceClass = dmd.Devices
if not hasattr(deviceClass, catalog_name):
manage_addZCatalog(deviceClass, catalog_name, catalog_name)
zcatalog = deviceClass._getOb(catalog_name)
cls._create_indexes(zcatalog, spec)
return zcatalog
def _create_catalog(self, name, scope='device'):
"""Create and return catalog defined by name."""
from Products.ZCatalog.ZCatalog import manage_addZCatalog
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)
self._create_indexes(zcatalog, spec)
return zcatalog
@classmethod
def _create_indexes(cls, zcatalog, spec):
from Products.ZCatalog.Catalog import CatalogError
from Products.Zuul.interfaces import ICatalogTool
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:
# the device if it's a device scoped catalog, or dmd.Devices
# if it's a global scoped catalog.
context = zcatalog.getParentNode()
# reindex all objects of this type so they are added to the
# catalog.
results = ICatalogTool(context).search(types=(classname,))
for result in results:
if hasattr(result.getObject(), 'index_object'):
result.getObject().index_object()
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.
"""
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 getStatus(self, statClass='/Status'):
"""Return the status number for this component.
Overridden to default statClass to /Status instead of
/Status/<self.meta_type>. Current practices do not include using
a separate event class for each component meta_type. The event
class plus component field already convey this level of
information.
"""
return BaseDeviceComponent.getStatus(self, statClass=statClass)
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
raise ZenSchemaError("%s (%s) has no containing relationship" % (self.__class__.__name__, self))
@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, root=None, streams=None, seen=None, path=None, recurse_all=False):
"""Generate non-containing related objects for faceting."""
if seen is None:
seen = set()
if path is None:
path = []
if root is None:
root = self
if streams is None:
streams = getattr(self, '_v_path_pattern_streams', [])
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]
relpath = "/".join(path + [relname])
# Always include directly-related objects.
for obj in relobjs:
if obj in seen:
continue
yield obj
seen.add(obj)
# If 'all' mode, just include indirectly-related objects as well, in
# an unfiltered manner.
if recurse_all:
for facet in obj.get_facets(root=root, seen=seen, path=path + [relname], recurse_all=True):
yield facet
return
# Otherwise, look at extra_path defined path pattern streams
for stream in streams:
recurse = any([pattern.match(relpath) for pattern in stream])
LOG.log(9, "[%s] matching %s against %s: %s" % (root.meta_type, relpath, [x.pattern for x in stream], recurse))
if not recurse:
continue
for obj in relobjs:
for facet in obj.get_facets(root=root, seen=seen, streams=[stream], path=path + [relname]):
if facet in seen:
continue
yield facet
seen.add(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."""