Beispiel #1
0
 def getProductsByManufacturer(self, uid, params={}):
     """
     The all the products for this manufacturer
     """
     obj = self._getObject(uid)
     products = [IInfo(i) for i in obj.products.objectValuesAll()]
     prods = []
     filt = params.get('prod_id', "")
     for entry in products:
         if filt.lower() in entry.id.lower():
             prod = obj.products._getOb(entry.id, None)
             prods.append({
                 'id': entry.id,
                 'uid': entry.uid,
                 'key': prod.productKeys,
                 'type': prod.type(),
                 'count': prod.count()
             })
     return prods
 def getDeviceIssues(self):
     zep = getFacade('zep', self._dmd)
     manager = IGUIDManager(self._dmd)
     deviceSeverities = zep.getDeviceIssuesDict()
     zem = self.context.dmd.ZenEventManager
     devdata = []
     # only get the first 100 since this is just the portlet
     for uuid in deviceSeverities.keys()[:100]:
         dev = manager.getObject(uuid)
         if dev and isinstance(dev, Device):
             if (not zem.checkRemotePerm(ZEN_VIEW, dev)
                     or dev.productionState < zem.prodStateDashboardThresh
                     or dev.priority < zem.priorityDashboardThresh):
                 continue
             severities = deviceSeverities[uuid]
             info = IInfo(dev)
             info.setEventSeverities(severities)
             devdata.append(info)
     return devdata
Beispiel #3
0
 def getMibNodes(self,
                 uid,
                 limit=0,
                 start=0,
                 sort='name',
                 dir='DESC',
                 relation='nodes'):
     obj = self._getObject(uid)
     if isinstance(obj, MibOrganizer):
         return 0, []
     functor = getattr(obj, relation, None)
     if functor is None:
         log.warn("Unable to retrieve the relation '%s' from %s", relation,
                  obj.id)
         return 0, []
     all = [IInfo(node) for node in functor()]
     reverse = dir == 'DESC'
     return len(all), sorted(all,
                             key=lambda info: getattr(info, sort),
                             reverse=reverse)[start:limit + start]
    def _getDataSourceInfoFromObject(self, obj):
        """
        Given the obj this returns the correct info. We can not rely on
        adapt for datasources since we need different info objects depending on
        their type not the subclass.

        This defaults to using the adapters to return the correct info if not a datasource.
        """
        info = None

        # look for datasource type
        if isinstance(obj, BasicDataSource):
            if obj.sourcetype == 'SNMP':
                info = SNMPDataSourceInfo(obj)
            if obj.sourcetype == 'COMMAND':
                info = CommandDataSourceInfo(obj)

        # use the default adapter
        if not info:
            info = IInfo(obj)

        return info
Beispiel #5
0
    def getIpAddresses(self,
                       limit=0,
                       start=0,
                       sort='ipAddressAsInt',
                       dir='DESC',
                       params=None,
                       uid=None,
                       criteria=()):
        infos = []
        cat = IModelCatalogTool(self._getObject(uid))
        reverse = dir == 'DESC'

        brains = cat.search("Products.ZenModel.IpAddress.IpAddress",
                            start=start,
                            limit=limit,
                            orderby=sort,
                            reverse=reverse)

        for brain in brains:
            infos.append(IInfo(unbrain(brain)))

        devuuids = set(info.device.uuid for info in infos if info.device)

        # get ping severities
        zep = getFacade('zep')
        pingSeverities = zep.getEventSeverities(devuuids,
                                                severities=(),
                                                status=(),
                                                eventClass=Status_Ping)
        self._assignPingStatuses(infos, pingSeverities)

        # get snmp severities
        snmpSeverities = zep.getEventSeverities(devuuids,
                                                severities=(),
                                                status=(),
                                                eventClass=Status_Snmp)
        self._assignSnmpStatuses(infos, snmpSeverities)

        return SearchResults(infos, brains.total, brains.hash_)
    def addMaintWindow(self, params):
        """
        adds a new Maintenance Window
        """
        newMw = None
        obj = self._getObject(params['uid'])

        id = params['name'].strip()
        if not id:
            raise Exception('Missing Maintenance Window name.')
        if re.compile(r'[^a-zA-Z0-9-_,.$\(\) ]').findall(id):
            raise Exception('`name` contains bad characters. '
                            'Use only a-z, A-Z, 0-9, (, ), $, _, dash, dot '
                            'and whitespace.')
        obj.manage_addMaintenanceWindow(id)
        maintenanceWindows = (IInfo(s) for s in obj.maintenanceWindows())
        try:
            newMw = (x for x in maintenanceWindows if x.id == id).next()
        except StopIteration:
            pass
        if newMw:
            newMw.updateWindow(params)
Beispiel #7
0
    def _buildMetric(self, context, dp, cf, extraRpn="", format=""):
        datasource = dp.datasource()
        dsId = datasource.id
        info = IInfo(dp)

        # find out our aggregation function
        agg = AGGREGATION_MAPPING.get(cf.lower(), cf.lower())
        rateOptions = info.getRateOptions()
        tags = self._buildTagsFromContextAndMetric(context, dsId)
        metricname = dp.name()
        key = self._get_key_from_tags(tags)
        search = _devname_pattern.match(key)
        if search:
            metricname = metrics.ensure_prefix(context.getMetricMetadata(),
                                               metricname)
        name = context.getResourceKey() + "|" + dp.name()
        metric = dict(
            metric=metricname,
            aggregator=agg,
            tags=tags,
            rate=info.rate,
            name=name,
        )
        combined_metric = [metric]
        if rateOptions:
            metric["rateOptions"] = rateOptions
        if extraRpn:
            metric["emit"] = "false"
            metric["name"] = "{}-raw".format(dp.name())
            new_metric = dict(
                expression="rpn:{}-raw,{}".format(dp.name(), extraRpn),
                format=format,
                name=name,
            )
            combined_metric.append(new_metric)
        else:
            metric["format"] = format
        return combined_metric
