Exemplo n.º 1
0
    def __init__(self,
                 deviceId,
                 taskName,
                 scheduleIntervalSeconds,
                 taskConfig,
                 clientName=DEFAULT_JMX_JAVA_CLIENT_NAME ):

        super( ZenJMXTask, self ).__init__()
        self.name = taskName
        self.configId = deviceId
        self.state = TaskStates.STATE_IDLE
        
        self._taskConfig = taskConfig
        self._manageIp = self._taskConfig.manageIp

        self._dataService = zope.component.queryUtility( IDataService )
        self._eventService = zope.component.queryUtility( IEventService )
        self._preferences = zope.component.queryUtility( ICollectorPreferences,
                                                         'zenjmx' )
        self._client = zope.component.queryUtility( IZenJMXJavaClient,
                                                    clientName )

        # At this time, do not use the interval passed from the device
        # configuration.  Use the value pulled from the daemon
        # configuration.
        unused( scheduleIntervalSeconds )
        self.interval = self._preferences.options.cycleInterval
 def checkRaw(self, dataPoint, timeOf, value):
     """A new datapoint has been collected, use the given _raw_
     value to re-evalue the threshold.
     returns a sequence of events.
     """
     unused(timeOf, value)
     return self.check([dataPoint])
Exemplo n.º 3
0
 def getRRDCreateCommand(self, performanceConf):
     """Get the create command.
     Return '' for the default from performanceConf"""
     unused(performanceConf)
     if self.createCmd:
         return self.createCmd
     return ''
Exemplo n.º 4
0
 def objectItems(self, spec=None):
     """
     ToManyRelationship doesn't publish objectItems to prevent
     zope recursion problems.
     """
     unused(spec)
     return []
 def countDevices(self, devrel="devices"):
     """count all devices with in a device group"""
     unused(devrel)
     count = self.devices.countObjects()
     for group in self.children():
         count += group.countDevices()
     return count
 def getGraphCmds(self, cmds, context, rrdDir, addSummary, idx, 
                     multiid=-1, prefix=''):
     ''' Build the graphing commands for this graphpoint
     '''
     from Products.ZenUtils.Utils import unused
     unused(cmds, context, rrdDir, addSummary, idx, multiid, prefix)
     return cmds + ['COMMENT:%s' % self.text.replace(':', '\:')]
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        pointval = self.pointval
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                pointval = rpneval(pointval, rpn)
            except:
                pointval= 0
                self.raiseRPNExc()

        result = []
        if pointval:
            result += [ "COMMENT:%s(%s)\\j" % (self.SeverityString , pointval),
                ]
        log.warn(gopts + result)
        return gopts + result
Exemplo n.º 8
0
 def _getDeviceBatch(self, selectstatus='none', goodevids=[],
                    badevids=[], offset=0, count=50, filter='',
                    orderby='titleOrId', orderdir='asc'):
     unused(count, offset, orderby, orderdir)
     if not isinstance(goodevids, (list, tuple)):
         goodevids = [goodevids]
     if not isinstance(badevids, (list, tuple)):
         badevids = [badevids]
     if selectstatus=='all':
         idquery = ~In('id', badevids)
     else:
         idquery = In('id', goodevids)
     filter = '(?is).*%s.*' % filter
     filterquery = Or(
         MatchRegexp('id', filter),
         MatchRegexp('titleOrId', filter),
         MatchRegexp('getDeviceIp', filter),
         MatchRegexp('getProdState', filter),
         MatchRegexp('getDeviceClassPath', filter)
     )
     query = Eq('getPhysicalPath', self.context.absolute_url_path()) & idquery
     query = query & filterquery
     catalog = getattr(self.context, self.context.default_catalog)
     objects = catalog.evalAdvancedQuery(query)
     return [x['id'] for x in objects]
 def manage_editOSProcessClass(self,
                               name="",
                               zMonitor=True, 
                               zAlertOnRestart=False,
                               zFailSeverity=3,
                               regex="",
                               description="",
                               ignoreParametersWhenModeling=False,
                               ignoreParameters=False,
                               REQUEST=None):
                              
     """
     Edit a ProductClass from a web page.
     """
     from Products.ZenUtils.Utils import unused
     unused(zAlertOnRestart, zFailSeverity, zMonitor)
     # Left in name, added title for consistency
     self.title = name
     self.name = name
     id = self.prepId(name)
     redirect = self.rename(id)
     self.regex = regex        
     self.description = description
     self.ignoreParametersWhenModeling = ignoreParametersWhenModeling
     self.ignoreParameters = ignoreParameters
     if REQUEST:
         from Products.ZenUtils.Time import SaveMessage
         messaging.IMessageSender(self).sendToBrowser(
             'Product Class Saved',
             SaveMessage()
         )
         return self.callZenScreen(REQUEST, redirect)
Exemplo n.º 10
0
    def loadObjectFromXML(self, objstack=None, xmlfile=""):
        """This method can be used to load data for the root of Zenoss (default
        behavior) or it can be used to operate on a specific point in the
        Zenoss hierarchy (ZODB).

        Upon loading the XML file to be processed, the content of the XML file
        is handled (processed) by the methods in this class.
        """
        from Products.ZenUtils.Utils import unused

        unused(objstack)
        if xmlfile:
            # check to see if we're getting the XML from a URL ...
            schema, host, path, null, null, null = urlparse(xmlfile)
            if schema and host:
                self.infile = urllib2.urlopen(xmlfile)
            # ... or from a file on the file system
            else:
                self.infile = open(xmlfile)
        elif self.options.infile:
            self.infile = open(self.options.infile)
        else:
            self.infile = sys.stdin
        self.doc = parse(self.infile)
        self.handleDevices()
        self.doc.unlink()
        self.infile.close()
