def getTree(self, id): """ Returns the tree structure of the application and collector hierarchy. @type id: string @param id: Id of the root node of the tree to be returned @rtype: [dictionary] @return: Object representing the tree """ try: appfacade = self._getFacade() monitorfacade = Zuul.getFacade("monitors", self.context) nodes = [ITreeNode(m) for m in monitorfacade.query()] for monitor in nodes: apps = appfacade.queryMonitorDaemons(monitor.name) for app in apps: monitor.addChild(IInfo(app)) apps = appfacade.queryMasterDaemons() for app in apps: nodes.append(IInfo(app)) return Zuul.marshal(nodes) except URLError as e: log.exception(e) return DirectResponse.fail( "Error fetching daemons list: " + str(e.reason) )
def cutover(self, dmd): self.dmd = dmd self.triggers_facade = Zuul.getFacade('triggers', dmd) self.existing_triggers = self.triggers_facade.getTriggers() self.existing_notifications = self.triggers_facade.getNotifications() # action rules are being removed, make sure they haven't been yet. rules = [] if hasattr(dmd.ZenUsers, 'getAllActionRules'): rules = dmd.ZenUsers.getAllActionRules() failed = False for rule in rules: try: trigger = self._createTrigger(rule) self._createNotification(rule, trigger) log.info('Done processing rule: %s.' % rule.id) except InvalidTriggerActionType, e: failed = True log.warn(" %s: Successfully migrated rule to Trigger, but was " "unable to create a Notification - rule has invalid or " "unknown action type: %s" % (rule.id, rule.action)) except TriggerRuleSourceError: failed = True log.warn('Unable to parse existing rule: %s' % rule.id)
def __init__(self, context, request): super(EventsRouter, self).__init__(context, request) self.zep = Zuul.getFacade('zep', context) self.catalog = IModelCatalogTool(context) self.manager = IGUIDManager(context.dmd) self._filterParser = _FilterParser(self.zep) self.use_permissions = False
def cutover(self, dmd): self.dmd = dmd self.triggers_facade = Zuul.getFacade('triggers', dmd) self.existing_triggers = self.triggers_facade.getTriggers() self.existing_notifications = self.triggers_facade.getNotifications() # action rules are being removed, make sure they haven't been yet. commands = dmd.ZenEventManager.commands.objectValues() failed = False for command in commands: if not command.where: continue try: trigger = self._createTrigger(command) self._createNotification(command, trigger) log.info('Done processing event command: %s.' % command.id) except TriggerRuleSourceError, e: failed = True log.warn('Unable to parse existing event command: %s' % command.id) except PythonConversionException, e: log.debug("Failed conversion: %s", e) log.warn("Unable to convert existing event command: %s" % command.id) failed = True
def getTree(self, id): """ Returns the tree structure of the application and collector hierarchy. @type id: string @param id: Id of the root node of the tree to be returned @rtype: [dictionary] @return: Object representing the tree """ try: appfacade = self._getFacade() monitorfacade = Zuul.getFacade("monitors", self.context) nodes = [ITreeNode(m) for m in monitorfacade.query()] for monitor in nodes: apps = appfacade.queryMonitorDaemons(monitor.name) for app in apps: monitor.addChild(IInfo(app)) apps = appfacade.queryMasterDaemons() for app in apps: nodes.append(IInfo(app)) return Zuul.marshal(nodes) except URLError as e: log.exception(e) return DirectResponse.fail("Error fetching daemons list: " + str(e.reason))
def __init__(self, context, request): self.api = Zuul.getFacade('reports') self.context = context self.request = request self.keys = ('deletable', 'edit_url', 'isMultiGraphReport', 'isGraphReport', 'columns') super(ReportRouter, self).__init__(context, request)
def __call__(self): appfacade = Zuul.getFacade('applications') zenHubs = [] collectors = [] collectorDaemons = [] for hub in self.context.dmd.Monitors.Hub.objectValues(spec='HubConf'): hubService = appfacade.queryHubDaemons(hub.id)[0] zenHubs.append(dict(id='hub_{}'.format(hub.id), title=hub.id, controlplaneServiceId=hubService.id, lastModeledState=str(hubService.state).lower(), RAMCommitment=getattr(hubService, 'RAMCommitment', None), instanceCount=hubService.instances)) for collector in hub.collectors(): collectors.append(dict(id='collector_{}'.format(collector.id), title=collector.id, set_hub='hub_{}'.format(hub.id))) for collectorDaemon in appfacade.queryMonitorDaemons(collector.id): if collectorDaemon.name in ('collectorredis', 'MetricShipper', 'zenmodeler', 'zminion'): continue collectorDaemons.append(dict(id='{}_{}'.format(collectorDaemon.name, collector.id), title='{} - {}'.format(collectorDaemon.name, collector.id), controlplaneServiceId=collectorDaemon.id, instanceCount=collectorDaemon.instances, lastModeledState=str(collectorDaemon.state).lower(), RAMCommitment=getattr(collectorDaemon, 'RAMCommitment', None), set_collector='collector_{}'.format(collector.id), monitor=collectorDaemon.autostart)) self.request.response.write(json.dumps(dict(zenHubs=zenHubs, collectors=collectors, collectorDaemons=collectorDaemons)))
def getTriggers(self): triggerFacade = Zuul.getFacade('triggers', self.context) triggers = triggerFacade.getTriggers() data = [{ 'name': t['name'], 'code': t['rule']['source'] } for t in triggers] return data
def getDevices(self, start=0, limit=200, orderby=None, reverse=False, params=None, fields=None): """ Retrieves a list of devices. @type limit: integer @param limit: (optional) Number of items to return @type params: dictionary @param params: (optional) Key-value pair of filters for this search e.g. params={'name': 'localhost'} @type fields: list of strings @param fields: (optional) list of indexed fields to retrieve, if None then attempts to retrive values for all indexes we have in SOLR. e.g. fields=["name", "osModel", "productionState"] """ if fields is None: indexes = self._getIndexes() indexes.append('events') else: indexes = self.filterIndexes(fields) if 'uuid' not in indexes: indexes.append('uuid') # in case customer uses not indexed fields to filter results in SOLR remove them from the query if params: for parameter in params.keys(): if parameter not in self.indexed: params.pop(parameter) results = self.model_catalog_helper.get_devices(start=start, limit=limit, orderby=orderby, reverse=reverse, globFilters=params, fields=indexes) devices = [brain.to_dict(indexes) for brain in results] if 'events' in indexes: uuids = [dev['uuid'] for dev in devices] zep = Zuul.getFacade('zep', self.context.dmd.primaryAq()) severities = zep.getEventSeverities(uuids) for device in devices: events = dict( (zep.getSeverityName(sev).lower(), counts) for (sev, counts) in severities[device['uuid']].iteritems()) device['events'] = events return devices, results.total
def asyncGetTree(self, id=None, additionalKeys=()): """ Server side method for asynchronous tree calls. Retrieves the immediate children of the node specified by "id" NOTE: our convention on the UI side is if we are asking for the root node then return the root and its children otherwise just return the children @type id: string @param id: The uid of the node we are getting the children for @rtype: [dictionary] @return: Object representing the immediate children """ showEventSeverityIcons = self.context.dmd.UserInterfaceSettings.getInterfaceSettings().get('showEventSeverityIcons') facade = self._getFacade() currentNode = facade.getTree(id) # we want every tree property except the "children" one keys = ('id', 'path', 'uid', 'iconCls', 'text', 'hidden', 'leaf') + additionalKeys # load the severities in one request childNodes = list(currentNode.children) if showEventSeverityIcons: uuids = [n.uuid for n in childNodes if n.uuid] zep = Zuul.getFacade('zep', self.context.dmd) if uuids: severities = zep.getWorstSeverity(uuids) for child in childNodes: if child.uuid: child.setSeverity(zep.getSeverityName(severities.get(child.uuid, 0)).lower()) children = [] # explicitly marshall the children for child in childNodes: childData = Marshaller(child).marshal(keys) # set children so that there is not an expanding # icon next to this child # see if there are any subtypes so we can show or not show the # expanding icon without serializing all the children. # Note that this is a performance optimization see ZEN-15857 organizer = child._get_object() # this looks at the children's type without waking them up hasChildren = any((o['meta_type'] for o in organizer._objects if o['meta_type'] == organizer.meta_type)) # reports have a different meta_type for the child organizers if "report" not in organizer.meta_type.lower() and not hasChildren: childData['children'] = [] children.append(childData) children.sort(key=lambda e: (e['leaf'], e['uid'].lower())) obj = currentNode._object._unrestrictedGetObject() # check to see if we are asking for the root primaryId = obj.getDmdRoot(obj.dmdRootName).getPrimaryId() if id == primaryId: root = Marshaller(currentNode).marshal(keys) root['children'] = children return [root] return children
def getCollector(self, collectorString): """ Get a collector by name @type collectorString: string @param collectorString: name of collector to return """ facade = Zuul.getFacade('monitors', self.context) collector = IInfo(facade.get(collectorString)) return DirectResponse.succeed(data=Zuul.marshal(collector))
def _getFacade(self): ''' getfacade ''' # The parameter in the next line - myAppAdapter - must match with # the name field in an adapter stanza in configure.zcml return Zuul.getFacade('BMCAdapter', self.context)
def afterSetUp(self): super(TemplateFacadeTest, self).afterSetUp() self.facade = Zuul.getFacade('template', self.dmd) # uid for a template self.uid = '/zport/dmd/Devices/rrdTemplates/test1' devices = self.dmd.Devices devices.manage_addRRDTemplate('test1') self.template = self.dmd.unrestrictedTraverse(self.uid)
def _getMonitorTree(self, id): appfacade = self._getFacade() monitorfacade = Zuul.getFacade("monitors", self.context) m = monitorfacade.get(id[len(_monitorprefix):]) monitor = ITreeNode(m) apps = appfacade.queryMonitorDaemons(monitor.name) for app in apps: monitor.addChild(IInfo(app)) return Zuul.marshal(monitor)
def testMetricBuilder(self): dev = self.dmd.Devices.createInstance('device1') templateFac = Zuul.getFacade('template', self.dmd) template = templateFac.addTemplate('test', '/zport/dmd/Devices')._object templateFac.addDataSource(template.getPrimaryId(), 'test', 'SNMP') metric = template.datasources()[0].datapoints()[0] cf = "avg" metric = self.facade._buildMetric(dev, metric, cf) self.assertEquals(metric['metric'], "device1/test_test") self.assertEquals(metric['aggregator'], 'avg')
def getReplayId(self, id): replayId = None zep = Zuul.getFacade('zep') event = zep.getEventSummary(id) occurrence = event.get('occurrence', [{}])[0] details = occurrence.get('details', []) for detail in details: if detail['name'] == 'eventReplayId': replayId = detail['value'][0] break return replayId
def getFetchedDataPoint(self, name): result = super(BulkMetricLoadMixin, self).getBulkLoadProperty(name) if result is not None: return result # if we load the data and it turns out to be missing or None don't try to fetch again if hasattr(self, "_metricsloaded") and self._metricsloaded: return result self._metricsloaded = True facade = Zuul.getFacade('device', self._object.dmd) facade.bulkLoadMetricData([self]) return super(BulkMetricLoadMixin, self).getBulkLoadProperty(name)
def stream(self): facade = Zuul.getFacade('checktrigger', self.context) data = json.loads(self.request.get('data')) uids = data.get('uids', {}) evids = uids.get('evids', []) trigger = uids.get('trigger') style = uids.get('style', 'human') results = facade.checkTriggers(evids, trigger) formatted = facade.formatOutput(style, results) for result in formatted: self.write(result) self.write('Done')
def asyncGetTree(self, id=None, additionalKeys=()): """ Server side method for asynchronous tree calls. Retrieves the immediate children of the node specified by "id" NOTE: our convention on the UI side is if we are asking for the root node then return the root and its children otherwise just return the children @type id: string @param id: The uid of the node we are getting the children for @rtype: [dictionary] @return: Object representing the immediate children """ showEventSeverityIcons = self.context.dmd.UserInterfaceSettings.getInterfaceSettings( ).get('showEventSeverityIcons') facade = self._getFacade() currentNode = facade.getTree(id) # we want every tree property except the "children" one keys = ('id', 'path', 'uid', 'iconCls', 'text', 'hidden', 'leaf') + additionalKeys # load the severities in one request childNodes = list(currentNode.children) if showEventSeverityIcons: uuids = [n.uuid for n in childNodes if n.uuid] zep = Zuul.getFacade('zep', self.context.dmd) if uuids: severities = zep.getWorstSeverity(uuids) for child in childNodes: if child.uuid: child.setSeverity( zep.getSeverityName(severities.get(child.uuid, 0)).lower()) children = [] # explicitly marshall the children for child in childNodes: childData = Marshaller(child).marshal(keys) children.append(childData) children.sort(key=lambda e: (e['leaf'], e['uid'].lower())) obj = currentNode._object._unrestrictedGetObject() # check to see if we are asking for the root primaryId = obj.getDmdRoot(obj.dmdRootName).getPrimaryId() if id == primaryId: root = Marshaller(currentNode).marshal(keys) root['children'] = children return [root] return children
def __call__(self): appfacade = Zuul.getFacade('applications') zenHubs = [] collectors = [] collectorDaemons = [] for hub in self.context.dmd.Monitors.Hub.objectValues(spec='HubConf'): hubService = appfacade.queryHubDaemons(hub.id)[0] zenHubs.append( dict(id='hub_{}'.format(hub.id), title=hub.id, controlplaneServiceId=hubService.id, lastModeledState=str(hubService.state).lower(), RAMCommitment=getattr(hubService, 'RAMCommitment', None), instanceCount=hubService.instances)) for collector in hub.collectors(): collectors.append( dict(id='collector_{}'.format(collector.id), title=collector.id, set_hub='hub_{}'.format(hub.id))) for collectorDaemon in appfacade.queryMonitorDaemons( collector.id): if collectorDaemon.name in ('collectorredis', 'MetricShipper', 'zenmodeler', 'zminion'): continue collectorDaemons.append( dict(id='{}_{}'.format(collectorDaemon.name, collector.id), title='{} - {}'.format(collectorDaemon.name, collector.id), controlplaneServiceId=collectorDaemon.id, instanceCount=collectorDaemon.instances, lastModeledState=str( collectorDaemon.state).lower(), RAMCommitment=getattr(collectorDaemon, 'RAMCommitment', None), set_collector='collector_{}'.format(collector.id), monitor=collectorDaemon.autostart)) self.request.response.write( json.dumps( dict(zenHubs=zenHubs, collectors=collectors, collectorDaemons=collectorDaemons)))
def asyncGetTree(self, id=None, additionalKeys=()): """ Server side method for asynchronous tree calls. Retrieves the immediate children of the node specified by "id" NOTE: our convention on the UI side is if we are asking for the root node then return the root and its children otherwise just return the children @type id: string @param id: The uid of the node we are getting the children for @rtype: [dictionary] @return: Object representing the immediate children """ showEventSeverityIcons = self.context.dmd.UserInterfaceSettings.getInterfaceSettings().get('showEventSeverityIcons') facade = self._getFacade() currentNode = facade.getTree(id) # we want every tree property except the "children" one keys = ('id', 'path', 'uid', 'iconCls', 'text', 'hidden', 'leaf') + additionalKeys # load the severities in one request childNodes = list(currentNode.children) if showEventSeverityIcons: uuids = [n.uuid for n in childNodes if n.uuid] zep = Zuul.getFacade('zep', self.context.dmd) if uuids: severities = zep.getWorstSeverity(uuids) for child in childNodes: if child.uuid: child.setSeverity(zep.getSeverityName(severities.get(child.uuid, 0)).lower()) children = [] # explicitly marshall the children for child in childNodes: childData = Marshaller(child).marshal(keys) children.append(childData) children.sort(key=lambda e: (e['leaf'], e['uid'].lower())) obj = currentNode._object._unrestrictedGetObject() # check to see if we are asking for the root primaryId = obj.getDmdRoot(obj.dmdRootName).getPrimaryId() if id == primaryId: root = Marshaller(currentNode).marshal(keys) root['children'] = children return [root] return children
def __call__(self, *args, **kwargs): """ Takes the id and prints out logs if we can fetch them from the facade. """ id = self.request.get('id', None) response = self.request.response if not id: response.write("id parameter is missing") return facade = Zuul.getFacade('applications', self.context) try: log = facade.getLog(id) self.request.response.setHeader('Content-Type', 'text/plain') response.write(log) except Exception as ex: response.write("Unable to find service with id %s: %s" % (id, ex))
def getDevices(self, start=0, limit=200, orderby=None, reverse=False, params=None, fields=None): """ Retrieves a list of devices. @type limit: integer @param limit: (optional) Number of items to return @type params: dictionary @param params: (optional) Key-value pair of filters for this search e.g. params={'name': 'localhost'} @type fields: list of strings @param fields: (optional) list of indexed fields to retrieve, if None then attempts to retrive values for all indexes we have in SOLR. e.g. fields=["name", "osModel", "productionState"] """ if fields is None: indexes = self._getIndexes() indexes.append('events') else: indexes = self.filterIndexes(fields) if 'uuid' not in indexes: indexes.append('uuid') # in case customer uses not indexed fields to filter results in SOLR remove them from the query if params: for parameter in params.keys(): if parameter not in self.indexed: params.pop(parameter) results = self.model_catalog_helper.get_devices(start=start, limit=limit, orderby=orderby, reverse=reverse, globFilters=params, fields=indexes) devices = [brain.to_dict(indexes) for brain in results] if 'events' in indexes: uuids = [dev['uuid'] for dev in devices] zep = Zuul.getFacade('zep', self.context.dmd.primaryAq()) severities = zep.getEventSeverities(uuids) for device in devices: events = dict((zep.getSeverityName(sev).lower(), counts) for (sev, counts) in severities[device['uuid']].iteritems()) device['events'] = events return devices, results.total
def __call__(self, *args, **kwargs): """ Takes the id and prints out logs if we can fetch them from the facade. """ id = self.request.get('id', None) response = self.request.response if not id: response.write("id parameter is missing") return facade = Zuul.getFacade('applications', self.context) try: log = facade.getLog(id) self.request.response.setHeader('Content-Type', 'text/plain') response.write(log) except Exception as ex: response.write( "Unable to find service with id %s: %s" % (id, ex) )
def _getOneTree(self, id): if id.startswith(_monitorprefix): return self._getMonitorTree(id) appfacade = self._getFacade() monitorfacade = Zuul.getFacade("monitors", self.context) roots = [] monitors = [ITreeNode(m) for m in monitorfacade.query()] for monitor in monitors: monitordict = Marshaller(monitor).marshal(_monkeys) if not appfacade.queryMonitorDaemons(monitor.name): monitordict['children'] = [] roots.append(monitordict) apps = [ IInfo(a) for a in appfacade.queryMasterDaemons() ] roots.extend([Marshaller(app).marshal(_appkeys) for app in apps]) return {'id': 'root', 'children': roots}
def getStatus(self, statusclass="/Status/*", **kwargs): """Return status number for this device. The status number is the number of critical events associated with this device. This includes only events tagger with the device's UUID, and not events affecting components of the device. None is returned when the device's status is unknown because it isn't being monitored, or because there was an error retrieving its events. This method is overridden here to provide a simpler default meaning for "down". By default any critical severity event that is in either the new or acknowledged state in the /Status event class and is tagged with the device's UUID indicates that the device is down. An alternate event class (statusclass) can be provided, which is what would be done by the device's getPingStatus and getSnmpStatus methods. A key different between this methods behavior vs. that of the Device.getStatus method it overrides is that warning and error events are not considered as affecting the device's status. """ if not self.monitorDevice(): return None zep = Zuul.getFacade("zep", self.dmd) try: event_filter = zep.createEventFilter( tags=[self.getUUID()], element_sub_identifier=[""], severity=[SEVERITY_CRITICAL], status=[STATUS_NEW, STATUS_ACKNOWLEDGED], event_class=filter(None, [statusclass])) result = zep.getEventSummaries(0, filter=event_filter, limit=0) except Exception: return None return int(result['total'])
def getStatus(self, statusclass="/Status/*", **kwargs): # This is identical the behavior provided by ZPL- once this zenpack # is converted to ZPL, this method can be removed. if not self.monitorDevice(): return None zep = Zuul.getFacade("zep", self.dmd) try: event_filter = zep.createEventFilter( tags=[self.getUUID()], element_sub_identifier=[""], severity=[SEVERITY_CRITICAL], status=[STATUS_NEW, STATUS_ACKNOWLEDGED], event_class=filter(None, [statusclass])) result = zep.getEventSummaries(0, filter=event_filter, limit=0) except Exception: return None return int(result['total'])
def update(self, uid, id, value, select_variable=None): """Updates an existing property. """ facade = self._getFacade() if select_variable: facade.updateCustomProperty( uid, id, select_variable=select_variable ) # Transform date value from milliseconds into DateTime object. prop = facade.getZenProperty(uid, id) if prop.get("type") == "date": userfacade = Zuul.getFacade('properties', self.context) usersettings = userfacade._dmd.ZenUsers.getUserSettings() tz = usersettings.timezone dt = DateTime(value, tz) if tz else DateTime(value) value = dt.ISO8601() facade.setZenProperty(uid, id, value) return DirectResponse.succeed( msg="Property %s successfully updated." % (id,) )
def getObjectsEventSummary(zem, objects, prodState=None, REQUEST=None): """ Return an HTML link and event pill for each object passed as a JSON object ready for inclusion in a YUI data table. @param objects: The objects for which to create links and pills. @type objects: list @return: dict containing 'columns' and 'data' entries @rtype: dict """ ret = {'columns':['Object', 'Events'], 'data':[]} zep = Zuul.getFacade('zep') uuids = [ obj.getUUID() for obj in objects ] sevs = (SEVERITY_CRITICAL,SEVERITY_ERROR,SEVERITY_WARNING,SEVERITY_INFO,SEVERITY_DEBUG) all_severities = zep.getEventSeveritiesByUuids(uuids, severities=sevs) severities_per_uuid = {} for uuid, severities in all_severities.iteritems(): severities_per_uuid[uuid] = dict((zep.getSeverityName(sev).lower(), counts) for (sev, counts) in severities.iteritems()) # build list of device-pill-pillsortkey tuples devdata = [] for obj in objects: alink = obj.getPrettyLink() uuid = obj.getUUID() obj_severities = severities_per_uuid[uuid] pill = getEventPillME(obj, showGreen=True, prodState=prodState, severities=obj_severities) if isinstance(pill, (list, tuple)): pill = pill[0] devdata.append((alink, pill, _getPillSortKey(pill))) devdata.sort(key=lambda x:x[-1]) # save object-pill data to return dict ret['data'] = [{'Object':x[0],'Events':x[1]} for x in devdata] return ret
def cutover(self, dmd): self.dmd = dmd self.triggers_facade = Zuul.getFacade('triggers', dmd) self.existing_triggers = self.triggers_facade.getTriggers() self.existing_notifications = self.triggers_facade.getNotifications() # action rules are being removed, make sure they haven't been yet. rules = [] if hasattr(dmd.ZenUsers, 'getAllActionRules'): rules = dmd.ZenUsers.getAllActionRules() failed = False for rule in rules: try: trigger = self._createTrigger(rule) self._createNotification(rule, trigger) log.info('Done processing rule: %s.' % rule.id) except InvalidTriggerActionType as e: failed = True log.warn(" %s: Successfully migrated rule to Trigger, but was " "unable to create a Notification - rule has invalid or " "unknown action type: %s" % (rule.id, rule.action)) except TriggerRuleSourceError: failed = True log.warn('Unable to parse existing rule: %s' % rule.id) except PythonConversionException as e: failed = True log.debug("Exception: %s", e) log.warn("Failed to convert existing rule: %s" % rule.id) if failed: log.info('If any rules were unable to be migrated, they will need to' ' be manually migrated to triggers and notifications. You can access' ' the old Alerting Rules through the ZMI.')
def afterSetUp(self): super(DeviceFacadeTest, self).afterSetUp() self.facade = Zuul.getFacade('device', self.dmd) # Un-jobify jobby methods self.facade.moveDevices = self.facade._moveDevices self.facade.deleteDevices = self.facade._deleteDevices
def _getFacade(self): return Zuul.getFacade('triggers', self)
def _getFacade(self): return Zuul.getFacade('um', self.context)
def _getFacade(self): return Zuul.getFacade('elementpool',self.context)
def __init__(self, context, request): super(NetworkRouter, self).__init__(context, request) self.api = Zuul.getFacade('network')
def _getFacade(self): return Zuul.getFacade('network', self.context)
def __init__(self, context, request): self.api = Zuul.getFacade('reports') self.context = context self.request = request self.keys = ('deletable', 'edit_url') super(ReportRouter, self).__init__(context, request)
def _getFacade(self): return Zuul.getFacade('oVirt', self.context)
def _getFacade(self): return Zuul.getFacade('zenpack', self.context)
def _getFacade(self): return Zuul.getFacade('devicemanagement', self.context)
def load(self, pack, app): """ Load Notifications and Triggers from an actions.json file Given a JSON-formatted configuration located at {zenpack}/actions/actions.json, create or update triggers and notifications specific to this zenpack. When creating or updating, the object is first checked to see whether or not an object exists with the configured guid for notifications or uuid for triggers. If an object is not found, one will be created. During creation, care is taken with regard to the id - integer suffixes will be appended to try to create a unique id. If we do not find a unique id after 100 tries, an error will occur. When updating an object, care is taken to not change the name as it may have since been altered by the user (or by this loader adding a suffix). """ log.debug("ZPTriggerAction: load") import Products.Zuul as Zuul from Products.Zuul.facades import ObjectNotFoundException tf = Zuul.getFacade('triggers', app.dmd) guidManager = IGUIDManager(app) for conf in findFiles(pack, 'zep',lambda f: f == 'actions.json'): import json data = json.load(open(conf, "r")) log.debug("DATA IS: %s" % data) triggers = data.get('triggers', []) notifications = data.get('notifications', []) tf.synchronize() all_names = set(t['name'] for t in tf.getTriggerList()) for trigger_conf in triggers: existing_trigger = guidManager.getObject(trigger_conf['uuid']) if existing_trigger: trigger_data = tf.getTrigger(trigger_conf['uuid']) trigger_conf['name'] = trigger_data['name'] log.info('Existing trigger found, updating: %s' % trigger_conf['name']) tf.updateTrigger(**trigger_conf) else: test_name = trigger_conf['name'] for x in xrange(1,101): if test_name in all_names: test_name = '%s_%d' % (trigger_conf['name'], x) else: log.debug('Found unused trigger name: %s' % test_name) break else: # if we didn't find a unique name raise Exception('Could not find unique name for trigger: "%s".' % trigger_conf['name']) log.info('Creating trigger: %s' % test_name) tf.createTrigger(test_name, uuid=trigger_conf['uuid'], rule=trigger_conf['rule']) for notification_conf in notifications: existing_notification = guidManager.getObject(str(notification_conf['guid'])) if existing_notification: log.info("Existing notification found, updating: %s" % existing_notification.id) subscriptions = set(existing_notification.subscriptions + notification_conf['subscriptions']) notification_conf['uid'] = '/zport/dmd/NotificationSubscriptions/%s' % existing_notification.id notification_conf['subscriptions'] = list(subscriptions) notification_conf['name'] = existing_notification.id tf.updateNotification(**notification_conf) else: test_id = notification_conf['id'] for x in xrange(1,101): test_uid = '/zport/dmd/NotificationSubscriptions/%s' % test_id try: tf.getNotification(test_uid) except ObjectNotFoundException: break test_id = '%s_%d' % (notification_conf['id'], x) else: # if we didn't find a unique name raise Exception('Could not find unique name for notification: "%s".' % notification_conf['id']) log.info('Creating notification: %s' % test_id) tf.createNotification(str(test_id), notification_conf['action'], notification_conf['guid']) notification_conf['uid'] = '/zport/dmd/NotificationSubscriptions/%s' % test_id tf.updateNotification(**notification_conf)
def __init__(self, context, request): self.facade = Zuul.getFacade('user', context) self.context = context self.request = request super(UsersRouter, self).__init__(context, request)
def __call__(self): appfacade = Zuul.getFacade('applications') idFormat = '{}_{}' titleFormat = '{} - {}' def getRedises(svcName, metricShipperParent=None): redises = [] for svc in appfacade.query(svcName): parentName = appfacade.get(svc.parentId).name shipperParentName = metricShipperParent if metricShipperParent else parentName metricShipper = 'MetricShipper_{}'.format(shipperParentName) redises.append(dict(id=idFormat.format(svc.name, parentName), title=titleFormat.format(svc.name, parentName), controlplaneServiceId=svc.id, RAMCommitment=getattr(svc, 'RAMCommitment', None), instanceCount=svc.instances, lastModeledState=str(svc.state).lower(), set_metricShipper=metricShipper, )) return redises redises = getRedises('redis', 'Metrics') redises.extend(getRedises('collectorredis')) metricShippers = [] for svc in appfacade.query('MetricShipper'): parentName = appfacade.get(svc.parentId).name if parentName == 'Metrics': redis = 'redis_Infrastructure' else: redis = 'collectorredis_{}'.format(parentName) data = dict(id=idFormat.format(svc.name, appfacade.get(svc.parentId).name), title=titleFormat.format(svc.name, appfacade.get(svc.parentId).name), controlplaneServiceId=svc.id, instanceCount=svc.instances, RAMCommitment=getattr(svc, 'RAMCommitment', None), lastModeledState=str(svc.state).lower(), set_redis=redis, ) metricShippers.append(data) consumerService = appfacade.query('MetricConsumer')[0] metricConsumers = [dict(id='MetricConsumer', title='MetricConsumer', controlplaneServiceId=consumerService.id, lastModeledState=str(consumerService.state).lower(), RAMCommitment=getattr(consumerService, 'RAMCommitment', None), instanceCount=consumerService.instances)] queryService = appfacade.query('CentralQuery')[0] centralQueries = [dict(id='CentralQuery', title='CentralQuery', controlplaneServiceId=queryService.id, lastModeledState=str(queryService.state).lower(), RAMCommitment=getattr(queryService, 'RAMCommitment', None), instanceCount=queryService.instances)] data = dict( redises=redises, metricShippers=metricShippers, metricConsumers=metricConsumers, centralQueries=centralQueries, ) self.request.response.write(json.dumps(data))
def __init__(self, context, request): super(BaseApiView, self).__init__(context, request) self._appfacade = Zuul.getFacade('applications')
def afterSetUp(self): super(MetricFacadeTest, self).afterSetUp() self.facade = Zuul.getFacade('metric', self.dmd) self.facade._client = MockRestServiceClient('http://localhost:8888')
def _getFacade(self): return Zuul.getFacade('hosts', self.context)
def load(self, pack, app): """ Load Notifications and Triggers from an actions.json file Given a JSON-formatted configuration located at {zenpack}/actions/actions.json, create or update triggers and notifications specific to this zenpack. When creating or updating, the object is first checked to see whether or not an object exists with the configured guid for notifications or uuid for triggers. If an object is not found, one will be created. During creation, care is taken with regard to the id - integer suffixes will be appended to try to create a unique id. If we do not find a unique id after 100 tries, an error will occur. When updating an object, care is taken to not change the name as it may have since been altered by the user (or by this loader adding a suffix). """ log.debug("ZPTriggerAction: load") import Products.Zuul as Zuul from Products.Zuul.facades import ObjectNotFoundException tf = Zuul.getFacade('triggers', app.dmd) guidManager = IGUIDManager(app) for conf in findFiles(pack, 'zep', lambda f: f == 'actions.json'): import json data = json.load(open(conf, "r")) log.debug("DATA IS: %s" % data) triggers = data.get('triggers', []) notifications = data.get('notifications', []) tf.synchronize() all_names = set(t['name'] for t in tf.getTriggerList()) for trigger_conf in triggers: existing_trigger = guidManager.getObject(trigger_conf['uuid']) if existing_trigger: trigger_data = tf.getTrigger(trigger_conf['uuid']) trigger_conf['name'] = trigger_data['name'] log.info('Existing trigger found, updating: %s' % trigger_conf['name']) tf.updateTrigger(**trigger_conf) else: test_name = trigger_conf['name'] for x in xrange(1, 101): if test_name in all_names: test_name = '%s_%d' % (trigger_conf['name'], x) else: log.debug('Found unused trigger name: %s' % test_name) break else: # if we didn't find a unique name raise Exception( 'Could not find unique name for trigger: "%s".' % trigger_conf['name']) log.info('Creating trigger: %s' % test_name) tf.createTrigger(test_name, uuid=trigger_conf['uuid'], rule=trigger_conf['rule']) for notification_conf in notifications: existing_notification = guidManager.getObject( str(notification_conf['guid'])) if existing_notification: log.info("Existing notification found, updating: %s" % existing_notification.id) subscriptions = set(existing_notification.subscriptions + notification_conf['subscriptions']) notification_conf[ 'uid'] = '/zport/dmd/NotificationSubscriptions/%s' % existing_notification.id notification_conf['subscriptions'] = list(subscriptions) notification_conf['name'] = existing_notification.id tf.updateNotification(**notification_conf) else: test_id = notification_conf['id'] for x in xrange(1, 101): test_uid = '/zport/dmd/NotificationSubscriptions/%s' % test_id try: tf.getNotification(test_uid) except ObjectNotFoundException: break test_id = '%s_%d' % (notification_conf['id'], x) else: # if we didn't find a unique name raise Exception( 'Could not find unique name for notification: "%s".' % notification_conf['id']) log.info('Creating notification: %s' % test_id) tf.createNotification(str(test_id), notification_conf['action'], notification_conf['guid']) notification_conf[ 'uid'] = '/zport/dmd/NotificationSubscriptions/%s' % test_id tf.updateNotification(**notification_conf)
def _getFacade(self): return Zuul.getFacade('template', self.context)