Beispiel #1
0
 def getSubComponents(self, dmd):
     i = 0
     catalog = ICatalogTool(dmd.Devices)
     COMPONENT = 'Products.ZenModel.DeviceComponent.DeviceComponent'
     query = Eq('monitored', '1')
     for brain in catalog.search(COMPONENT, query=query):
         i += 1
         obj = None
         try:
             obj = brain.getObject()
         except KeyError:
             continue
         dev = obj.device()
         status = obj.getStatus()
         row = (dict(getParentDeviceTitle=obj.getParentDeviceTitle(),
                     hostname=obj.getParentDeviceTitle(),
                     name=obj.name(),
                     meta_type=obj.meta_type,
                     getInstDescription=obj.getInstDescription(),
                     getStatusString=obj.convertStatus(status),
                     getDeviceLink=obj.getDeviceLink(),
                     getPrimaryUrlPath=obj.getPrimaryUrlPath(),
                     cssclass=obj.getStatusCssClass(status),
                     status=status))
         obj._p_invalidate()
         dev._p_invalidate()
         if i % 100 == 0:
             transaction.abort()
         yield Utils.Record(**row)
def _getPercentUtilization( availableReal, totalReal, usedPercent ):
    if usedPercent:
        return usedPercent
    elif totalReal and availableReal:
        return Utils.percent( totalReal - availableReal, totalReal )
    else:
        return None
Beispiel #3
0
def _getPercentUtilization(availableReal, totalReal, usedPercent):
    if usedPercent:
        return usedPercent
    elif totalReal and availableReal:
        return Utils.percent(totalReal - availableReal, totalReal)
    else:
        return None
    def run(self, dmd, args):
        report = []
        for g in dmd.Groups.getSubOrganizers():
	    t_mem = 0
	    t_disk_used = 0
	    t_disk_total = 0
	    t_devices = 0
	    t_cpuspeed = 0
            for d in g.getSubDevices():
		t_mem += self.getMemory(d)
		t_disk_used += self.getDiskSpaceUsed(d)
		t_disk_total += self.getDiskSpaceTotal(d)
		t_devices += 1
		t_cpuspeed += self.getCPUSpeed(d)
	    t_disk_used = int(t_disk_used / 1024 / 1024 / 1024)
	    t_disk_total = int(t_disk_total / 1024 / 1024 / 1024)
	    t_mem = int(t_mem / 1024 / 1024)
	    report.append(
		Utils.Record(
		    group = g,
		    groupname = g.getOrganizerName(),
		    tmem = t_mem,
		    tdiskused = t_disk_used,
		    tdisktotal = t_disk_total,
		    tcpuspeed = t_cpuspeed,
		    tdevices = t_devices
		)
	    )
        return report
Beispiel #5
0
 def run(self, dmd, args):
     report = []
     recordCount = 0
     for m in dmd.Manufacturers.objectValues():
         if m.id == 'Unknown' or m.meta_type != 'Manufacturer': continue
         for p in m.products.objectValues():
             if p.meta_type == 'SoftwareClass':
                 c = 0
                 for i in p.instances():
                     try:
                         if dmd.checkRemotePerm('View', i.device()):
                             c += 1
                     except Exception:
                         continue
                     i._p_invalidate()
                 if c == 0: continue
                 report.append(
                     Utils.Record(manufLink=m.getIdLink(),
                                  manufId=m.id,
                                  softLink=p.getIdLink(),
                                  softId=p.id,
                                  count=c))
             p._p_invalidate()
         m._p_invalidate()
         recordCount += 1
         if recordCount % 100 == 0:
             transaction.abort()
     return report