Exemplo n.º 11
0
 def getGraphCmds(self, cmds, context, rrdDir, addSummary, idx, 
                 multiid=-1, prefix=''):
     ''' Build the graphing commands for this graphpoint
     '''
     from Products.ZenUtils.Utils import unused
     unused(multiid, prefix, rrdDir)
     return cmds
    def wrapper(*args, **kwargs):
        try:
            import ZenPacks.zenoss.Impact
            unused(ZenPacks.zenoss.Impact)
        except ImportError:
            return

        return f(*args, **kwargs)
Exemplo n.º 13
0
    def remote_updateDeviceList(self, devices):
        """
        Callable from zenhub.

        @param devices: list of devices (unused)
        @type devices: list
        """
        unused(devices)
        self.log.debug("Async update of device list")
Exemplo n.º 14
0
 def redirectToUserCommands(self, REQUEST, commandId=None):
     ''' Redirect to the page which lists UserCommands
     for this Commandable object.
     '''
     unused(commandId)
     url = self.getUrlForUserCommands()
     if url:
         return REQUEST.RESPONSE.redirect(url)
     return self.callZenScreen(REQUEST)
Exemplo n.º 15
0
 def _getOb(self, id, default=zenmarker):
     """
     Return object by id if it exists on this relationship.
     If it doesn't exist return default or if default is not set
     raise AttributeError
     """
     unused(default)
     if True:
         raise NotImplementedError
Exemplo n.º 16
0
 def manage_addAdministrativeRole(self, name=None, type='device', role=None,
                                  guid=None, uid=None, REQUEST=None):
     "Add a Admin Role to the passed object"
     unused(role)
     mobj = None
     if guid or uid:
         # look up our object by either guid or uid
         if guid:
             manager = IGUIDManager(self.dmd)
             mobj = manager.getObject(guid)
         elif uid:
             mobj = self.unrestrictedTraverse(uid)
     else:
         # use magic to look up our object
         if not name:
             name = REQUEST.deviceName
         if type == 'device':
             mobj =self.getDmdRoot("Devices").findDevice(name)
         else:
             try:
                 root = type.capitalize()+'s'
                 if type == "deviceClass":
                     mobj = self.getDmdRoot("Devices").getOrganizer(name)
                 else:
                     mobj = self.getDmdRoot(root).getOrganizer(name)
             except KeyError: pass
     if not mobj:
         if REQUEST:
             messaging.IMessageSender(self).sendToBrowser(
                 'Error',
                 "%s %s not found"%(type.capitalize(),name),
                 priority=messaging.WARNING
             )
             return self.callZenScreen(REQUEST)
         else: return
     roleNames = [ r.id for r in mobj.adminRoles() ]
     if self.id in roleNames:
         if REQUEST:
             messaging.IMessageSender(self).sendToBrowser(
                 'Error',
                 (("Administrative Role for %s %s "
                  "for user %s already exists.") % (type, name, self.id)),
                 priority=messaging.WARNING
             )
             return self.callZenScreen(REQUEST)
         else: return
     mobj.manage_addAdministrativeRole(self.id)
     if REQUEST:
         messaging.IMessageSender(self).sendToBrowser(
             'Role Added',
             ("Administrative Role for %s %s for user %s added" %
                 (type, name, self.id))
         )
         audit('UI.User.AddAdministrativeRole', username=self.id,
               data_={mobj.meta_type:mobj.getPrimaryId()})
         return self.callZenScreen(REQUEST)
Exemplo n.º 17
0
 def children(self, sort=False, checkPerm=True, spec=None):
     ''' Return all objects that are instances of ReportClass
     '''
     unused(spec)
     kids = [o for o in self.objectValues() if isinstance(o, ReportClass)]
     if checkPerm:
         kids = [kid for kid in kids if self.checkRemotePerm("View", kid)]
     if sort: 
         kids.sort(key=lambda x: x.primarySortKey())
     return kids
 def check(self, dataPoints):
     """The given datapoints have been updated, so re-evaluate.
     returns events or an empty sequence"""
     unused(dataPoints)
     result = []
     for dp in self.dataPointNames:
         cycleTime, rrdType = self._getRRDType(dp)
         result.extend(self._checkImpl(
             dp, self._fetchLastValue(dp, cycleTime)))
     return result
 def check(self, dataPoints):
     """The given datapoints have been updated, so re-evaluate.
     returns events or an empty sequence"""
     unused(dataPoints)
     result = []
     for dp in self.dataPointNames:
         cycleTime, rrdType = self.rrdInfoCache(dp)
         result.extend(self.checkDuration(
             dp, self.fetchValuesList(dp, self.interval)))
     return result
 def check(self, dataPoint):
     """The given datapoints have been updated, so re-evaluate.
     returns events or an empty sequence"""
     unused(dataPoint)
     result = []
     for dp in self.dataPointNames:
         cycleTime, rrdType = self.rrdInfoCache(dp)
         result.extend(self.checkStatus(
             dp, self.fetchLastValue(dp, cycleTime)))
     return result
 def getGraphCmds(self, cmds, context, rrdDir, addSummary, idx, 
                     multiid=-1, prefix=''):
     ''' Build the graphing commands for this graphpoint
     '''
     from Products.ZenUtils.Utils import unused
     unused(multiid, rrdDir)
     return cmds + ['PRINT:%s:%s%s' % (
                 self.addPrefix(prefix, self.vname),
                 (self.format or self.DEFAULT_FORMAT).replace(':', '\:'),
                 self.strftime and ':%s' % self.strftime or '')]
