示例#1
0
    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)
            )
示例#2
0
 def test_getInfo(self):
     obj = self.facade.getInfo('/zport/dmd/Processes/foo/osProcessClasses/bar')
     self.assertEqual('bar', obj.name)
     data = Zuul.marshal(obj)
     self.assertEqual('bar', data['name'])
     data = {'name': 'barbar'}
     Zuul.unmarshal(data, obj)
     self.assertEqual('barbar', obj.name)
 def exportConfiguration(self, triggerIds=None, notificationIds=None):
     facade = self._getFacade()
     triggers, notifications = facade.exportConfiguration(triggerIds, notificationIds)
     msg = "Exported %d triggers and %d notifications" % (len(triggers), len(notifications))
     audit("UI.TriggerNotification.Export", msg)
     return DirectResponse.succeed(
         triggers=Zuul.marshal(triggers), notifications=Zuul.marshal(notifications), msg=msg
     )
示例#4
0
 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)
示例#5
0
 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))
示例#6
0
    def test_recursion(self):
        data = [TestClass(), TestClass()]
        result = Zuul.marshal(data)
        self.assert_(isinstance(result, list))
        for o in result:
            self.match(o)

        data = {'a':TestClass(), 'b':TestClass()}
        result = Zuul.marshal(data)
        self.assert_(isinstance(result, dict))
        self.assertEqual(sorted(result.keys()), ['a', 'b'])
        for v in result.values():
            self.match(v)
示例#7
0
    def test_recursion_with_keys(self):
        keys = ['foo', '_bar']
        data = [TestClass(), TestClass()]
        result = Zuul.marshal(data, keys=keys)
        self.assert_(isinstance(result, list))
        for o in result:
            self.match(o, keys=keys)

        data = {'a':TestClass(), 'b':TestClass()}
        result = Zuul.marshal(data, keys=keys)
        self.assert_(isinstance(result, dict))
        self.assertEqual(sorted(result.keys()), ['a', 'b'])
        for v in result.values():
            self.match(v, keys=keys)
示例#8
0
    def setInfo(self, **data):
        """
        Main method for setting attributes on a network or network organizer.
        This method accepts any keyword argument for the property that you wish
        to set. The only required property is "uid".

        @type    uid: string
        @keyword uid: Unique identifier of an object
        @rtype: DirectResponse
        """
        network = self.api.getInfo(data['uid'])
        Zuul.unmarshal(data, network)
        audit(['UI', getDisplayType(network), 'Edit'], network, data_=data)
        return DirectResponse.succeed()
示例#9
0
 def manage_events(self, evids=None, excludeIds=None, params=None, uid=None, asof=None, limit=None, timeout=None):
     user = self.context.dmd.ZenUsers.getUserSettings()
     if Zuul.checkPermission(ZEN_MANAGE_EVENTS, self.context):
         return True
     if params.get('excludeNonActionables'):
         return Zuul.checkPermission('ZenCommon', self.context)
     try:
         if uid is not None:
             organizer_name = self.context.dmd.Devices.getOrganizer(uid).getOrganizerName()
         else:
             return self._hasPermissionsForAllEvents(ZEN_MANAGE_EVENTS, evids)
     except (AttributeError, KeyError):
         return False
     manage_events_for = (r.managedObjectName() for r in user.getAllAdminRoles() if r.role in READ_WRITE_ROLES)
     return organizer_name in manage_events_for
示例#10
0
 def getProductData(self, uid, prodname):
     """
     return all extra data for product id
     """
     facade = self._getFacade()
     data = facade.getProductData(uid, prodname)
     return DirectResponse(data=Zuul.marshal(data) )
示例#11
0
    def setInfo(self, **data):
        """
        Set attributes on an object.
        This method accepts any keyword argument for the property that you wish
        to set. The only required property is "uid".

        @type    uid: string
        @keyword uid: Unique identifier of an object
        @rtype:  DirectResponse
        @return: B{Properties}:
            - data: (dictionary) The modified object
        """
        uid = data['uid']
        del data['uid']
        obj = self._getFacade()._getObject(uid)
        passwordFields = self._getPasswordFields(obj)
        oldData = self._getInfoData(obj, data)
        info = self._getFacade().setInfo(uid, data)
        newData = self._getInfoData(obj, data)
        # Trac #29376: Consistently show thresholdType with threshold operations.
        thresholdType = obj.getTypeName() if isinstance(obj, ThresholdClass) else None
        audit(['UI', getDisplayType(obj), 'Edit'], obj, thresholdType=thresholdType,
              data_=newData, oldData_=oldData,
              skipFields_=('newId',), # special case in TemplateFacade.setInfo()
              maskFields_=passwordFields)  
        return DirectResponse.succeed(data=Zuul.marshal(info))
