Beispiel #1
0
    def tokenparser(self, toklist, toktypes, indent):
        """Parse directive arguments."""
        super(RPI, self).tokenparser(toklist, toktypes, indent)

        try:
            self.args.sensor
        except AttributeError:
            raise directive.ParseFailure('Sensor not specified')
        try:
            self.args.sensortype
        except AttributeError:
            raise directive.ParseFailure('Sensor type not specified')
        if self.args.sensor == 'DHT':
            try:
                self.args.gpiopin
                self.defaultVarDict['gpiopin'] = self.args.sensor
            except AttributeError:
                raise directive.ParseFailure('GPIO pin not specified')
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure('Rule not specified')

        self.defaultVarDict['sensor'] = self.args.sensor
        self.defaultVarDict['sensortype'] = self.args.sensortype
        self.defaultVarDict['rule'] = self.args.rule

        # define unique ID
        if self.ID is None:
            self.ID = '%s.RPI.%s' % (log.hostname, self.args.sensor)
        self.state.ID = self.ID

        log.log(
            "<disk>RPI.tokenparser(): ID '%s' sensor '%s' rule '%s'" %
            (self.state.ID, self.args.sensor, self.args.rule), 8)
Beispiel #2
0
    def tokenparser(self, toklist, toktypes, indent):
        super(COM, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.cmd
        except AttributeError:
            raise directive.ParseFailure("Command (cmd) not specified")
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        # Set any COM-specific variables
        #  cmd = the command
        self.defaultVarDict['cmd'] = self.args.cmd

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.COM.%s.%s' % (log.hostname, self.args.cmd,
                                        self.args.rule)
        self.state.ID = self.ID

        log.log("<directive>COM.tokenparser(): ID '%s' cmd '%s' rule '%s'" %
                (self.state.ID, self.args.cmd, self.args.rule), 8)
Beispiel #3
0
    def tokenparser(self, toklist, toktypes, indent):
        """Parse directive arguments."""
        super(RPI, self).tokenparser(toklist, toktypes, indent)

        try:
            self.args.sensor
        except AttributeError:
            raise directive.ParseFailure('Sensor not specified')
        try:
            self.args.sensortype
        except AttributeError:
            raise directive.ParseFailure('Sensor type not specified')
        if self.args.sensor == 'DHT':
            try:
                self.args.gpiopin
                self.defaultVarDict['gpiopin'] = self.args.sensor
            except AttributeError:
                raise directive.ParseFailure('GPIO pin not specified')
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure('Rule not specified')

        self.defaultVarDict['sensor'] = self.args.sensor
        self.defaultVarDict['sensortype'] = self.args.sensortype
        self.defaultVarDict['rule'] = self.args.rule

        # define unique ID
        if self.ID is None:
            self.ID = '%s.RPI.%s' % (log.hostname, self.args.sensor)
        self.state.ID = self.ID

        log.log("<disk>RPI.tokenparser(): ID '%s' sensor '%s' rule '%s'" %
                (self.state.ID, self.args.sensor, self.args.rule), 8)
Beispiel #4
0
    def getData(self):

        if self.args.protocol == 'tcp' or self.args.protocol == 'TCP':
            connections = self.data_collectors['netstat.TCPtable'].getHash()
        elif self.args.protocol == 'udp' or self.args.protocol == 'UDP':
            connections = self.data_collectors['netstat.UDPtable'].getHash()
        else:
            log.log("<directive>SP.getData(): protocol '%s' illegal" %
                    (self.args.protocol), 8)
            raise directive.DirectiveError("protocol '%s' illegal" % (self.args.protocol))

        if len(connections) == 0:
            log.log("<directive>SP.getData(): Zero connections for protocol '%s'" %
                    (self.args.protocol), 6)
            return None

        data = {}
        if self.args.bindaddr == 'any':
            # only compare port part of connection - ignore bind address
            data['exists'] = False
            for key in connections.keys():
                p = key.split(':')[1]
                if p == str(self.port):
                    data['exists'] = True
                    break
        else:
            # compare bind address and port for match
            key = "%s:%s" % (self.args.bindaddr, self.port)
            data['exists'] = key in connections.keys()  # true or false

        return data