Exemplo n.º 22
0
 def _delObject(self, id, dp=1, suppress_events=False):
     """Emulate ObjectManager deletetion."""
     unused(dp)
     obj = self._getOb(id, False)
     if not obj:
         log.warning(
         "Tried to delete object id '%s' but didn't find it on %s",
         id, self.getPrimaryId())
         return
     self.removeRelation(obj, suppress_events)
     obj.__primary_parent__ = None
Exemplo n.º 23
0
 def getGraphCmds(self, cmds, context, rrdDir, addSummary, idx,
                     multiid=-1, prefix=''):
     ''' Build the graphing commands for this graphpoint
     '''
     from Products.ZenUtils.Utils import unused
     unused(rrdDir)
     if not self.rpn:
         return cmds
     rpn = self.talesEval(self.rpn, context)
     return cmds + ['CDEF:%s=%s' % (
                     self.getDsName(self.id, multiid, prefix),
                     self.getRpn(multiid, prefix))]
Exemplo n.º 24
0
    def enrich(self, event, subject):
        """
        Sanitize the event facility and severity fields.

        @param event: event
        @type event: simple class
        @param subject: e-mail subject (unused)
        @type subject: string
        """
        unused(subject)
        event.facility = "unknown"
        event.severity = self.eventSeverity
Exemplo n.º 25
0
    def clientConnectionFailed(self, connector, reason):
        """
        If we don't connect let the modeler know

        @param connector: unused (unused)
        @type connector: unused
        @param reason: error message to report
        @type reason: string
        """
        unused(connector)
        log.warn(reason.getErrorMessage())
        self.clientFinished()
Exemplo n.º 26
0
def _load_modules():
    # Due to the manipulation of sys.path during the loading of plugins,
    # we can get ObjectMap imported both as DataMaps.ObjectMap and the
    # full-path from Products.  The following gets the class registered
    # with the jelly serialization engine under both names:
    #  1st: get Products.DataCollector.plugins.DataMaps.ObjectMap
    from Products.DataCollector.plugins.DataMaps import ObjectMap
    #  2nd: get DataMaps.ObjectMap
    sys.path.insert(0, zenPath('Products', 'DataCollector', 'plugins'))
    import DataMaps

    unused(DataMaps, ObjectMap)
 def getGraphCmds(self, cmds, context, rrdDir, addSummary, idx, 
                     multiid=-1, prefix=''):
     ''' Build the graphing commands for this graphpoint
     '''
     from Products.ZenUtils.Utils import unused
     unused(multiid, prefix, rrdDir)
     legend = self.talesEval(self.legend, context)
     legend = self.escapeForRRD(legend)
     return cmds + ['HRULE:%s%s%s' % (
                 self.value or 0,
                 self.getColor(idx),
                 legend and ':%s' % legend or '')]
Exemplo n.º 28
0
def manage_addCollectionItem(context, id, deviceId, compPath, sequence,
                                                            REQUEST = None):
    ''' This is here so than zope will let us copy/paste/rename
    CollectionItems.
    '''
    unused(deviceId, compPath, sequence)
    ci = CollectionItem(id)
    context._setObject(id, ci)
    ci.deviceId = deviceId
    ci.compPath = compPath
    ci.sequence = sequence
    if REQUEST is not None:
        return REQUEST['RESPONSE'].redirect(context.absolute_url_path() +'/manage_main') 
Exemplo n.º 29
0
 def getAllCounts(self, devrel=None):
     """Count all devices within a device group and get the
     ping and snmp counts as well"""
     unused(devrel)
     counts = [
         self.ipaddresses.countObjects(),
         self._status("Ping", "ipaddresses"),
         self._status("Snmp", "ipaddresses"),
     ]
     for group in self.children():
         sc = group.getAllCounts()
         for i in range(3): counts[i] += sc[i]
     return counts
Exemplo n.º 30
0
 def _startMaintenance(self, ignored=None):
     unused(ignored)
     if not self.options.cycle:
         self._maintenanceCycle()
         return
     if self.options.logTaskStats > 0:
         log.debug("Starting Task Stat logging")
         loop = task.LoopingCall(self._displayStatistics, verbose=True)
         loop.start(self.options.logTaskStats, now=False)
     interval = self.preferences.cycleInterval
     self.log.debug("Initializing maintenance Cycle")
     maintenanceCycle = MaintenanceCycle(interval, self, self._maintenanceCycle)
     maintenanceCycle.start()
Exemplo n.º 31
0
 def __init__(self, id, title=None, buildRelations=True):
     unused(title)
     self.id = id
     if buildRelations: self.buildRelations()
Exemplo n.º 32
0
                                             IEventService,\
                                             IScheduledTask
from Products.ZenCollector.tasks import SimpleTaskFactory,\
                                        SimpleTaskSplitter,\
                                        TaskStates, \
                                        BaseTask

from Products.ZenEvents.ZenEventClasses import Status_Snmp
from Products.ZenEvents import Event

# We retrieve our configuration data remotely via a Twisted PerspectiveBroker
# connection. To do so, we need to import the class that will be used by the
# configuration service to send the data over, i.e. SnmpDeviceProxy.
from Products.ZenUtils.Utils import unused
from Products.ZenHub.services.SnmpPerformanceConfig import SnmpDeviceProxy
unused(SnmpDeviceProxy)
from Products.ZenHub.services.PerformanceConfig import SnmpConnInfo
unused(SnmpConnInfo)

COLLECTOR_NAME = "zenperfsnmp"
MAX_BACK_OFF_MINUTES = 20


class SnmpPerformanceCollectionPreferences(object):
    zope.interface.implements(ICollectorPreferences)

    def __init__(self):
        """
        Constructs a new SnmpPerformanceCollectionPreferences instance and
        provides default values for needed attributes.
        """