Beispiel #6
0
    def run(self, dmd, args):
        """
    Generate the report using custom filter
    """

        report = []
        #    log.info('invoking InstalledSoftware report')
        # Filter the device list down according to the
        # values from the filter widget
        for device in self.filteredDevices(dmd, args):
            yield Utils.Record(device=device)
    def _createRecord(self,
                      device,
                      component=None,
                      columnDatapointsMap={},
                      summary={},
                      templateArgs=None):
        """
        Creates a record for the given row context
        (that is, the device and/or component)

        @param device: the device for this row
        @param component: the (optional) component for this row
        @param columnDatapointsMap: a dict of Column objects to
                                    alias-datapoint pairs.  The first
                                    datapoint that gives a value for
                                    the context will be used.
        @param summary: a dict of report parameters like start date,
                        end date, and rrd summary function
        @param templateArgs the template tags from the ui

        @rtype L{Utils.Record}
        """
        def localGetValue(device, component, extra):
            try:
                return column.getValue(device, component, extra=extra)
            except (TypeError, NameError):
                return None

        columnValueMap = {}
        for column, aliasDatapointPairs in columnDatapointsMap.iteritems():
            columnName = column.getColumnName()
            extra = dict(aliasDatapointPairs=aliasDatapointPairs,
                         summary=summary,
                         templateArgs=templateArgs)
            value = localGetValue(device, component, extra)
            columnValueMap[columnName] = value

        # The composite columns cannot be RRD columns, because we do
        # not pass datapoints.
        extra = dict(summary=summary)
        extra.update(columnValueMap)
        for column in self.getCompositeColumns():
            columnName = column.getColumnName()
            value = localGetValue(device, component, extra)
            columnValueMap[columnName] = value
            extra.update({columnName: value})

        return Utils.Record(device=device,
                            component=component,
                            **columnValueMap)
    def run(self, dmd, args):
        report = []
        for device in dmd.Devices.getSubDevicesGen():
            report.append(
                Utils.Record(
                    device=device.titleOrId(),
                    ip=device.manageIp,
                    hardware="%s %s" % (device.hw.getManufacturerName(),
                                        device.hw.getProductName()),
                    software="%s %s" % (device.os.getManufacturerName(),
                                        device.os.getProductName()),
                ))

        return report
    def run(self, dmd, args):
        report = []
        zem = dmd.ZenEventManager
        windows_class = None

        # Guard against people removing the /Server/Windows device class.
        try:
            windows_class = dmd.getObjByPath('Devices/Server/Windows')
        except KeyError:
            return []

        for d in windows_class.getSubDevices():
            if "MSExchangeIS" not in d.zDeviceTemplates: continue
            if not d.monitorDevice(): continue

            availability = d.availability()
            uptime = d.sysUpTime()
            uptime_string = "unknown"
            if uptime and uptime != -1:
                uptime = uptime / 100
                uptime_string = Time.Duration(uptime)
            else:
                uptime = None

            r = Utils.Record(
                device=d.titleOrId(),
                deviceUrl=d.getPrimaryUrlPath(),
                availability=float(availability),
                availability_string=str(availability),
                uptime=uptime,
                uptime_string=uptime_string,
                )

            for winservice in self.winservices:
                ws = getattr(d.os.winservices, winservice, None)
                if ws:
                    r.values[winservice] = ws.getStatusString(
                        '/Status/WinService')

                    r.values[winservice+'_img'] = d.getStatusImgSrc(
                        ws.getStatus())

            report.append(r)

        return report
 def getSubComponents(self, dmd):
     catalog = IModelCatalogTool(dmd.Devices)
     COMPONENT = 'Products.ZenModel.DeviceComponent.DeviceComponent'
     query = Eq('monitored', '1')
     with gc_cache_every(100, db=dmd._p_jar._db):
         for brain in catalog.search(COMPONENT, query=query):
             try:
                 obj = brain.getObject()
             except KeyError:
                 continue
             status = obj.getStatus()
             row = (dict(getParentDeviceTitle=obj.getParentDeviceTitle(),
                         hostname=obj.getParentDeviceTitle(),
                         name=obj.name(),
                         meta_type=obj.meta_type,
                         getInstDescription=obj.getInstDescription(),
                         getStatusString=obj.convertStatus(status),
                         getDeviceLink=obj.getDeviceLink(),
                         getPrimaryUrlPath=obj.getPrimaryUrlPath(),
                         cssclass=obj.getStatusCssClass(status),
                         status=status))
             yield Utils.Record(**row)
Beispiel #11
0
    def run(self, dmd, args):
        summary = Utilization.getSummaryArgs(dmd, args)
        deviceClass = args.get('deviceClass', '/Server')
        organizer = deviceClass
        showAll = args.get('showAll', '') == "on"
        deviceFilter = args.get('deviceFilter', '')
        deviceMatch = re.compile('.*%s.*' % deviceFilter)

        report = []
        if deviceClass == '/': return []

        parts = organizer.lstrip('/').split('/')
        try:
            if not len(parts):
                raise AttributeError()  # Invalid organizer
            root = dmd.getDmdRoot(parts[0])
            for part in parts[1:]:
                root = getattr(root, part)
        except AttributeError:
            root = dmd.Devices

        for org in [
                root,
        ] + root.getSubOrganizers():
            path = org.getPrimaryUrlPath()
            for devObj in org.getDevices():
                devObj = devObj.primaryAq()
                if not deviceMatch.match(devObj.id): continue
                types = getattr(org, 'zPerfReportableMetaTypes',
                                ['IpInterface'])
                avePeriod = getattr(org, 'zPerfReportableAvePeriod', 86400)
                fullComponentList = []
                for typeEntry in types:
                    fullComponentList = fullComponentList + devObj.getMonitoredComponents(
                        type=str(typeEntry))
                for intObj in fullComponentList:
                    if not showAll:
                        if intObj.snmpIgnore(): continue
                        isLocal = re.compile(devObj.zLocalInterfaceNames)
                        if isLocal.match(intObj.name()): continue
                        if not intObj.speed:
                            speed = 'Unknown'
                        else:
                            speed = intObj.speed

                        counters = [
                            'ifHCInOctets', 'ifHCOutOctets', 'ifInOctets',
                            'ifOutOctets'
                        ]

                        def multiply(number, by):
                            if number is None or by is None:
                                return None
                            return number * by

                        aveVals = getRRDValues(intObj,
                                               dsNames=counters,
                                               operation='AVERAGE',
                                               **summary)
                        volAveIn = multiply(
                            aveVals.get('ifHCInOctets',
                                        aveVals.get('ifInOctets', None)),
                            avePeriod)
                        volAveOut = multiply(
                            aveVals.get('ifHCOutOctets',
                                        aveVals.get('ifOutOctets', None)),
                            avePeriod)

                        totalVals = getRRDValues(intObj,
                                                 counters,
                                                 operation='TOTAL',
                                                 **summary)
                        volIn = totalVals.get(
                            'ifHCInOctets', totalVals.get('ifInOctets', None))
                        volOut = totalVals.get(
                            'ifHCOutOctets',
                            totalVals.get('ifOutOctets', None))

                        if volAveOut and volAveIn:
                            volTotal = volOut + volIn
                        else:
                            volTotal = 0

                        record = Utils.Record(
                            device=devObj.id,
                            devicePath=devObj.getPrimaryUrlPath(),
                            id=intObj.id,
                            path=intObj.getPrimaryUrlPath(),
                            description=intObj.description,
                            speed=speed,
                            volIn=volIn,
                            volOut=volOut,
                            volAveIn=volAveIn,
                            volAveOut=volAveOut,
                            volTotal=volTotal)
                        report.append(record)
        return report