示例#12
0
 def getSequence(self, uid):
     """
     returns the sequence order of keys for a given instance
     """
     facade = self._getFacade()
     data = facade.getSequence(uid)        
     return DirectResponse(data=Zuul.marshal(data) )
示例#13
0
 def _correctReportTitles(self, data):
     data = Zuul.marshal(data)
     # show the context in the report title, otherwise the user
     # has no idea which component the graph is for
     for row in data:
         row['title'] = row['contextTitle']
     return DirectResponse(data=data)
示例#14
0
 def getManufacturerData(self, uid):
     """
     return all extra data for manufacturer id
     """
     facade = self._getFacade()
     data = facade.getManufacturerData(uid)
     return DirectResponse(data=Zuul.marshal(data) ) 
示例#15
0
 def getProductInstances(self, uid, id, params={}):
     """
     return all instances of this product
     """
     facade = self._getFacade()
     data = facade.getProductInstances(uid, id, params)
     return DirectResponse(data=Zuul.marshal(data) )        
示例#16
0
 def getTraps(
         self, uid, dir='ASC', sort='name', start=0, page=None, limit=256):
     count, nodes = self.api.getMibNodes(
         uid=uid, dir=dir, sort=sort, start=start,
         limit=limit, relation='notifications'
     )
     return DirectResponse.succeed(count=count, data=Zuul.marshal(nodes))
示例#17
0
 def getManufacturers(self):
     """
     return all manufacturers
     """
     facade = self._getFacade()
     data = facade.getManufacturers()
     return DirectResponse(data=Zuul.marshal(data))
示例#18
0
    def test_Zuuldotinfo(self):
        isinfo = lambda x:isinstance(x, TargetInfo)

        single = Zuul.info(Target())
        alist = Zuul.info([Target(), Target()])
        adict = Zuul.info({'a':Target(), 'b':Target()})
        nested = Zuul.info([{'a':[Target()], 'b':Target()}])

        self.assert_(isinfo(single))
        self.assert_(isinstance(alist, list))
        for ob in alist:
            self.assert_(isinfo(ob))
        self.assert_(isinstance(adict, dict))
        for k, v in adict.items():
            self.assert_(isinfo(v))
        self.assert_(isinstance(nested, list))
示例#19
0
 def deleteMaintWindow(self, uid, id):
     """
     delete a maintenance window
     """
     facade = self._getFacade()
     data = facade.deleteMaintWindow(uid, id)
     return DirectResponse.succeed(data=Zuul.marshal(data))           
示例#20
0
文件: zep.py 项目: c0ns0le/zenoss-4
    def queryGenerator(self, sort='lastTime', dir='desc', evids=None, excludeIds=None, params=None,
                       archive=False, uid=None, detailFormat=False):
        """
        Query for events.

        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     'lastTime')
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: 'DESC')
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
                       (default: None)
        @type  archive: boolean
        @param archive: (optional) True to search the event archive instead
                        of active events (default: False)
        @type  uid: string
        @param uid: (optional) Context for the query (default: None)
        @rtype:   generator
        @return:  Generator returning events.
        """
        if not self._canViewEvents():
            return
        includeFilter, excludeFilter = self._buildRequestFilters(uid, params, evids, excludeIds)

        events = self.zep.getEventSummariesGenerator(filter=includeFilter, exclude=excludeFilter,
                                                      sort=self._buildSort(sort, dir), archive=archive)
        eventFormat = EventCompatInfo
        if detailFormat:
            eventFormat = EventCompatDetailInfo
        for event in events:
            yield Zuul.marshal(eventFormat(self.context.dmd, event))
 def getTransformTree(self, uid):
     """
     returns a transform for the context with all its inherited transforms
     """
     facade = self._getFacade()
     data = facade.getTransformTree(uid)
     return DirectResponse(data=Zuul.marshal(data) )