from Products.ZenCollector.daemon import CollectorDaemon
from Products.ZenCollector.interfaces \
    import ICollectorPreferences, IScheduledTask, IEventService, IDataService

from Products.ZenCollector.tasks \
    import SimpleTaskFactory, SimpleTaskSplitter, TaskStates

from Products.ZenUtils.observable import ObservableMixin

from Products.ZenUtils.Utils import unused

from ZenPacks.itri.PowerConsumptionMonitor.services.PowerMonConfigService \
    import PowerMonConfigService

unused(Globals)
unused(PowerMonConfigService)

from Products.ZenEvents.ZenEventClasses import Error, Clear, Critical

class ZenPowerConsumptionMonitorPreferences(object):
    zope.interface.implements(ICollectorPreferences)

    def __init__(self):
        self.collectorName = 'powercond'
        self.configurationService = \
            "ZenPacks.itri.PowerConsumptionMonitor.services.PowerMonConfigService"

        # How often the daemon will collect each device. Specified in seconds.
        self.cycleInterval = 1 * 60
Exemplo n.º 34
0
 def buildOptions(self, parser):
     unused(self, parser)
     pass
Exemplo n.º 35
0
 def __init__(self, noopts=0, app=None, keeproot=False):
     ZenDaemon.__init__(self, noopts, keeproot)
     unused(app)
     self.opendb()
     self.openconn = self.getPoolSize()
Exemplo n.º 36
0
    def generate_xml_table(self, parser, options):
        """
        Create a Docbook table based on the long-form of the option names

        @parameter parser: an optparse parser object which contains defaults, help
        @parameter options: parsed options list containing actual values
        """

        #
        # Header for the configuration file
        #
        unused(options)
        daemon_name = os.path.basename(sys.argv[0])
        daemon_name = daemon_name.replace('.py', '')

        print """<?xml version="1.0" encoding="UTF-8"?>

<section version="4.0" xmlns="http://docbook.org/ns/docbook"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:xi="http://www.w3.org/2001/XInclude"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns:mml="http://www.w3.org/1998/Math/MathML"
   xmlns:html="http://www.w3.org/1999/xhtml"
   xmlns:db="http://docbook.org/ns/docbook"

  xml:id="%s.options"
>

<title>%s Options</title>
<para />
<table frame="all">
  <caption>%s <indexterm><primary>Daemons</primary><secondary>%s</secondary></indexterm> options</caption>
<tgroup cols="2">
<colspec colname="option" colwidth="1*" />
<colspec colname="description" colwidth="2*" />
<thead>
<row>
<entry> <para>Option</para> </entry>
<entry> <para>Description</para> </entry>
</row>
</thead>
<tbody>
""" % (daemon_name, daemon_name, daemon_name, daemon_name)

        options_to_ignore = ('help', 'version', '', 'genconf', 'genxmltable')

        #
        # Create an entry for each of the command line flags
        #
        # NB: Ideally, this should print out only the option parser dest
        #     entries, rather than the command line options.
        #
        import re
        for opt in getAllParserOptionsGen(parser):
            if opt.help is SUPPRESS_HELP:
                continue

            #
            # Create a Docbook-happy version of the option strings
            # Yes, <arg></arg> would be better semantically, but the output
            # just looks goofy in a table.  Use literal instead.
            #
            all_options = '<literal>' + re.sub(
                r'/', '</literal>,</para> <para><literal>',
                "%s" % opt) + '</literal>'

            #
            # Don't display anything we shouldn't be displaying
            #
            option_name = re.sub(r'.*/--', '', "%s" % opt)
            option_name = re.sub(r'^--', '', "%s" % option_name)
            if option_name in options_to_ignore:
                continue

            default_value = parser.defaults.get(opt.dest)
            if default_value is NO_DEFAULT or default_value is None:
                default_value = ""
            default_string = ""
            if default_value != "":
                default_string = "<para> Default: <literal>" + str(
                    default_value) + "</literal></para>\n"

            comment = self.pretty_print_config_comment(opt.help)

            #
            # TODO: Determine the variable name used and display the --option_name=variable_name
            #
            if opt.action in ['store_true', 'store_false']:
                print """<row>
<entry> <para>%s</para> </entry>
<entry>
<para>%s</para>
%s</entry>
</row>
""" % (all_options, comment, default_string)

            else:
                target = '=<replaceable>' + opt.dest.lower() + '</replaceable>'
                all_options = all_options + target
                all_options = re.sub(r',', target + ',', all_options)
                print """<row>
<entry> <para>%s</para> </entry>
<entry>
<para>%s</para>
%s</entry>
</row>
""" % (all_options, comment, default_string)

        #
        # Close the table elements
        #
        print """</tbody></tgroup>
</table>
<para />
</section>
"""
        sys.exit(0)
Exemplo n.º 37
0
# License.zenoss under the directory where your Zenoss product is installed.
#
##############################################################################

import Globals
from Products.DataCollector.Plugins import loadPlugins
from Products.ZenHub import PB_PORT
from Products.ZenHub.zenhub import LastCallReturnValue
from Products.ZenHub.PBDaemon import translateError, RemoteConflictError
from Products.ZenUtils.Time import isoDateTime
from Products.ZenUtils.ZCmdBase import ZCmdBase
from Products.ZenUtils.Utils import unused, zenPath
from Products.ZenUtils.PBUtil import ReconnectingPBClientFactory
# required to allow modeling with zenhubworker
from Products.DataCollector.plugins import DataMaps
unused(DataMaps)