Beispiel #12
0
    def run(self, dmd, args):
        now = time.time()
        zep = getFacade("zep", dmd)

        # read in args
        dateAsFloat(args, 'startDate', Availability.getDefaultAvailabilityStart(dmd))
        dateAsFloat(args, 'endDate', Availability.getDefaultAvailabilityEnd())
        args['eventClass'] = args.get('eventClass', '') or '/Perf'

        startDate = min(args['startDate'], now)
        endDate = min(args['endDate'], now)
        startDate = getBeginningOfDay(startDate)
        endDate = getEndOfDay(endDate)
        if endDate <= startDate:
            return []

        # convert start and end date to integer milliseconds for defining filters
        startDate = int(startDate*1000)
        endDate = int(endDate*1000)

        # compose filter for retrieval from ZEP
        create_filter_args = {
            'severity' : _severityGreaterThanOrEqual(SEVERITY_WARNING),
            'event_class' : args['eventClass'] +
                            ('/' if not args['eventClass'].endswith('/') else ''),
            'first_seen' : (0,endDate),
            'last_seen' : (startDate,),
            }
        event_filter = zep.createEventFilter(**create_filter_args)
        events = zep.getEventSummariesGenerator(event_filter)
        events_from_archive = zep.getEventSummariesGenerator(event_filter, archive=True)

        sum = defaultdict(int)
        counts = defaultdict(int)
        for evtsumm in chain(events, events_from_archive):

            first = evtsumm['first_seen_time']
            # if event is still open, downtime persists til end of report window
            if evtsumm['status'] not in CLOSED_EVENT_STATUSES:
                last = endDate
            else:
                last = evtsumm['status_change_time']

            # clip first and last within report time window
            first = max(first, startDate)
            last = min(last, endDate)

            # discard any events that have no elapsed time
            if first == last:
                continue

            # extract key fields, and update time/count tallies
            evt = evtsumm['occurrence'][0]
            evt_actor = evt['actor']
            device = evt_actor.get('element_identifier')
            component = evt_actor.get('element_sub_identifier')
            eventClass = evt['event_class']

            diff = last - first
            sum[(device, component, eventClass)] += diff
            counts[(device, component, eventClass)] += 1


        # Look up objects that correspond to the names
        report = []
        find = dmd.Devices.findDevice
        totalTime = endDate - startDate
        for k, seconds in sum.items():
            deviceName, componentName, eventClassName = k
            deviceLink = deviceName
            component = None
            componentLink = componentName
            eventClass = None
            eventClassLink = eventClassName
            device = find(deviceName)
            if not device or not dmd.checkRemotePerm('View', device): continue
            deviceLink = device.urlLink()
            if componentName:
                for c in device.getMonitoredComponents():
                    if c.name().find(componentName) >= 0:
                        component = c
                        componentLink = c.urlLink()
                        break
            # get some values useful for the report
            duration = Duration(seconds/1000)
            percent = seconds * 100. / totalTime
            try:
                eventClass = dmd.Events.getOrganizer(eventClassName)
                eventClassLink = eventClass.urlLink()
            except KeyError:
                pass
            report.append(Utils.Record(
                deviceName=deviceName,
                deviceLink=deviceLink,
                componentName=componentName,
                componentLink=componentLink,
                eventClassName=eventClassName,
                eventClassLink=eventClassLink,
                count=counts.get(k, 1),
                seconds=seconds,
                percentTime=percent,
                duration=duration))

        return report