Beispiel #8
0
 def addWindow(self, contextUid, newId):
     notification = self._getObject(contextUid)
     window = NotificationSubscriptionWindow(newId)
     notification.windows._setObject(newId, window)
     new_window = notification.windows._getOb(newId)
     return IInfo(new_window)
Beispiel #9
0
 def getWindows(self, uid):
     notification = self._getObject(uid)
     for window in notification.windows():
         yield IInfo(window)
Beispiel #10
0
 def addNotification(self, newId, action):
     notification = self.createNotification(newId, action)
     return IInfo(notification)
Beispiel #11
0
 def getInfo(self, uid=None):
     obj = self._getObject(uid)
     return IInfo(obj)
Beispiel #12
0
 def location(self):
     loc = self._object.location()
     if loc:
         info = IInfo(loc)
         return dict(name=info.name, uid=info.uid, uuid=info.uuid)
    def _componentSearch(self,
                         uid=None,
                         types=(),
                         meta_type=(),
                         start=0,
                         limit=None,
                         sort='name',
                         dir='ASC',
                         name=None,
                         keys=()):
        reverse = dir == 'DESC'
        if isinstance(meta_type, basestring) and get_component_field_spec(
                meta_type) is not None:
            brains, total = self._typecatComponentBrains(
                uid, types, meta_type, start, limit, sort, dir, name, keys)
            if brains is not None:
                return self._typecatComponentPostProcess(
                    brains, total, sort, reverse)
        if isinstance(meta_type, basestring):
            meta_type = (meta_type, )
        if isinstance(types, basestring):
            types = (types, )
        querySet = []
        if meta_type:
            querySet.append(Or(*(Eq('meta_type', t) for t in meta_type)))
        querySet.append(Generic('getAllPaths', uid))
        query = And(*querySet)
        obj = self._getObject(uid)

        cat = obj.device().componentSearch
        if 'getAllPaths' not in cat.indexes():
            obj.device()._createComponentSearchPathIndex()
        brains = cat.evalAdvancedQuery(query)

        # unbrain the results
        comps = []
        for brain in brains:
            try:
                comps.append(IInfo(unbrain(brain)))
            except:
                log.warn(
                    'There is broken component "{}" in componentSearch catalog on {} device.'
                    .format(brain.id,
                            obj.device().id))

        # filter the components
        if name is not None:
            comps = self._filterComponents(comps, keys, name)

        total = len(comps)
        hash_ = str(total)

        def componentSortKey(parent):
            val = getattr(parent, sort)
            if val:
                if isinstance(val, list):
                    val = val[0]
                if callable(val):
                    val = val()
                if IInfo.providedBy(val):
                    val = val.name
            return pad_numeric_values_for_indexing(val)

        # sort the components
        sortedResults = list(
            sorted(comps, key=componentSortKey, reverse=reverse))

        # limit the search results to the specified range
        if limit is None:
            pagedResult = sortedResults[start:]
        else:
            pagedResult = sortedResults[start:start + limit]

        # fetch any rrd data necessary
        self.bulkLoadMetricData(pagedResult)

        # Do one big lookup of component events and add to the result objects
        showSeverityIcon = self.context.dmd.UserInterfaceSettings.getInterfaceSettings(
        ).get('showEventSeverityIcons')
        if showSeverityIcon:
            uuids = [r.uuid for r in pagedResult]
            zep = getFacade('zep')
            severities = zep.getWorstSeverity(uuids)
            for r in pagedResult:
                r.setWorstEventSeverity(severities[r.uuid])

        return SearchResults(iter(pagedResult), total, hash_, False)
 def getSoftware(self, uid):
     obj = self._getObject(uid)
     softwares = (IInfo(s) for s in obj.os.software.objectValuesGen())
     return softwares
Beispiel #15
0
 def getCollectors(self, query=None):
     facade = self._getFacade()
     collectors = [IInfo(collector) for collector in facade.query()]
     return DirectResponse.succeed(data=Zuul.marshal(collectors))
 def getNetworks(self):
     root = self._dmd.Networks
     return [IInfo(network) for network in root.getSubNetworks()]
Beispiel #17
0
 def getWindow(self, uid):
     window = self._getObject(uid)
     return IInfo(window)
Beispiel #18
0
 def _getDataPoint(self):
     try:
         return IInfo(self._object.graphDef().rrdTemplate().getRRDDataPoint(
             self._object.dpName))
     except (ConfigurationError, AttributeError):
         return None
    def getNotifications(self):
        self.synchronize()

        user = getSecurityManager().getUser()
        for n in self.notificationPermissions.findNotifications(user, self._getNotificationManager().getChildNodes()):
            yield IInfo(n)
Beispiel #20
0
 def add(self, monitorId, sourceId=None):
     """
     """
     createObject("PerformanceConf", self._perf, monitorId, sourceId)
     monitor = self._perf.get(monitorId)
     return IInfo(monitor)
 def addUser(self, id, password, email, roles):
     propertiedUser = self._root.manage_addUser(id, password, roles)
     user = self._root.getUserSettings(propertiedUser.getId())
     user.email = email
     return IInfo(user)
Beispiel #22
0
 def getGraphDefinition(self, uid):
     obj = self._getObject(uid)
     if not isinstance(obj, GraphDefinition):
         raise Exception('Cannot find GraphDefinition at "%s".' % uid)
     return IInfo(obj)