from twisted.cred import credentials
from twisted.spread import pb
from twisted.internet import defer, reactor, error
from ZODB.POSException import ConflictError
from collections import defaultdict

import cPickle as pickle
import time
import signal
import os

IDLE = "None/None"

Exemplo n.º 38
0
 def _setOb(self, id, obj):
     """don't use attributes in relations"""
     unused(id)
     unused(obj)
     if True:
         raise NotImplementedError
Exemplo n.º 39
0
 def snmpStatus(self, devrel=None):
     """aggregate snmp status for all devices in this group and below"""
     unused(devrel)
     return DeviceOrganizer.snmpStatus(self, "ipaddresses")
Exemplo n.º 40
0
from zope.event import notify

from zExceptions import BadRequest

from ZPublisher.Converters import type_converters
from Products.ZenModel.interfaces import IDeviceLoader
from Products.ZenUtils.ZCmdBase import ZCmdBase
from Products.ZenModel.Device import Device
from Products.ZenRelations.ZenPropertyManager import iszprop
from Products.ZenModel.ZenModelBase import iscustprop
from Products.ZenEvents.ZenEventClasses import Change_Add
from Products.Zuul.catalog.events import IndexingEvent
from Products.ZenUtils.Utils import unused
# We import DateTime so that we can set properties of type DateTime in the batchload
from DateTime import DateTime
unused(DateTime)

from Products.ZenUtils.IpUtil import isip

from zenoss.protocols.protobufs.zep_pb2 import SEVERITY_INFO, SEVERITY_ERROR

class BatchDeviceLoader(ZCmdBase):
    """
    Base class wrapping around dmd.DeviceLoader
    """

# ZEN-9930 - Pulled these options from sample config
# setHWProduct=('myproductName','manufacturer'), setOSProduct=('OS Name','manufacturer')

    sample_configs = """#
# Example zenbatchloader file (Groups, Systems Locations, Devices, etc.)
 def zenPropertyOptions(self, propname):
     """Provide a set of default options for a ZProperty.
     """
     unused(propname)
     return []
$Id: SQLClient.py,v 2.19 2011/12/29 23:40:12 egor Exp $"""

__version__ = "$Revision: 2.19 $"[11:-2]

import Globals
from Products.ZenUtils.Utils import zenPath, unused
from Products.ZenUtils.Driver import drive
from Products.DataCollector.BaseClient import BaseClient

from twisted.enterprise import adbapi
from twisted.internet import defer
from twisted.python.failure import Failure
from pysamba.wbem.Query import Query

unused(Query)

import datetime
import decimal
from DateTime import DateTime

import re

DTPAT = re.compile(
    r'^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+|-])(\d{3})')

import os
import sys
import logging

log = logging.getLogger("zen.SQLClient")
Exemplo n.º 43
0
from Products.ZenRRD import runner

from Products.ZenCollector.daemon import CollectorDaemon
from Products.ZenCollector.interfaces import ICollectorPreferences,\
                                             IDataService,\
                                             IEventService,\
                                             IScheduledTask
from Products.ZenCollector.tasks import SimpleTaskFactory,\
                                        SubConfigurationTaskSplitter,\
                                        TaskStates, \
                                        BaseTask
from Products.ZenEvents import Event
from Products.ZenUtils.Executor import TwistedExecutor

from Products.DataCollector import Plugins
unused(Plugins)

MAX_CONNECTIONS = 250
MAX_BACK_OFF_MINUTES = 20

# We retrieve our configuration data remotely via a Twisted PerspectiveBroker
# connection. To do so, we need to import the class that will be used by the
# configuration service to send the data over, i.e. DeviceProxy.
from Products.ZenCollector.services.config import DeviceProxy
unused(DeviceProxy)

# The following classes were refactored into the runner module after the
# 4.2 release. ZenPacks were importing those classes from here, so they
# must be exported for backwards compatibility.
ProcessRunner = runner.ProcessRunner
ProcessRunner.start = ProcessRunner.send
Exemplo n.º 44
0
                                             IStatisticsService
from Products.ZenCollector.tasks import SimpleTaskFactory,\
                                        SimpleTaskSplitter,\
                                        TaskStates
from Products.ZenEvents.ZenEventClasses import Clear, Error, Warning, Info, \
    Debug, Status_Wmi
from Products.ZenUtils.observable import ObservableMixin
from ZenPacks.zenoss.WindowsMonitor.Watcher import Watcher
from ZenPacks.zenoss.WindowsMonitor.utils import addNTLMv2Option, setNTLMv2Auth

# We retrieve our configuration data remotely via a Twisted PerspectiveBroker
# connection. To do so, we need to import the class that will be used by the
# configuration service to send the data over, i.e. DeviceProxy.
from Products.ZenUtils.Utils import unused
from Products.ZenCollector.services.config import DeviceProxy
unused(DeviceProxy)
from ZenPacks.zenoss.WindowsMonitor.services.EventLogConfig import EventLogConfig
unused(EventLogConfig)

#
# creating a logging context for this module to use
#
log = logging.getLogger("zen.zeneventlog")


# Create an implementation of the ICollectorPreferences interface so that the
# ZenCollector framework can configure itself from our preferences.
class ZenEventLogPreferences(object):
    zope.interface.implements(ICollectorPreferences)

    def __init__(self):
Exemplo n.º 45
0
 def _notifyOfCopyTo(self, container, op=0):
     """Manage copy/move/rename state for use in manage_beforeDelete."""
     unused(container)
     self._operation = op # 0 == copy, 1 == move, 2 == rename