示例#22
0
文件: zep.py 项目: c0ns0le/zenoss-4
    def queryArchive(self, page=None, limit=0, start=0, sort='lastTime', dir='desc', params=None, exclusion_filter=None, keys=None, uid=None, detailFormat=False):
        if not self._canViewEvents():
            return DirectResponse.succeed(
                events=[],
                totalCount=0,
                asof=time.time()
                )

        filter = self._buildFilter(uid, params)
        if exclusion_filter is not None:
            exclusion_filter = self._buildFilter(uid, exclusion_filter)
        events = self.zep.getEventSummariesFromArchive(limit=limit, offset=start, sort=self._buildSort(sort, dir),
                                                       filter=filter, exclusion_filter=exclusion_filter)
        eventFormat = EventCompatInfo
        if detailFormat:
            eventFormat = EventCompatDetailInfo

        dmd = self.context.dmd
        # filter out the component and device UUIDs that no longer exist in our system
        evdata = self._filterInvalidUuids(events['events'])
        eventObs = [eventFormat(dmd, e) for e in evdata]
        return DirectResponse.succeed(
            events=Zuul.marshal(eventObs, keys),
            totalCount=events['total'],
            asof=time.time()
        )
示例#23
0
 def deleteUserCommand(self, uid, id):
     """
     delete a user command
     """
     facade = self._getFacade()
     data = facade.deleteUserCommand(uid, id)
     return DirectResponse.succeed(data=Zuul.marshal(data))         
 def getInstanceData(self, uid):
     """
     return all extra data for instance id
     """
     facade = self._getFacade()
     data = facade.getInstanceData(uid)
     return DirectResponse(data=Zuul.marshal(data) )
示例#25
0
    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 getTransform(self, uid):
     """
     returns a transform for the context
     """
     facade = self._getFacade()
     data = facade.getTransform(uid)
     return DirectResponse(data=Zuul.marshal(data) )
示例#27
0
 def getUsers(self, keys=None, start=0, limit=50, page=0,
                 sort='name', dir='ASC', name=None):
     """
     Retrieves a list of users. This method supports pagination.
     @type  start: integer
     @param start: (optional) Offset to return the results from; used in
                   pagination (default: 0)
     @type  name: string
     @param name: (optional) filter to be applied to users returned (default: None)
     @type  limit: integer
     @param limit: (optional) Number of items to return; used in pagination
                   (default: 50)
     @type  sort: string
     @param sort: (optional) Key on which to sort the return results (default:
                  'name')
     @type  dir: string
     @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                 (default: 'ASC')
     @rtype:   DirectResponse
     @return:  B{Properties}:
          - data: (list) Dictionaries of user properties
          - totalCount: (integer) Number of devices returned
     """
     facade = self._getFacade()
     users = facade.getUsers(start=start, limit=limit, sort=sort,
                             dir=dir, name=name)
     total = users.total
     data = Zuul.marshal(users, keys)
     return DirectResponse.succeed(data=data, totalCount=total)
 def getEventsCounts(self, uid):
     """
     return all the event counts for this context
     """
     facade = self._getFacade()
     data = facade.getEventsCounts(uid)
     return DirectResponse(data=Zuul.marshal(data) )
示例#29
0
    def getInstances(self, uid, start=0, params=None, limit=50, sort='name',
                     page=None, dir='ASC'):
        """
        Get a list of instances for a process UID.

        @type  uid: string
        @param uid: Process UID to get instances of
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: 0)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: 50)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     'name')
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: 'ASC')
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - data: ([dictionary]) List of objects representing process instances
             - total: (integer) Total number of instances
        """
        facade = self._getFacade()
        instances = facade.getInstances(uid, start, limit, sort, dir, params)
        keys = ['device', 'monitored', 'pingStatus', 'processName', 'name', 'uid']
        data = Zuul.marshal(instances, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total)
示例#30
0
    def getIpAddresses(self, uid, start=0, params=None, limit=50, sort='ipAddressAsInt',
                       page=None, dir='ASC'):
        """
        Given a subnet, get a list of IP addresses and their relations.

        @type  uid: string
        @param uid: Unique identifier of a subnet
        @type  start: integer
        @param start: Offset to return the results from; used in pagination
        @type  params: string
        @param params: Not used
        @type  limit: integer
        @param limit: Number of items to return; used in pagination
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results;
                     defaults to 'name'
        @type  order: string
        @param order: Sort order; can be either 'ASC' or 'DESC'
        @rtype: DirectResponse
        """
        if isinstance(params, basestring):
            params = unjson(params)
        instances = self.api.getIpAddresses(uid=uid, start=start, params=params,
                                          limit=limit, sort=sort, dir=dir)

        keys = ['name', 'netmask', 'pingstatus', 'snmpstatus', 'uid',
                'device', 'interface', 'macAddress',
                'interfaceDescription', 'manageDevice']
        data = Zuul.marshal(instances.results, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total,
                                      hash=instances.hash_)