Beispiel #5
0
    def tokenparser(self, toklist, toktypes, indent):
        """
        Parse directive arguments.
        """

        super(FS, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.fs
        except AttributeError:
            raise directive.ParseFailure("Filesystem not specified")
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        # Set any directive-specific variables
        self.defaultVarDict['rule'] = self.args.rule

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.FS.%s' % (log.hostname, self.args.fs)
        self.state.ID = self.ID

        log.log("<directive>FS.tokenparser(): ID '%s' fs '%s' rule '%s'" %
                (self.state.ID, self.args.fs, self.args.rule), 8)
Beispiel #6
0
    def tokenparser(self, toklist, toktypes, indent):
        """
        Parse directive arguments.
        """

        super(STORE, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        # Rule should be a string
        if not isinstance(self.args.rule, str):
            raise directive.ParseFailure("STORE parse error, rule is not string.")

        self.defaultVarDict['rule'] = self.args.rule

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.STORE.%s' % (log.hostname, self.args.rule)
        self.state.ID = self.ID

        log.log("<directive>STORE.tokenparser(): ID '%s' rule '%s'" %
                (self.state.ID, self.args.rule), 8)
Beispiel #7
0
    def collectData(self):
        """
        Collect disk usage data.
        """
        # Get information about all local filesystems from 'df'.
        rawList = utils.safe_popen('df -l', 'r')
        rawList.readline()  # skip header

        self.data.datahash = {}
        self.data.mounthash = {}

        lines = rawList.read()
        lines = re.sub(r'\n    ', '', lines)
        lines = lines.split('\n')
        for line in lines:
            fields = line.split()
            if len(fields) == 6:
                p = df(fields)
                self.data.datahash[
                    fields[0]] = p  # dictionary of filesystem devices
                self.data.mounthash[
                    fields[5]] = p  # dictionary of mount points

        utils.safe_pclose(rawList)
        log.log("<df>dfList.collectData(): filesystem data collected", 7)
Beispiel #8
0
    def getData(self):
        """
        Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        data = {}

        # Check if pidfile exists
        try:
            pidfile = open(self.args.pidfile, 'r')
        except IOError:
            # pidfile not found
            data['exists'] = False
        else:
            data['exists'] = True
            pid = pidfile.readline()
            pidfile.close()
            pid = string.strip(pid)
            pid = string.split(pid)[0]            # Get rid of any other junk after pid
            pid = int(pid)                        # want it as an integer
            data['pid'] = pid

            # Search for pid in process list
            if self.data_collectors['proc.procList'].pidExists(pid) == 0:
                # there is no process with pid == pid
                data['running'] = False
                log.log("<directive>PID.getData(): pid %s not in process list" % (pid), 7)
            else:
                data['running'] = True
                log.log("<directive>PID.getData(): pid %s is in process list" % (pid), 7)

        return data
Beispiel #9
0
    def tokenparser(self, toklist, toktypes, indent):
        """Parse tokenized input."""

        super(PROC, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.name
        except AttributeError:
            raise directive.ParseFailure("Process name not specified")
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        # Set any PROC-specific action variables
        #  proc_check_name = the process name being checked
        self.defaultVarDict['name'] = self.args.name

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.PROC.%s' % (log.hostname, self.args.name)
        self.state.ID = self.ID

        log.log("<directive>PROC.tokenparser(): ID '%s' name '%s' rule '%s'" %
                (self.state.ID, self.args.name, self.args.rule), 8)
Beispiel #10
0
    def _getuptime(self):
        """Get system statistics from the output of the 'uptime' command.
        """

        uptime_cmd = "/usr/bin/uptime"

        (retval, output) = utils.safe_getstatusoutput(uptime_cmd)

        if retval != 0:
            log.log(
                "<system>system._getuptime(): error calling '%s'" %
                (uptime_cmd), 5)
            return None

        uptime_dict = {}

        uptime_re = ".+up (?P<uptime>.+), (?P<users>[0-9]+) users?, load averages: (?P<loadavg1>[0-9.]+) (?P<loadavg5>[0-9.]+) (?P<loadavg15>[0-9.]+)"
        inx = re.compile(uptime_re)
        sre = inx.search(output)
        if sre:
            uptime_dict = sre.groupdict()
        else:
            log.log(
                "<system>system._getuptime(): could not parse uptime output '%s'"
                % (output), 5)
            return None

        # convert types
        uptime_dict['uptime'] = uptime_dict['uptime']
        uptime_dict['users'] = int(uptime_dict['users'])
        uptime_dict['loadavg1'] = float(uptime_dict['loadavg1'])
        uptime_dict['loadavg5'] = float(uptime_dict['loadavg5'])
        uptime_dict['loadavg15'] = float(uptime_dict['loadavg15'])

        return uptime_dict
Beispiel #11
0
    def getData(self):
        """
        Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        datahash = None

        # Get data as directed by rule.
        # * this is hard-coded to a few different 'rules' atm.  This should be
        # cleaned up later to handle any type of rule (TODO)

        if self.args.rule[:6] == 'system':
            datahash = self.data_collectors['system.system'].getHash()  # get dictionary of system stats
        elif self.args.rule[:7] == 'netstat':
            datahash = self.data_collectors['netstat.stats_ctrs'].getHash()  # get dictionary of network stats
        elif self.args.rule[:4] == 'proc':
            datahash = self.data_collectors['proc.procList'].allprocs()  # get dictionary of process details
        elif self.args.rule[:2] == 'if':
            datahash = self.data_collectors['netstat.netstat'].getAllInterfaces()  # get dictionary of interface details

        if datahash is None:
            log.log("<directive>STORE.getData(): rule '%s' is invalid." %
                    (self.args.rule), 4)
            return None

        return datahash
Beispiel #12
0
    def _getuptime(self):
        """Get system statistics from the output of the 'uptime' command.
        """

        uptime_cmd = "/usr/bin/uptime"

        (retval, output) = utils.safe_getstatusoutput(uptime_cmd)

        if retval != 0:
            log.log("<system>system._getuptime(): error calling '%s'"%(uptime_cmd), 5)
            return None

        uptime_dict = {}

        uptime_re = ".+up (?P<uptime>.+), (?P<users>[0-9]+) users?, load averages: (?P<loadavg1>[0-9.]+) (?P<loadavg5>[0-9.]+) (?P<loadavg15>[0-9.]+)"
        inx = re.compile(uptime_re)
        sre = inx.search(output)
        if sre:
            uptime_dict = sre.groupdict()
        else:
            log.log("<system>system._getuptime(): could not parse uptime output '%s'" % (output), 5)
            return None

        # convert types
        uptime_dict['uptime'] = uptime_dict['uptime']
        uptime_dict['users'] = int(uptime_dict['users'])
        uptime_dict['loadavg1'] = float(uptime_dict['loadavg1'])
        uptime_dict['loadavg5'] = float(uptime_dict['loadavg5'])
        uptime_dict['loadavg15'] = float(uptime_dict['loadavg15'])

        return uptime_dict
Beispiel #13
0
    def getData(self):
        """Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        disk = self.data_collectors['diskdevice.DiskStatistics'][self.args.device]
        if disk is None:
            log.log("<disk>DISK.docheck(): Error, device not found '%s'" %
                    (self.args.device), 4)
            return None
        else:
            return disk.getHash()
Beispiel #14
0
    def getData(self):
        """Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        sensorid = "%s-%s" % (self.args.sensor, self.args.gpiopin)
        sensor = self.data_collectors['rpi.DHTData'][sensorid]
        if sensor is None:
            log.log("<sensor>RPI.docheck(): Error, sensor not found '%s'" %
                    (sensorid), 4)
            return None
        else:
            return sensor.getHash()
Beispiel #15
0
        def collectData(self):
            self.data.datahash = {}
            sensortype = SENSORTYPES['2302']
            pin = '4'
            humidity, temperature = Adafruit_DHT.read_retry(sensortype, pin)
            if humidity is not None and temperature is not None:
                sensorid = 'DHT-4'
                sensor = DHT(sensorid)
                self.data.datahash[sensorid] = sensor
                sensor.set_data('humidity', humidity)
                sensor.set_data('temperature', temperature)

            log.log("<dhtsensor>DHTData.collectData(): Collected data")
Beispiel #16
0
    def tokenparser(self, toklist, toktypes, indent):
        super(PORT, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.host
        except AttributeError:
            raise directive.ParseFailure("Host not specified")
        try:
            self.args.port
        except AttributeError:
            raise directive.ParseFailure("Port not specified")
        try:
            self.args.port = int(self.args.port)
        except ValueError:
            raise directive.ParseFailure("Port is not an integer: %s" %
                                         (self.args.port))
        # send is optional
        try:
            self.args.send
        except AttributeError:
            self.args.send = ""                # default to not send
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        # Set any PORT-specific variables
        #  host = the host
        #  port = the port
        #  send = the send string
        #  expect = the expect string
        self.defaultVarDict['host'] = self.args.host
        self.defaultVarDict['port'] = self.args.port
        self.defaultVarDict['rule'] = self.args.rule
        self.defaultVarDict['send'] = self.args.send
        if 'expect' in dir(self.args):
            self.defaultVarDict['expect'] = self.args.expect

        if 'expectrexp' in dir(self.args):
            self.defaultVarDict['expectrexp'] = self.args.expectrexp
            self.regexp = re.compile(self.args.expectrexp)

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.PORT.%s.%d' % (log.hostname,
                                         self.args.host, self.args.port)
        self.state.ID = self.ID

        log.log("<directive>PORT.tokenparser(): ID '%s' host '%s' port %d" %
                (self.state.ID, self.args.host, self.args.port), 8)
Beispiel #17
0
    def getData(self):
        """Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        disk = self.data_collectors['diskdevice.DiskStatistics'][
            self.args.device]
        if disk is None:
            log.log(
                "<disk>DISK.docheck(): Error, device not found '%s'" %
                (self.args.device), 4)
            return None
        else:
            return disk.getHash()
Beispiel #18
0
    def getData(self):
        """Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        sensorid = "%s-%s" % (self.args.sensor, self.args.gpiopin)
        sensor = self.data_collectors['rpi.DHTData'][sensorid]
        if sensor is None:
            log.log(
                "<sensor>RPI.docheck(): Error, sensor not found '%s'" %
                (sensorid), 4)
            return None
        else:
            return sensor.getHash()
Beispiel #19
0
    def collectData(self):
        """Collect system statistics data.
        """

        self.data.datahash = {}                # dict of system data

        vmstat_dict = self._getvmstat()
        if vmstat_dict:
            self.data.datahash.update(vmstat_dict)

        uptime_dict = self._getuptime()
        if uptime_dict:
            self.data.datahash.update(uptime_dict)

        log.log("<system>system.collectData(): collected data for %d system statistics" %
                (len(self.data.datahash.keys())), 6)
Beispiel #20
0
    def collectData(self):
        """Collect system statistics data.
        """

        self.data.datahash = {}  # dict of system data

        vmstat_dict = self._getvmstat()
        if vmstat_dict:
            self.data.datahash.update(vmstat_dict)

        uptime_dict = self._getuptime()
        if uptime_dict:
            self.data.datahash.update(uptime_dict)

        log.log(
            "<system>system.collectData(): collected data for %d system statistics"
            % (len(self.data.datahash.keys())), 6)
Beispiel #21
0
    def tokenparser(self, toklist, toktypes, indent):
        super(SP, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.port
        except AttributeError:
            raise directive.ParseFailure("Port not specified")
        try:
            self.args.protocol
        except AttributeError:
            raise directive.ParseFailure("Protocol not specified")
        try:
            self.args.bindaddr
        except AttributeError:
            raise directive.ParseFailure("Bind address not specified")
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        if self.args.bindaddr == '*':
            self.args.bindaddr = '0.0.0.0'

        self.port_n = self.args.port                # remember port name

        # lets try resolving this service port to a number
        try:
            self.port = socket.getservbyname(str(self.port_n), self.args.protocol)
        except socket.error:
            self.port = self.port_n

        self.defaultVarDict['port'] = self.port_n
        self.defaultVarDict['bindaddr'] = self.args.bindaddr
        self.defaultVarDict['protocol'] = self.args.protocol

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.SP.%s/%s.%s' % (log.hostname, self.args.protocol,
                                          self.port_n, self.args.bindaddr)
        self.state.ID = self.ID

        log.log("<directive>SP.tokenparser(): ID '%s' protocol '%s', port '%s', bind addr '%s'" %
                (self.state.ID, self.args.protocol,
                 self.port, self.args.bindaddr), 8)
Beispiel #22
0
    def getData(self):
        """
        Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        try:
            df = self.data_collectors['df.dfList'][self.args.fs]
        except KeyError:
            log.log("<directive>FS.docheck(): Error, filesystem not found '%s'" %
                    (self.args.fs), 4)
            return None

        if df is None:
            log.log("<directive>FS.docheck(): Error, filesystem not found '%s'" %
                    (self.args.fs), 4)
            return None
        else:
            return df.getHash()
Beispiel #23
0
    def collectData(self):
        """
        Collect disk usage data.
        """
        # Get information about all local filesystems from 'df'.
        rawList = utils.safe_popen('/bin/df -l -k', 'r')
        rawList.readline()                        # skip header

        self.data.datahash = {}
        self.data.mounthash = {}

        for line in rawList.readlines():
            fields = line.split()
            if len(fields) == 9:
                p = df(fields)
                self.data.datahash[fields[0]] = p        # dictionary of filesystem devices
                self.data.mounthash[fields[5]] = p        # dictionary of mount points

        utils.safe_pclose(rawList)
        log.log("<df>dfList.collectData(): filesystem data collected", 7)
Beispiel #24
0
    def getData(self):
        """
        Called by Directive docheck() method to fetch the data required for
        evaluating the directive rule.
        """

        data = {}

        proc = self.data_collectors['proc.procList'][self.args.name]
        if proc is None:
            log.log("<directive>PROC.getData(): process not in process table, '%s'" %
                    (self.args.name), 7)
            data['exists'] = False
        else:
            log.log("<directive>PROC.getData(): process is in process table, '%s'" %
                    (self.args.name), 7)
            data['exists'] = True
            data.update(proc.procinfo())

        return data
Beispiel #25
0
    def _getvmstat(self):
        """Get system virtual memory statistics from the 'vm_stat' command.
        """

        vmstat_cmd = "/usr/bin/vm_stat"

        (retval, output) = utils.safe_getstatusoutput(vmstat_cmd)

        if retval != 0:
            log.log(
                "<system>system._getvmstat(): error calling '%s'" %
                (vmstat_cmd), 5)
            return None

        vmstat_dict = {}

        for l in output.split('\n'):
            if l.find('Pages free:') != -1:
                vmstat_dict['pages_free'] = long(l.split()[-1][:-1])
            elif l.find('Pages active:') != -1:
                vmstat_dict['pages_active'] = long(l.split()[-1][:-1])
            elif l.find('Pages inactive:') != -1:
                vmstat_dict['pages_inactive'] = long(l.split()[-1][:-1])
            elif l.find('Pages wired down:') != -1:
                vmstat_dict['pages_wired_down'] = long(l.split()[-1][:-1])
            elif l.find('Translation faults') != -1:
                vmstat_dict['ctr_translation_faults'] = long(
                    l.split()[-1][:-1])
            elif l.find('Pages copy-on-write:') != -1:
                vmstat_dict['ctr_pages_copyonwrite'] = long(l.split()[-1][:-1])
            elif l.find('Pages zero filled:') != -1:
                vmstat_dict['ctr_pages_zero_filled'] = long(l.split()[-1][:-1])
            elif l.find('Pages reactivated:') != -1:
                vmstat_dict['ctr_pages_reactivated'] = long(l.split()[-1][:-1])
            elif l.find('Pageins:') != -1:
                vmstat_dict['ctr_pageins'] = long(l.split()[-1][:-1])
            elif l.find('Pageouts:') != -1:
                vmstat_dict['ctr_pageouts'] = long(l.split()[-1][:-1])

        return vmstat_dict
Beispiel #26
0
        def collectData(self):
            self.data.datahash = {}
            self.data.numdisks = 0

            disk_stats = disk_io_counters(True)
            for name in disk_stats:
                try:
                    # do we have an existing disk object
                    disk = self.data.datahash[name]
                except KeyError:
                    # create new Disk object if needed
                    disk = Disk(name)
                    self.data.datahash[name] = disk
                self.data.numdisks += 1

                for attrname in ['read_count', 'write_count',
                                 'read_bytes', 'write_bytes',
                                 'read_time', 'write_time']:
                    disk.set_stat(attrname, getattr(disk_stats[name], attrname))

            log.log("<diskdevice>DiskStatistics.collectData(): Collected stats for %d disks" %
                    (self.data.numdisks), 6)
Beispiel #27
0
    def collectData(self):
        """
        Collect disk usage data.
        """
        # Get information about all local filesystems from 'df'.
        rawList = utils.safe_popen("df -l", "r")
        rawList.readline()  # skip header

        self.data.datahash = {}
        self.data.mounthash = {}

        lines = rawList.read()
        lines = re.sub(r"\n    ", "", lines)
        lines = lines.split("\n")
        for line in lines:
            fields = line.split()
            if len(fields) == 6:
                p = df(fields)
                self.data.datahash[fields[0]] = p  # dictionary of filesystem devices
                self.data.mounthash[fields[5]] = p  # dictionary of mount points

        utils.safe_pclose(rawList)
        log.log("<df>dfList.collectData(): filesystem data collected", 7)
Beispiel #28
0
    def tokenparser(self, toklist, toktypes, indent):
        """Parse directive arguments."""
        super(DISK, self).tokenparser(toklist, toktypes, indent)

        try:
            self.args.device
        except AttributeError:
            raise directive.ParseFailure('Device not specified')
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure('Rule not specified')

        self.defaultVarDict['device'] = self.args.device
        self.defaultVarDict['rule'] = self.args.rule

        # define unique ID
        if self.ID is None:
            self.ID = '%s.DISK.%s' % (log.hostname, self.args.device)
        self.state.ID = self.ID

        log.log("<disk>DISK.tokenparser(): ID '%s' device '%s' rule '%s'" %
                (self.state.ID, self.args.device, self.args.rule), 8)
Beispiel #29
0
    def tokenparser(self, toklist, toktypes, indent):
        """Parse rest of rule (after ':')."""
        super(IF, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.name
        except AttributeError:
            raise directive.ParseFailure("Interface name not specified")
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        self.defaultVarDict['name'] = self.args.name

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.IF.%s.%s' % (log.hostname,self.args.name,self.rule)
        self.state.ID = self.ID

        log.log("<directive>IF.tokenparser(): ID '%s' name '%s', rule '%s'" %
                (self.state.ID, self.args.name, self.args.rule), 8)
Beispiel #30
0
    def _getvmstat(self):
        """Get system virtual memory statistics from the 'vm_stat' command.
        """

        vmstat_cmd = "/usr/bin/vm_stat"

        (retval, output) = utils.safe_getstatusoutput(vmstat_cmd)

        if retval != 0:
            log.log("<system>system._getvmstat(): error calling '%s'"%(vmstat_cmd), 5)
            return None

        vmstat_dict = {}

        for l in output.split('\n'):
            if l.find('Pages free:') != -1:
                vmstat_dict['pages_free'] = long(l.split()[-1][:-1])
            elif l.find('Pages active:') != -1:
                vmstat_dict['pages_active'] = long(l.split()[-1][:-1])
            elif l.find('Pages inactive:') != -1:
                vmstat_dict['pages_inactive'] = long(l.split()[-1][:-1])
            elif l.find('Pages wired down:') != -1:
                vmstat_dict['pages_wired_down'] = long(l.split()[-1][:-1])
            elif l.find('Translation faults') != -1:
                vmstat_dict['ctr_translation_faults'] = long(l.split()[-1][:-1])
            elif l.find('Pages copy-on-write:') != -1:
                vmstat_dict['ctr_pages_copyonwrite'] = long(l.split()[-1][:-1])
            elif l.find('Pages zero filled:') != -1:
                vmstat_dict['ctr_pages_zero_filled'] = long(l.split()[-1][:-1])
            elif l.find('Pages reactivated:') != -1:
                vmstat_dict['ctr_pages_reactivated'] = long(l.split()[-1][:-1])
            elif l.find('Pageins:') != -1:
                vmstat_dict['ctr_pageins'] = long(l.split()[-1][:-1])
            elif l.find('Pageouts:') != -1:
                vmstat_dict['ctr_pageouts'] = long(l.split()[-1][:-1])

        return vmstat_dict
Beispiel #31
0
    def collectData(self):
        self.data.datahash = {}
        self.data.numdisks = 0

        disk_stats = disk_io_counters(True)
        for name in disk_stats:
            try:
                # do we have an existing disk object
                disk = self.data.datahash[name]
            except KeyError:
                # create new Disk object if needed
                disk = Disk(name)
                self.data.datahash[name] = disk
            self.data.numdisks += 1

            for attrname in [
                    'read_count', 'write_count', 'read_bytes', 'write_bytes',
                    'read_time', 'write_time'
            ]:
                disk.set_stat(attrname, getattr(disk_stats[name], attrname))

        log.log(
            "<diskdevice>DiskStatistics.collectData(): Collected stats for %d disks"
            % (self.data.numdisks), 6)
Beispiel #32
0
    def tokenparser(self, toklist, toktypes, indent):
        super(PID, self).tokenparser(toklist, toktypes, indent)

        # test required arguments
        try:
            self.args.pidfile
        except AttributeError:
            raise directive.ParseFailure("pidfile argument not specified")
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure("Rule not specified")

        # Set any PID-specific variables
        #  %pidf = the PID-file
        self.defaultVarDict['pidfile'] = self.args.pidfile
        self.defaultVarDict['rule'] = self.args.rule

        # define the unique ID
        if self.ID is None:
            self.ID = '%s.PID.%s.%s' % (log.hostname,self.args.pidfile,self.args.rule)
        self.state.ID = self.ID

        log.log("<directive>PID.tokenparser(): ID '%s' pid '%s' rule '%s'" % (self.state.ID, self.args.pidfile, self.args.rule), 8)
Beispiel #33
0
    def tokenparser(self, toklist, toktypes, indent):
        """Parse directive arguments."""
        super(DISK, self).tokenparser(toklist, toktypes, indent)

        try:
            self.args.device
        except AttributeError:
            raise directive.ParseFailure('Device not specified')
        try:
            self.args.rule
        except AttributeError:
            raise directive.ParseFailure('Rule not specified')

        self.defaultVarDict['device'] = self.args.device
        self.defaultVarDict['rule'] = self.args.rule

        # define unique ID
        if self.ID is None:
            self.ID = '%s.DISK.%s' % (log.hostname, self.args.device)
        self.state.ID = self.ID

        log.log(
            "<disk>DISK.tokenparser(): ID '%s' device '%s' rule '%s'" %
            (self.state.ID, self.args.device, self.args.rule), 8)
Beispiel #34
0
    def getData(self):
        log.log("<directive>COM.getData(): acquiring systemcall_semaphore for cmd '%s'" %
                (self.args.cmd), 9)
        utils.systemcall_semaphore.acquire()
        log.log("<directive>COM.getData(): systemcall_semaphore acquired for cmd '%s'" %
                (self.args.cmd), 9)
        tmpprefix = "/var/tmp/com%d" % os.getpid()
        cmd = "{ %s ; } >%s.out 2>%s.err" % (self.args.cmd, tmpprefix, tmpprefix)
        log.log("<directive>COM.getData(): calling system('%s')" % (cmd), 7)
        retval = os.system(cmd)
        signum = None
        if (retval & 0xff) == 0:
            # call terminated from standard exit()
            retval = retval >> 8
        elif (retval & 0xff00) == 0:
            # call terminated due to a signal
            signum = retval & 0xff
        elif (retval & 0xff) == 0o177:
            # child process stopped with WSTOPFLG (0177) set
            signum = retval & 0xff00

        out = ""
        try:
            outf = open(tmpprefix + ".out", 'r')
        except IOError:
            # stdout tmp file not found
            log.log("<directive>COM.docheck(): Error, could not open '%s'" %
                    (tmpprefix + ".out"), 4)
        else:
            out = outf.read()
            outf.close()
            os.remove(tmpprefix + ".out")
            out = string.strip(out)

        err = ""
        try:
            errf = open(tmpprefix + ".err", 'r')
        except IOError:
            # stderr tmp file not found
            log.log("<directive>COM.docheck(): Error, could not open '%s'" %
                    (tmpprefix + ".err"), 4)
        else:
            err = errf.read()
            errf.close()
            os.remove(tmpprefix + ".err")
            err = string.strip(err)

        utils.systemcall_semaphore.release()
        log.log("<directive>COM.getData(): released systemcall_semaphore for cmd '%s'" %
                (self.args.cmd), 9)

        log.log("<directive>COM.getData(): retval=%d" % retval, 7)
        log.log("<directive>COM.getData(): signum=%s" % signum, 9)
        log.log("<directive>COM.getData(): stdout='%s'" % out, 9)
        log.log("<directive>COM.getData(): stderr='%s'" % err, 9)

        data = {}                      # environment for com rules execution
        data['out'] = out
        data['err'] = err
        data['ret'] = retval
        data['signum'] = signum

        # Split output to assist rules
        outsplit = string.split(out)
        data['outfield1'] = ""         # Always set outfield1 so rule strings don't break
        data['outfields'] = len(outsplit)
        for i in range(0, len(outsplit)):
            data['outfield%d' % (i+1)] = utils.typeFromString(outsplit[i])

        return data
Beispiel #35
0
    def tcp_test(self, host, port, send=""):
        """
        Opens a connection to 'host' tcp port 'port' to test the connection.
        If 'send' is not an empty string, it will be sent to the remote host
        and any response stored in recv_string.

        Returns the tuple:
         (connected, recv_string, connect_time, error, errorstr)
         - connected: true (1) or false (0) based on a successful connection or
           not.
         - recv_string: contains the data received from the remote host.
         - connect_time: the total amount of time the between establishing the
           connection and closing the connection.
         - error: the error code from a failed connection.
         - errorstr: plain text description of the above error.
        """

        # Defaults
        connected = 0
        recv_string = None
        connect_time = 0.0
        error = None
        errorstr = ""

        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                time_start = time.time()
                s.connect((host, port))
                connected = 1    # port connection ok

                if send != "":
                    exec("send='%s'" % send)
                    sendlist = string.split(send, '\n')                # split each line
                    # send each line - only capture last output received
                    for line in sendlist:
                        log.log("<directive>PORT.tcp_test(): sending '%s'" % (line), 9)
                        s.send(line+'\n')

                recv_string = s.recv(1024)        # receive max 1024 bytes
                s.close()
                time_finish = time.time()

                connect_time = time_finish - time_start

            except socket.error:
                e = sys.exc_info()
                s.close()
                try:
                    error = errno.errorcode[e[1][0]]
                except KeyError:
                    error = str(e[1][0])
                errorstr = e[1][1]
                log.log("<directive>PORT.tcp_test(): socket.error: %s, %s" %
                        (e[0], e[1]), 7)

        except:
            e = sys.exc_info()
            tb = traceback.format_list(traceback.extract_tb(e[2]))
            log.log("<directive>PORT.tcp_test(): ID '%s', Uncaught exception: %s, %s, %s" %
                    (self.state.ID, e[0], e[1], tb), 3)

        return (connected, recv_string, connect_time, error, errorstr)