Exemplo n.º 46
0
    def generate_configs(self, parser, options):
        """
        Create a configuration file based on the long-form of the option names

        @parameter parser: an optparse parser object which contains defaults, help
        @parameter options: parsed options list containing actual values
        """

        #
        # Header for the configuration file
        #
        unused(options)
        daemon_name = os.path.basename(sys.argv[0])
        daemon_name = daemon_name.replace('.py', '')

        print """#
# Configuration file for %s
#
#  To enable a particular option, uncomment the desired entry.
#
# Parameter     Setting
# ---------     -------""" % (daemon_name)

        options_to_ignore = ('help', 'version', '', 'genconf', 'genxmltable')

        #
        # Create an entry for each of the command line flags
        #
        # NB: Ideally, this should print out only the option parser dest
        #     entries, rather than the command line options.
        #
        import re
        for opt in getAllParserOptionsGen(parser):
            if opt.help is SUPPRESS_HELP:
                continue

            #
            # Get rid of the short version of the command
            #
            option_name = re.sub(r'.*/--', '', "%s" % opt)

            #
            # And what if there's no short version?
            #
            option_name = re.sub(r'^--', '', "%s" % option_name)

            #
            # Don't display anything we shouldn't be displaying
            #
            if option_name in options_to_ignore:
                continue

            #
            # Find the actual value specified on the command line, if any,
            # and display it
            #

            value = getattr(parser.values, opt.dest)

            default_value = parser.defaults.get(opt.dest)
            if default_value is NO_DEFAULT or default_value is None:
                default_value = ""
            default_string = ""
            if default_value != "":
                default_string = ", default: " + str(default_value)

            comment = self.pretty_print_config_comment(opt.help +
                                                       default_string)

            #
            # NB: I would prefer to use tabs to separate the parameter name
            #     and value, but I don't know that this would work.
            #
            print """#
# %s
#%s %s""" % (comment, option_name, value)

        #
        # Pretty print and exit
        #
        print "#"
        sys.exit(0)
Exemplo n.º 47
0
    def generate_xml_configs(self, parser, options):
        """
        Create an XML file that can be used to create Docbook files
        as well as used as the basis for GUI-based daemon option
        configuration.
        """

        #
        # Header for the configuration file
        #
        unused(options)
        daemon_name = os.path.basename(sys.argv[0])
        daemon_name = daemon_name.replace('.py', '')

        export_date = datetime.datetime.now()

        print """<?xml version="1.0" encoding="UTF-8"?>

<!-- Default daemon configuration generated on %s -->
<configuration id="%s" >

""" % (export_date, daemon_name)

        options_to_ignore = (
            'help',
            'version',
            '',
            'genconf',
            'genxmltable',
            'genxmlconfigs',
        )

        #
        # Create an entry for each of the command line flags
        #
        # NB: Ideally, this should print out only the option parser dest
        #     entries, rather than the command line options.
        #
        import re
        for opt in getAllParserOptionsGen(parser):
            if opt.help is SUPPRESS_HELP:
                continue

            #
            # Don't display anything we shouldn't be displaying
            #
            option_name = re.sub(r'.*/--', '', "%s" % opt)
            option_name = re.sub(r'^--', '', "%s" % option_name)
            if option_name in options_to_ignore:
                continue

            default_value = parser.defaults.get(opt.dest)
            if default_value is NO_DEFAULT or default_value is None:
                default_string = ""
            else:
                default_string = str(default_value)

#
# TODO: Determine the variable name used and display the --option_name=variable_name
#
            if opt.action in ['store_true', 'store_false']:
                print """    <option id="%s" type="%s" default="%s" help="%s" />
""" % (
                    option_name,
                    "boolean",
                    default_string,
                    quote(opt.help),
                )

            else:
                target = opt.dest.lower()
                print """    <option id="%s" type="%s" default="%s" target="%s" help="%s" />
""" % (
                    option_name,
                    opt.type,
                    quote(default_string),
                    target,
                    quote(opt.help),
                )

        #
        # Close the table elements
        #
        print """
</configuration>
"""
        sys.exit(0)
import Globals
import zope.interface
import zope.component
from zope.event import notify

from Products.ZenCollector import daemon
from Products.ZenCollector import interfaces
from Products.ZenCollector import tasks
from Products.ZenUtils import IpUtil
import Products.ZenStatus.interfaces

# perform some imports to allow twisted's PB to serialize these objects
from Products.ZenUtils.Utils import unused
from Products.ZenCollector.services.config import DeviceProxy
from Products.ZenHub.services.PingPerformanceConfig import PingPerformanceConfig
unused(DeviceProxy)
unused(PingPerformanceConfig)

from .interfaces import IParserReadyForOptionsEvent

# define some constants strings
COLLECTOR_NAME = "zenping"
CONFIG_SERVICE = 'Products.ZenHub.services.PingPerformanceConfig'


class ParserReadyForOptionsEvent(object):
    zope.interface.implements(IParserReadyForOptionsEvent)

    def __init__(self, parser):
        self.parser = parser
Exemplo n.º 49
0
from twisted.python.failure import Failure
from twisted.internet import defer

import Globals
from zope import interface
from zope import component

from zenoss.protocols.protobufs.zep_pb2 import SEVERITY_CLEAR

from Products.ZenCollector import interfaces
from Products.ZenCollector.tasks import TaskStates, BaseTask

from Products.ZenUtils.Utils import unused
from Products.ZenCollector.services.config import DeviceProxy
unused(DeviceProxy)

from Products.ZenEvents.ZenEventClasses import Status_Ping
from Products.ZenEvents import ZenEventClasses
from zenoss.protocols.protobufs import zep_pb2 as events

from Products.ZenUtils.IpUtil import ipunwrap
from interfaces import IPingTask

COLLECTOR_NAME = "zenping"