示例#31
0
 def test_marshal_explicit(self):
     keys = ('foo', '_bar')
     dct = Zuul.marshal(TestClass(), keys=keys)
     self.match(dct, keys)
示例#32
0
 def getRouterInfo(self, router=None):
     """
     Return information about the router
     """
     data = self._getRouterInfo(router)
     return DirectResponse(data=Zuul.marshal(data))
示例#33
0
 def getGraphConfig(self, string):
     """
     Get graph config from Redis by it's hash
     """
     data = self.redis_tool.load_from_redis(string)
     return DirectResponse.succeed(data=Zuul.marshal({'data': data}))
示例#34
0
 def _getFacade(self):
     return Zuul.getFacade('template', self.context)
示例#35
0
 def _getFacade(self):
     return Zuul.getFacade('eventclasses', self.context)
示例#36
0
 def _getFacade(self):
     return Zuul.getFacade('manufacturers', self.context)
示例#37
0
 def info(f, *args, **kwargs):
     result = f(*args, **kwargs)
     return Zuul.info(result, adapterName=adapterName)
 def afterSetUp(self):
     super(MetricFacadeTest, self).afterSetUp()
     self.facade = Zuul.getFacade('metric', self.dmd)
     self.facade._client = MockRestServiceClient('http://localhost:8888')
示例#39
0
 def _getFacade(self):
     return Zuul.getFacade("network", self.context)
示例#40
0
 def marshal(f, *args, **kwargs):
     result = f(*args, **kwargs)
     return Zuul.marshal(result, keys=keys, marshallerName=marshallerName)
示例#41
0
def info(f, *args, **kwargs):
    """
    Apply Zuul.info to results.
    """
    result = f(*args, **kwargs)
    return Zuul.info(result)
示例#42
0
    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 currentNode.uid == primaryId:
            root = Marshaller(currentNode).marshal(keys)
            root['children'] = children
            return [root]
        return children
示例#43
0
 def _getFacade(self):
     return Zuul.getFacade('search', self.context)
示例#44
0
 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
示例#45
0
    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))
示例#46
0
 def __init__(self, context, request):
     super(BaseApiView, self).__init__(context, request)
     self._appfacade = Zuul.getFacade('applications')
 def getter(self):
     # rather than returning entire object(s), return just the fields
     # required by the UI renderer for creating links.
     return marshal(Zuul.info(getattr(self._object, relationship_name)()),
                    keys=('name', 'meta_type', 'class_label', 'uid'))
示例#48
0
 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)
示例#49
0
 def afterSetUp(self):
     super(MibFacadeTest, self).afterSetUp()
     self.facade = Zuul.getFacade('mibs', self.dmd)
     self.mibName = 'myTestMIB'
     self.mib = self.dmd.Mibs.createMibModule(self.mibName)
示例#50
0
 def __init__(self, context, request):
     super(NetworkRouter, self).__init__(context, request)
     self.api = Zuul.getFacade('network')
示例#51
0
 def getCollectorTemplate(self, id):
     facade = self._getFacade()
     templates = facade.getCollectorTemplate()
     return Zuul.marshal(templates)
示例#52
0
 def _getFacade(self):
     return Zuul.getFacade('process', self.context)
示例#53
0
 def _getFacade(self):
     return Zuul.getFacade('oVirt', self.context)
示例#54
0
 def _getFacade(self):
     return Zuul.getFacade('um', self.context)
示例#55
0
 def _getFacade(self):
     return Zuul.getFacade('network', self.context)
示例#56
0
 def test_unmarshal(self):
     data = {'foo': 42}
     obj = TestClass()
     Zuul.unmarshal(data, obj)
     self.assertEqual(42, obj.foo)
示例#57
0
 def getNotification(self, uid):
     response = self._getFacade().getNotification(uid)
     return DirectResponse.succeed(data=Zuul.marshal(response))
示例#58
0
    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'):

            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)
示例#59
0
def marshal(f, *args, **kwargs):
    result = f(*args, **kwargs)
    return Zuul.marshal(result)
示例#60
0
 def test_marshal_implicit(self):
     dct = Zuul.marshal(TestClass())
     self.match(dct)