STATUS_EVENT = {
    'eventClass': Status_Ping,
    'component': 'zenping',
    '    eventGroup': 'Ping'
}
Exemplo n.º 50
0
from Products.ZenEvents import Event

from Products.ZenCollector.daemon import CollectorDaemon
from Products.ZenCollector.interfaces import ICollectorPreferences,\
                                             IDataService,\
                                             IEventService,\
                                             IScheduledTask
from Products.ZenCollector.tasks import SimpleTaskFactory,\
                                        SubConfigurationTaskSplitter,\
                                        TaskStates,\
                                        BaseTask

# do not delete this: it is needed for pb/jelly
from Products.ZenUtils.Utils import unused
from ZenPacks.zenoss.ZenMailTx.MailTxConfigService import Config
unused(Config)

COLLECTOR_NAME = "zenmailtx"
log = logging.getLogger("zen.%s" % COLLECTOR_NAME)

MAX_BACK_OFF_MINUTES = 20

mailEventClass = '/Status'


class MailTxCollectionPreferences(object):
    implements(ICollectorPreferences)

    def __init__(self):
        """
        Constructs a new preferences instance and
Exemplo n.º 51
0
    Option,
    SUPPRESS_HELP,
    NO_DEFAULT,
    OptionValueError,
    BadOptionError,
)
from urllib import quote

# There is a nasty incompatibility between pkg_resources and twisted.
# This pkg_resources import works around the problem.
# See http://dev.zenoss.org/trac/ticket/3146 for details
from Products.ZenUtils.PkgResources import pkg_resources

from Products.ZenUtils.Utils import unused, load_config_override, zenPath, getAllParserOptionsGen
from Products.ZenUtils.GlobalConfig import _convertConfigLinesToArguments, applyGlobalConfToParser
unused(pkg_resources)


class DMDError:
    pass


def checkLogLevel(option, opt, value):
    if re.match(r'^\d+$', value):
        value = int(value)
    else:
        intval = getattr(logging, value.upper(), None)
        if intval:
            value = intval
        else:
            raise OptionValueError('"%s" is not a valid log level.' % value)
Exemplo n.º 52
0
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is
# installed.
#
######################################################################

import logging
LOG = logging.getLogger('zen.XenServer')

import Globals

from Products.ZenModel.ZenPack import ZenPack as ZenPackBase
from Products.ZenRelations.zPropertyCategory import setzPropertyCategory
from Products.ZenUtils.Utils import unused

unused(Globals)

ZENPACK_NAME = 'ZenPacks.zenoss.XenServer'

# Modules containing model classes. Used by zenchkschema to validate
# bidirectional integrity of defined relationships.
productNames = (
    'Endpoint',
    'Host',
    'HostCPU',
    'Network',
    'PBD',
    'PIF',
    'Pool',
    'SR',
    'VBD',
Exemplo n.º 53
0
 def postStartup(self):
     unused(self)
     pass
Exemplo n.º 54
0
                                             IEventService, \
                                             IScheduledTask, IStatisticsService
from Products.ZenCollector.tasks import SimpleTaskFactory,\
                                        SimpleTaskSplitter,\
                                        BaseTask, TaskStates
from Products.ZenUtils.observable import ObservableMixin

from Products.ZenEvents.SyslogProcessing import SyslogProcessor

from Products.ZenUtils.Utils import zenPath
from Products.ZenUtils.IpUtil import asyncNameLookup

from Products.ZenEvents.EventServer import Stats
from Products.ZenUtils.Utils import unused
from Products.ZenCollector.services.config import DeviceProxy
unused(Globals, DeviceProxy)

COLLECTOR_NAME = 'zensyslog'
log = logging.getLogger("zen.%s" % COLLECTOR_NAME)


class SyslogPreferences(object):
    zope.interface.implements(ICollectorPreferences)

    def __init__(self):
        """
        Constructs a new PingCollectionPreferences instance and
        provides default values for needed attributes.
        """
        self.collectorName = COLLECTOR_NAME
        self.configCycleInterval = 20  # minutes
Exemplo n.º 55
0
 def cleanup(self):
     unused(self)
     pass
Exemplo n.º 56
0
from Products.ZenModel.Device import Device
from Products.ZenModel.ZenStatus import ZenStatus
from Products.ZenRelations.RelationshipBase import RelationshipBase
from Products.ZenRelations.ToManyContRelationship import ToManyContRelationship
from Products.ZenUtils.Utils import unused
from Products.ZenUtils.ZenScriptBase import ZenScriptBase
from time import localtime, strftime
try:
    from ZenPacks.zenoss.AdvancedSearch.SearchManager import SearchManager, SEARCH_MANAGER_ID
except ImportError:
    pass
from ZenToolboxUtils import inline_print
from ZODB.POSException import POSKeyError
from ZODB.utils import u64

unused(Globals)


def progress_bar(items, errors, repairs, fix_value, cycle):
    if fix_value:
        inline_print(
            "[%s]  Cycle %s  | Items Scanned: %12d | Errors:  %6d | Repairs: %6d |  "
            % (time.strftime("%Y-%m-%d %H:%M:%S"), cycle, items, errors,
               repairs))
    else:
        inline_print(
            "[%s]  Cycle %s  | Items Scanned: %12d | Errors:  %6d |  " %
            (time.strftime("%Y-%m-%d %H:%M:%S"), cycle, items, errors))


class Fixer(object):
Exemplo n.º 57
0
                                             IScheduledTask
from Products.ZenCollector.tasks import SimpleTaskFactory,\
                                        SimpleTaskSplitter,\
                                        TaskStates
from Products.ZenEvents.ZenEventClasses import Error, Clear, Status_WinService, Status_Wmi
from Products.ZenUtils.observable import ObservableMixin
from ZenPacks.zenoss.WindowsMonitor.WMIClient import WMIClient
from ZenPacks.zenoss.WindowsMonitor.Watcher import Watcher
from ZenPacks.zenoss.WindowsMonitor.utils import addNTLMv2Option, setNTLMv2Auth

# We retrieve our configuration data remotely via a Twisted PerspectiveBroker
# connection. To do so, we need to import the class that will be used by the
# configuration service to send the data over, i.e. DeviceProxy.
from Products.ZenUtils.Utils import unused
from Products.ZenCollector.services.config import DeviceProxy
unused(DeviceProxy)
from ZenPacks.zenoss.WindowsMonitor.services.WinServiceConfig import WinServiceConfig
unused(WinServiceConfig)

#
# creating a logging context for this module to use
#
log = logging.getLogger("zen.zenwin")


# Create an implementation of the ICollectorPreferences interface so that the
# ZenCollector framework can configure itself from our preferences.
class ZenWinPreferences(object):
    zope.interface.implements(ICollectorPreferences)

    def __init__(self):
Exemplo n.º 58
0
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        minval = self.minimum
        if minval is None or minval == '':
            minval = NaN
        maxval = self.maximum
        if maxval is None or maxval == '':
            maxval = NaN
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                minval = rpneval(minval, rpn)
            except:
                minval = 0
                self.raiseRPNExc()

            try:
                maxval = rpneval(maxval, rpn)
            except:
                maxval = 0
                self.raiseRPNExc()

        minstr = self.setPower(minval)
        maxstr = self.setPower(maxval)

        minval = nanToNone(minval)
        maxval = nanToNone(maxval)
        if legend:
            gopts.append("HRULE:%s%s:%s\\j" %
                         (minval or maxval, color, legend))
        elif minval is not None and maxval is not None:
            if minval == maxval:
                gopts.append(
                    "HRULE:%s%s:%s not equal to %s\\j" %
                    (minval, color, self.getNames(relatedGps), minstr))
            elif minval < maxval:
                gopts.append(
                    "HRULE:%s%s:%s not within %s and %s\\j" %
                    (minval, color, self.getNames(relatedGps), minstr, maxstr))
                gopts.append("HRULE:%s%s" % (maxval, color))
            elif minval > maxval:
                gopts.append(
                    "HRULE:%s%s:%s between %s and %s\\j" %
                    (minval, color, self.getNames(relatedGps), maxstr, minstr))
                gopts.append("HRULE:%s%s" % (maxval, color))
        elif minval is not None:
            gopts.append("HRULE:%s%s:%s less than %s\\j" %
                         (minval, color, self.getNames(relatedGps), minstr))
        elif maxval is not None:
            gopts.append("HRULE:%s%s:%s greater than %s\\j" %
                         (maxval, color, self.getNames(relatedGps), maxstr))

        return gopts
Exemplo n.º 59
0
from Products.DataCollector.zenmodeler import ZenModeler
from Products.ZenEvents.Event import Info
from Products.ZenEvents.ZenEventClasses import Status_Snmp
from Products.ZenHub.PBDaemon import FakeRemote, PBDaemon
from Products.ZenHub.services import DiscoverService, ModelerService
from Products.ZenHub.services.DiscoverService import JobPropertiesProxy
from Products.ZenModel.Exceptions import NoIPAddress
from Products.ZenStatus.nmap.util import executeNmapForIps
from Products.ZenUtils.Exceptions import ZentinelException
from Products.ZenUtils.IpUtil import (asyncNameLookup, isip, parse_iprange,
                                      getHostByName, ipunwrap)
from Products.ZenUtils.snmp import (SnmpAgentDiscoverer, SnmpV1Config,
                                    SnmpV2cConfig, SnmpV3Config)
from Products.ZenUtils.Utils import unused

unused(Globals, DiscoverService, ModelerService, JobPropertiesProxy)

DEFAULT_COMMUNITIES = ['public', 'private']


def _partitionPingResults(results):
    """Groups the results into a 'good' results and 'bad' results and
    returns each set as a tuple.

    @returns {tuple} (<good-results>, <bad-results>)
    """
    good, bad = [], []
    for result in results:
        if result.isUp:
            good.append(result.address)
        else:
Exemplo n.º 60
0
from Products.ZenUtils.Exceptions import ZentinelException
from Products.ZenUtils.Utils import unused
from Products.ZenUtils.Driver import drive
from Products.ZenUtils.IpUtil import asyncNameLookup, isip, parse_iprange, \
                                     getHostByName, ipunwrap
from Products.ZenUtils.NJobs import NJobs
from Products.ZenUtils.snmp import SnmpV1Config, SnmpV2cConfig
from Products.ZenUtils.snmp import SnmpAgentDiscoverer
from Products.ZenModel.Exceptions import NoIPAddress
from Products.ZenEvents.ZenEventClasses import Status_Snmp
from Products.ZenEvents.Event import Info
from Products.ZenStatus.PingService import PingService
from Products.ZenHub.PBDaemon import FakeRemote, PBDaemon
from Products.ZenHub.services import DiscoverService, ModelerService
from Products.ZenHub.services.DiscoverService import JobPropertiesProxy
unused(DiscoverService, ModelerService, JobPropertiesProxy)  # for pb

from twisted.internet.defer import succeed
from twisted.python.failure import Failure
from twisted.internet import reactor
from twisted.names.error import DNSNameError


class ZenDisc(ZenModeler):
    """
    Scan networks and routes looking for devices to add to the ZODB
    """

    initialServices = PBDaemon.initialServices + ['DiscoverService']
    name = 'zendisc'
    scanned = 0