def tokenparser(self, toklist, toktypes, indent): self.hostport = utils.stripquote(toklist[0]) # hostname:port self.username = utils.stripquote(toklist[1]) # username self.password = utils.stripquote(toklist[2]) # password self.actionList = self.parseAction(toklist[3:]) if ':' in self.hostport: (self.host, self.port) = string.split( self.hostport, ':' ) self.port = int(self.port) else: self.host = self.hostport self.port = 110 # Set any FS-specific variables # rule = rule self.Action.varDict['pop3timinghost'] = self.host self.Action.varDict['pop3timingport'] = self.port self.Action.varDict['pop3timingusername'] = self.username self.Action.varDict['pop3timingpassword'] = self.password # define the unique ID self.ID = '%s.POP3TIMING.%s.%d.%s' % (log.hostname,self.host,self.port,self.username) log.log( "<pop3.py>POP3TIMING.tokenparser(): ID '%s' host '%s' port %d username '%s'" % (self.ID, self.host, self.port, self.username), 8 )
def __init__(self, toklist): apply( Directive.__init__, (self, toklist) ) self.name = utils.stripquote(toklist[1]) # the daemon to check for self.daemon = utils.stripquote(toklist[1]) # the daemon to check for self.ruleDict = { 'NR' : self.NR, 'R' : self.R, 'check' : self.check }
def parseArgs(self, toklist): """ Return dictionary of directive arguments. toklist is a list of directive argument lines. Each line is a list of basic tokens. Argument lines must be of the form: <name>=<value> where <name> is a 'word' and <value> is something like a string, int, float, function call, etc. """ argdict = {} for argline in toklist: if len(argline) < 3 or argline[1] != '=': log.log( "<directive>Directive.parseArgs(): invalid directive argument '%s'" % (string.join(argline)), 1) raise ParseFailure("invalid directive argument '%s'" % (string.join(argline))) if len(argline) > 3: argdict[argline[0]] = utils.stripquote( string.join(argline[2:], "")) else: argdict[argline[0]] = utils.stripquote(argline[2]) return argdict
def __init__(self, toklist): apply( Directive.__init__, (self, toklist) ) # Must be 5 tokens to make up: ['SP', 'proto', '/', 'port', ':'] if len(toklist) < 5: raise ParseError, "SP proto/port not specified correctly" if toklist[2] != '/': raise ParseError, "SP proto/port not specified correctly" self.proto = utils.stripquote(toklist[1]) # the proto to check self.port_n = utils.stripquote(toklist[3]) # the port to check
def tokenparser(self, toklist, toktypes, indent): toklist = toklist[:-1] # lose CR toktypes = toktypes[:-1] # lose CR for t in toklist: if self.subject == None: self.subject = utils.stripquote(t) elif self.message == None: self.message = utils.stripquote(t) else: # tokens left and subject/message already defined raise ParseFailure, "Parse error during MSG definition"
def tokenparser(self, toklist, toktypes, indent): for argline in toklist: for t in argline: if self.subject == None: self.subject = utils.stripquote(t) elif self.message == None: self.message = utils.stripquote(t) else: # tokens left and subject/message already defined raise ParseFailure, "Parse error during MSG definition" log.log( "<definition>MSG.tokenparser(): MSG parsed, subject:'%s' message:'%s'" % (self.subject,self.message), 8 )
def tokenparser(self, toklist, toktypes, indent): self.touchfile = utils.stripquote(toklist[0]) # test file touched by cronjob self.rule = utils.stripquote(toklist[1]) # the rule self.actionList = self.parseAction(toklist[2:]) # Set any FS-specific variables # rule = rule self.Action.varDict['rule'] = self.rule # define the unique ID self.ID = '%s.CRON.%s' % (log.hostname,self.rule) log.log( "<solaris.py>CRON.tokenparser(): ID '%s' rule '%s' action '%s'" % (self.ID, self.rule, self.actionList), 8 )
def __init__(self, *arg): apply( Directive.__init__, (self,) + arg ) self.regexp = 'COM[\t \n]+\([a-zA-Z0-9_$><=&\|.,:;%*^/!-]+\|"[a-zA-Z0-9_$><=&\|.,:;%*^/!{}()\' \t-]+"\|\'[a-zA-Z0-9_$><=&\|.,:;%*^/!{}()" \t-]+\'\)[\t \n]+\([a-zA-Z0-9_$><=&\|.,:;%*^!{}()-]+\|["\'][a-zA-Z0-9_$><=&\|.,:;%*^!{}()"\' \t-]+["\']\)[\t \n]+\(.*\)' fields = self.parseRaw() self.command = utils.stripquote(fields[0]) # the command self.rule = utils.stripquote(fields[1]) # the rule self.action = fields[2] # the action #print "<COM> command: '%s' rule: '%s' action: '%s'" % (self.command, self.rule, self.action) # Set any PID-specific variables # %com = the command # %rule = the rule self.varDict['com'] = self.command self.varDict['rule'] = self.rule
def tokenparser(self, toklist, toktypes, indent): for argline in toklist: for t in argline: if self.subject == None: self.subject = utils.stripquote(t) elif self.message == None: self.message = utils.stripquote(t) else: # tokens left and subject/message already defined raise ParseFailure, "Parse error during MSG definition" log.log( "<definition>MSG.tokenparser(): MSG parsed, subject:'%s' message:'%s'" % (self.subject, self.message), 8)
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) self.workdir = None # if we don't have 3 elements ['WORKDIR', '=', <str> ] # then raise an error if len(list) != 3: raise ParseFailure, "WORKDIR definition has %d tokens when expecting only 3" % len( list) if list[1] != '=': raise ParseFailure, "WORKDIR statement invalid" workdir = utils.stripquote(list[2]) if os.path.isdir(workdir): self.workdir = workdir else: try: os.makedirs(workdir, 0700) # create all dirs - access by user only except OSError, err: log.log( "<config>WORKDIR: cannot create '%s', %s" % (workdir, err), 4) else:
def tokenparser(self, toklist, toktypes, indent): """Parse tokenized input.""" # Expect first token to be rule if toklist[0] in self.ruleDict.keys(): # - either one of self.ruleDict self.rule = self.ruleDict[toklist[0]] # Set the rule elif toktypes[0] == 'STRING': # - or a string containing a special check self.rule = self.ruleDict['check'] self.checkstring = utils.stripquote(toklist[0]) else: raise ParseFailure, "PROC found unexpected rule '%s'" % toklist[0] self.actionList = self.parseAction(toklist[1:]) # Set any PROC-specific variables # %procp = the process name self.Action.varDict['procp'] = self.daemon # %procpid = pid of process (ie: if found running for R rule) self.Action.varDict['procpid'] = '[pid not yet defined]' # define the unique ID self.ID = '%s.PROC.%s.%s' % (log.hostname,self.name,toklist[0]) log.log( "<Directive>PROC, ID '%s' daemon '%s' rule '%s' action '%s'" % (self.ID, self.daemon, self.rule, self.actionList), 8 )
def elvindb(self, table, data=None): """Send information to remote database listener via Elvin. Data to insert in db can be specified in the data argument as 'col1=data1, col2=data2, col3=data3' or if data is None it will use self.storedict """ log.log( "<action.py>action.elvindb( table='%s' data='%s' )"%(table,data), 8 ) if eddieElvin.UseElvin == 0: log.log( "<action.py>action.elvindb(), Elvin is not available - skipping.", 8 ) return 0 try: e = eddieElvin.elvindb() except eddieElvin.ElvinError: log.log( "<action.py>action.elvindb(), Error, eddieElvin.elvindb() could not connect", 2 ) return #print "created elvindb() connection to elvin" if data == None: # if nothing passed in data storedict will be used retval = e.send(table, self.storedict) else: data = parseVars( data, self.varDict ) # substitute variables datas = string.split(data, ',') # separate key/val pairs storedict = {} for d in datas: (key,val) = string.split(d, '=') # separate key & value key = string.strip(key) # strip spaces val = utils.stripquote(val) # strip spaces then quotes # try to convert val to float or int if possible try: val = float(val) except ValueError: try: val = int(val) except ValueError: pass storedict[key] = val #print "storedict:",storedict retval = e.send(table, storedict) # kill elvin connection (I hope?!) #e._destroy() # close connection #del e # Alert if return value != 0 if retval != 0: log.log( "<action.py>action.elvindb('%s', dict), Alert, return value for e.send() is %d" % (table,retval), 3 ) else: log.log( "<action.py>action.elvindb('%s', dict): store ok" % (table), 7 )
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have 3 elements ['ELVINSCOPE', '=', <str>] then raise an error if len(list) != 3: raise ParseFailure, "ELVINSCOPE definition has %d tokens when expecting 3" % len(list) # ok, value is 3rd list element eddieElvin4.ELVINSCOPE = utils.stripquote(list[2]) # set the config option log.log( "<config>ELVINSCOPE(): elvin scope set to '%s'." % (eddieElvin4.ELVINSCOPE), 8 )
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have 3 elements ['EMAIL_REPLYTO', '=', <string>] then raise an error if len(list) != 3: raise ParseFailure, "EMAIL_REPLYTO definition has %d tokens when expecting 3" % len(list) utils.EMAIL_REPLYTO = utils.stripquote(list[2]) # set for sendmail function to use log.log( "<config>EMAIL_REPLYTO: email From: set to '%s'" % (utils.EMAIL_REPLYTO), 8 )
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have 3 elements ['LOGFILE', '=', <val>] then raise an error if len(list) != 3: raise ParseFailure, "LOGFILE definition has %d tokens when expecting 3" % len(list) # ok, value is 3rd list element log.logfile = utils.stripquote(list[2]) # set the config option log.log( "<config>LOGFILE(): logfile set to '%s'." % (log.logfile), 8 )
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have 3 elements ['SPREADPORT', '=', <int>] then # raise an error if len(list) != 3: raise ParseFailure, "SPREADPORT definition has %d tokens when expecting 3" % len(list) # ok, value is 3rd list element eddieSpread.SPREADPORT = int(utils.stripquote(list[2])) # set the config option log.log( "<config>SPREADPORT(): Spread port set to '%s'." % (eddieSpread.SPREADPORT), 8 )
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have 3 elements ['LOGFILE', '=', <val>] then raise an error if len(list) != 3: raise ParseFailure, "LOGFILE definition has %d tokens when expecting 3" % len( list) # ok, value is 3rd list element log.logfile = utils.stripquote(list[2]) # set the config option log.log("<config>LOGFILE(): logfile set to '%s'." % (log.logfile), 8)
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have 3 elements ['SENDMAIL', '=', <string>] then raise an error if len(list) != 3: raise ParseFailure, "SENDMAIL definition has %d tokens when expecting 3" % len(list) utils.SENDMAIL = utils.stripquote(list[2]) # set for sendmail function to use utils.SENDMAIL_FUNCTION="sendmail_bin" # set sendmail binary as default method log.log( "<config>SENDMAIL: set to '%s'" % (utils.SENDMAIL), 8 )
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have 3 elements ['ADMIN', '=', <str>] then # raise an error if len(list) != 3: raise ParseFailure, "ADMIN definition has %d tokens when expecting 3" % len(list) # ok, value is 3rd list element log.adminemail = utils.stripquote(list[2]) # set the config option log.log( "<config>ADMIN(): admin set to '%s'." % (log.adminemail), 8 )
def __init__(self, toklist): apply( Directive.__init__, (self, toklist) ) # Expect only 3 tokens: ( 'PORT', <host>, ':' ) if len(toklist) > 3: raise ParseFailure, "Too many tokens for PORT directive" self.host = utils.stripquote(toklist[1]) # the host self.port = None self.sendstr = None self.expect = None
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have 3 elements ['ADMIN', '=', <str>] then # raise an error if len(list) != 3: raise ParseFailure, "ADMIN definition has %d tokens when expecting 3" % len( list) # ok, value is 3rd list element log.adminemail = utils.stripquote(list[2]) # set the config option log.log("<config>ADMIN(): admin set to '%s'." % (log.adminemail), 8)
def tokenparser(self, toklist, toktypes, indent): self.rule = utils.stripquote(toklist[0]) # the rule self.actionList = self.parseAction(toklist[1:]) # Set any FS-specific variables # rule = rule self.Action.varDict['rule'] = self.rule # define the unique ID self.ID = '%s.IPF.%s' % (log.hostname,self.rule) log.log( "<ipf.py>IPF.tokenparser(): ID '%s' rule '%s' action '%s'" % (self.ID, self.rule, self.actionList), 8 )
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have 3 elements ['SENDMAIL', '=', <string>] then raise an error if len(list) != 3: raise ParseFailure, "SENDMAIL definition has %d tokens when expecting 3" % len( list) utils.SENDMAIL = utils.stripquote( list[2]) # set for sendmail function to use utils.SENDMAIL_FUNCTION = "sendmail_bin" # set sendmail binary as default method log.log("<config>SENDMAIL: set to '%s'" % (utils.SENDMAIL), 8)
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have 3 elements ['ELVINSCOPE', '=', <str>] then raise an error if len(list) != 3: raise ParseFailure, "ELVINSCOPE definition has %d tokens when expecting 3" % len( list) # ok, value is 3rd list element eddieElvin4.ELVINSCOPE = utils.stripquote( list[2]) # set the config option log.log( "<config>ELVINSCOPE(): elvin scope set to '%s'." % (eddieElvin4.ELVINSCOPE), 8)
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have 3 elements ['EMAIL_REPLYTO', '=', <string>] then raise an error if len(list) != 3: raise ParseFailure, "EMAIL_REPLYTO definition has %d tokens when expecting 3" % len( list) utils.EMAIL_REPLYTO = utils.stripquote( list[2]) # set for sendmail function to use log.log( "<config>EMAIL_REPLYTO: email From: set to '%s'" % (utils.EMAIL_REPLYTO), 8)
def tokenparser(self, toklist, toktypes, indent): toklist = toklist[:-1] # lose CR toktypes = toktypes[:-1] # lose CR while len(toklist) > 0: if self.port == None: try: self.port = int(utils.stripquote(toklist[0])) except ValueError: raise ParseFailure, "Port should be integer, found '%s'" % toklist[0] toklist = toklist[1:] elif self.sendstr == None: self.sendstr = utils.stripquote(toklist[0]) toklist = toklist[1:] elif self.expect == None: self.expect = utils.stripquote(toklist[0]) toklist = toklist[1:] else: self.actionList = self.actionList + self.parseAction(toklist) toklist = [] # Set any PORT-specific variables # %porthost = the host # %portport = the port # %portsend = the send string # %portexpect = the expect string # %portrecv = the string received from port connection (at check time) self.Action.varDict['porthost'] = self.host self.Action.varDict['portport'] = self.port self.Action.varDict['portsend'] = self.sendstr self.Action.varDict['portexpect'] = self.expect self.Action.varDict['portrecv'] = '' # define the unique ID self.ID = '%s.PORT.%s.%s' % (log.hostname,self.host,self.port) log.log( "<Directive>PORT, ID '%s' host '%s' port '%d' sendstr '%s' expect '%s'" % (self.ID, self.host, self.port, self.sendstr, self.expect), 8 )
def __init__(self, *arg): apply( Directive.__init__, (self,) + arg ) #self.regexp = 'FS[\t \n]+\([a-zA-Z0-9_/\.-]+\)[\t \n]+\([a-zA-Z0-9_><=&\|%^!-]+|[\"\'][a-zA-Z0-9_><=&\|%^!\t -]+[\"\']\)[\t \n]+\(.*\)' self.regexp = 'FS[\t \n]+\([a-zA-Z0-9_/\.-]+\)[\t \n]+\([a-zA-Z0-9_$><=&\|%^()!-]+\|["\'][a-zA-Z0-9_$><=&\|%^()! \t-]+["\']\)[\t \n]+\(.*\)' fields = self.parseRaw() self.filesystem = fields[0] # the filesystyem to check self.rule = utils.stripquote(fields[1]) # the rules self.action = fields[2] # the action log.log( "<FS> filesystem: '%s' rule: '%s' action: '%s'" % (self.filesystem, self.rule, self.action), 8 ) # Set any FS-specific variables # fsf = filesystem # fsrule = rule self.varDict['fsf'] = self.filesystem self.varDict['fsrule'] = self.rule
def tokenparser(self, toklist, toktypes, indent): self.rule = utils.stripquote(toklist[0]) # the rule self.actionList = self.parseAction(toklist[1:]) # Set any FS-specific variables # fsf = filesystem # fsrule = rule self.Action.varDict['fsf'] = self.filesystem self.Action.varDict['fsrule'] = self.rule # define the unique ID self.ID = '%s.FS.%s.%s' % (log.hostname,self.filesystem,self.rule) log.log( "<Directive>FS, ID '%s' filesystem '%s' rule '%s' action '%s'" % (self.ID, self.filesystem, self.rule, self.actionList), 8 )
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have 3 elements ['SPREADPORT', '=', <int>] then # raise an error if len(list) != 3: raise ParseFailure, "SPREADPORT definition has %d tokens when expecting 3" % len( list) # ok, value is 3rd list element eddieSpread.SPREADPORT = int(utils.stripquote( list[2])) # set the config option log.log( "<config>SPREADPORT(): Spread port set to '%s'." % (eddieSpread.SPREADPORT), 8)
def parseArgs( self, toklist ): """ Return dictionary of directive arguments. toklist is a list of directive argument lines. Each line is a list of basic tokens. Argument lines must be of the form: <name>=<value> where <name> is a 'word' and <value> is something like a string, int, float, function call, etc. """ argdict = {} for argline in toklist: if len(argline) < 3 or argline[1] != '=': log.log( "<directive>Directive.parseArgs(): invalid directive argument '%s'" % (string.join(argline)), 1) raise ParseFailure, "invalid directive argument '%s'" %(string.join(argline)) if len(argline) > 3: argdict[argline[0]] = utils.stripquote(string.join(argline[2:],"")) else: argdict[argline[0]] = utils.stripquote(argline[2]) return argdict
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have at least 3 elements ['SMTP_SERVERS', '=', <str>, [',', <str>, ...] ] # then raise an error if len(list) < 3: raise ParseFailure, "SMTP_SERVERS definition has %d tokens when expecting at least 3" % len(list) servers=",".join(list[2:]) servers = utils.stripquote(servers) servlist = string.split(servers, ',') utils.SMTP_SERVERS=servlist utils.SENDMAIL_FUNCTION="sendmail_smtp" # set smtp as default method log.log( "<config>SMTP_SERVERS: set to %s" % (", ".join(servlist)), 8 )
def tokenparser(self, toklist, toktypes, indent): for argline in toklist: if argline[0] in ('Level', 'level', 'LEVEL'): # # Level must be a number. # if types[1] != 'NUMBER': # raise ParseFailure, 'N: Level definition expects a number, received a %s' % argline[1] if argline[2] != ':': raise ParseFailure level = argline[1] self.addLevel(argline[1]) # Create level self.configLevel = argline[1] elif argline[0] in self.defs.keys(): # One of the defined assignments if argline[1] != '=': raise ParseFailure, 'Expecting "=" after "%s", got "%s' % ( argline[0], argline[1]) # assume number followed by letter at the moment... #value = string.join(argline[2:3], "") value = utils.stripquote(argline[2]) if self.defs[argline[0]] == 'TIME': # Convert time to seconds if required value = utils.val2secs(value) assignment = 'self.%s=%d' % (argline[0], value) exec assignment else: # Must be a notification command (or list of commands) notiflist = self.getNotifList(argline) if len(notiflist) == 0: raise ParseFailure, "Notification list is empty" else: if self.configLevel == -1: # Error if no levels defined yet raise ParseFailure, "No notification levels have been defined yet" self.addNotif(self.configLevel, indent, notiflist) # Need reference to M objects self.MDict = self.parent.MDict # Finished parsing tokens log.log("<definition>N.tokenparser(): '%s'" % (self), 8)
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have at least 4 elements ['CLASS', '=', <str>, [',', <str>, ...] ] # then raise an error if len(list) < 3: raise ParseFailure, "INTERPRETERS definition has %d tokens when expecting 3" % len(list) self.name = list[1] hosts = list[3:] # pull hosts out hosts = string.join(hosts, '') # join all arguments hosts = utils.stripquote(hosts) # in case the arguments are in quotes (optional) self.hosts = string.split(hosts, ',') # finally, split into list of hosts log.log( "<config>CLASS(): class created %s:%s." % (self.name,self.hosts), 8 )
def __init__( self, list, typelist ): apply( ConfigOption.__init__, (self,list, typelist) ) # if we don't have 3 elements ['INTERPRETERS', '=', <str>] then raise an error if len(list) != 3: raise ParseFailure, "INTERPRETERS definition has %d tokens when expecting 3" % len(list) value = utils.stripquote(list[2]) # chris 2004-12-03: this is a terrible way to set interpreters # TODO re-write this to interface with proc properly try: proc.interpreters = string.split(value, ',') except NameError: log.log( "<config>INTERPRETERS(): interpreters ignored - no proc module.", 5 ) else: log.log( "<config>INTERPRETERS(): interpreters defined as '%s'." % (proc.interpreters), 8 )
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have at least 3 elements ['SMTP_SERVERS', '=', <str>, [',', <str>, ...] ] # then raise an error if len(list) < 3: raise ParseFailure, "SMTP_SERVERS definition has %d tokens when expecting at least 3" % len( list) servers = ",".join(list[2:]) servers = utils.stripquote(servers) servlist = string.split(servers, ',') utils.SMTP_SERVERS = servlist utils.SENDMAIL_FUNCTION = "sendmail_smtp" # set smtp as default method log.log("<config>SMTP_SERVERS: set to %s" % (", ".join(servlist)), 8)
def __init__(self, toklist): apply( Directive.__init__, (self, toklist) ) # Must be 3 tokens to make up: ['SP', 'ifname', ':'] if len(toklist) != 3: raise ParseError, "IF parse error, expected 3 tokens, found %d" % (len(toklist)) if toklist[2] != ':': raise ParseError, "IF parse error, no colon" self.name = utils.stripquote(toklist[1]) # the interface name self.rule = None self.checkstring = '' self.ruleDict = { 'NE' : self.NE, 'EX' : self.EX, 'check' : self.check }
def __init__( self, list ): apply( ConfigOption.__init__, (self,list) ) # if the last token isn't a carriage-return then we don't have the # whole line yet... if list[-1] != '\012': raise ParseNotcomplete # if we don't have 4 elements ['ELVINHOST', '=', <str>, '012'] then # raise an error if len(list) != 4: raise ParseFailure, "ELVINHOST definition has %d tokens when expecting 4" % len(list) # ok, value is 3rd list element eddieElvin.ELVINHOST = utils.stripquote(list[2]) # set the config option log.log( "<Config>ELVINHOST(), elvin host set to '%s'." % (eddieElvin.ELVINHOST), 6 )
def __init__( self, list ): apply( ConfigOption.__init__, (self,list) ) # if the last token isn't a carriage-return then we don't have the # whole line yet... if list[-1] != '\012': raise ParseNotcomplete # if we don't have 4 elements ['INTERPRETERS', '=', <str>, '012'] then # raise an error if len(list) != 4: raise ParseFailure, "INTERPRETERS definition has %d tokens when expecting 4" % len(list) value = utils.stripquote(list[2]) proc.interpreters = string.split(value, ',') log.log( "<Config>INTERPRETERS(), interpreters defined as '%s'." % (proc.interpreters), 6 )
def __init__( self, list ): apply( ConfigOption.__init__, (self,list) ) # if the last token isn't a carriage-return then we don't have the # whole line yet... if list[-1] != '\012': raise ParseNotcomplete # if we don't have 4 elements ['ADMIN', '=', <str>, '012'] then # raise an error if len(list) != 4: raise ParseFailure, "ADMIN definition has %d tokens when expecting 4" % len(list) # ok, value is 3rd list element log.adminemail = utils.stripquote(list[2]) # set the config option log.log( "<Config>ADMIN(), admin set to '%s'." % (log.adminemail), 6 )
def tokenparser(self, toklist, toktypes, indent): for argline in toklist: if argline[0] in ('Level', 'level', 'LEVEL'): # # Level must be a number. # if types[1] != 'NUMBER': # raise ParseFailure, 'N: Level definition expects a number, received a %s' % argline[1] if argline[2] != ':': raise ParseFailure level = argline[1] self.addLevel(argline[1]) # Create level self.configLevel = argline[1] elif argline[0] in self.defs.keys(): # One of the defined assignments if argline[1] != '=': raise ParseFailure, 'Expecting "=" after "%s", got "%s' % (argline[0], argline[1]) # assume number followed by letter at the moment... #value = string.join(argline[2:3], "") value = utils.stripquote(argline[2]) if self.defs[argline[0]] == 'TIME': # Convert time to seconds if required value = utils.val2secs(value) assignment = 'self.%s=%d' % (argline[0],value) exec assignment else: # Must be a notification command (or list of commands) notiflist = self.getNotifList( argline ) if len(notiflist) == 0: raise ParseFailure, "Notification list is empty" else: if self.configLevel == -1: # Error if no levels defined yet raise ParseFailure, "No notification levels have been defined yet" self.addNotif(self.configLevel,indent,notiflist) # Need reference to M objects self.MDict = self.parent.MDict # Finished parsing tokens log.log( "<definition>N.tokenparser(): '%s'" % (self), 8 )
def tokenparser(self, toklist, toktypes, indent): """Parse rest of rule (after ':').""" # Expect first token to be rule (a string) if toktypes[0] != 'STRING': raise ParseError, "SYS parse error, rule is not string." self.rulestring = utils.stripquote(toklist[0]) self.actionList = self.parseAction(toklist[1:]) self.Action.varDict['sysrule'] = self.rulestring # define the unique ID self.ID = '%s.SYS.%s' % (log.hostname,self.rulestring) log.log( "<Directive>SYS, ID '%s' rule '%s' action '%s'" % (self.ID, self.rulestring, self.actionList), 8 )
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have 3 elements ['INTERPRETERS', '=', <str>] then raise an error if len(list) != 3: raise ParseFailure, "INTERPRETERS definition has %d tokens when expecting 3" % len( list) value = utils.stripquote(list[2]) interpreters = string.split(value, ',') # The interpreters list is stored in the proc module for the current system procobj = directive.data_modules.import_module('proc') procobj.interpreters = interpreters log.log( "<config>INTERPRETERS(): interpreters defined as '%s'." % (procobj.interpreters), 8)
def elvindb(self, table, data=None): """Send information to remote database listener via Elvin. Data to insert in db can be specified in the data argument as 'col1=data1, col2=data2, col3=data3' or if data is None it will use self.storedict """ log.log( "<action>action.elvindb( table='%s' data='%s' )"%(table,data), 6 ) if eddieElvin4.UseElvin == 0: log.log( "<action>action.elvindb(): Elvin is not available - skipping.", 5 ) return 0 if data == None: # if nothing passed in data storedict will be used #retval = e.send(table, self.storedict) retval = elvin.elvindb(table, self.storedict) else: data = utils.parseVars( data, self.varDict ) # substitute variables datas = string.split(data, ',') # separate key/val pairs storedict = {} for d in datas: (key,val) = string.split(d, '=') # separate key & value key = string.strip(key) # strip spaces val = utils.stripquote(val) # strip spaces then quotes # try to convert val to float or int if possible try: val = float(val) except ValueError: try: val = int(val) except ValueError: pass storedict[key] = val retval = elvin.elvindb(table, storedict) # Alert if return value != 0 if retval != 0: log.log( "<action>action.elvindb('%s', dict): Alert, return value for e.send() is %d" % (table,retval), 5 ) else: log.log( "<action>action.elvindb('%s', dict): completed" % (table), 6 )
def __init__(self, list, typelist): apply(ConfigOption.__init__, (self, list, typelist)) # if we don't have at least 4 elements ['CLASS', '=', <str>, [',', <str>, ...] ] # then raise an error if len(list) < 3: raise ParseFailure, "INTERPRETERS definition has %d tokens when expecting 3" % len( list) self.name = list[1] hosts = list[3:] # pull hosts out hosts = string.join(hosts, '') # join all arguments hosts = utils.stripquote( hosts) # in case the arguments are in quotes (optional) self.hosts = string.split(hosts, ',') # finally, split into list of hosts log.log( "<config>CLASS(): class created %s:%s." % (self.name, self.hosts), 8)
def __init__(self, list, toktypes): apply(Definition.__init__, (self, list, toktypes)) # if we don't have 4 elements ['ALIAS', <str>, '=', <value>] then # raise an error if len(list) != 4: raise ParseFailure, "ALIAS definition has %d tokens when expecting 4" % len( list) # OK, grab values self.name = list[1] # the name of this ALIAS self.value = list[3] # the value assigned to it # convert value to int, float or string without quotes, if necessary. if toktypes[3] == 'NUMBER': if string.find(self.value, '.') == -1: self.value = int(self.value) # integer else: self.value = float(self.value) # float elif toktypes[3] == 'STRING': self.value = utils.stripquote( self.value) # the text that is assigned to it log.log( "<definition>ALIAS: ALIAS created: %s=%s" % (self.name, self.value), 8)
def __init__(self, toklist): # Check toklist for valid tokens if len(toklist) < 2: # need at least 2 tokens raise ParseFailure, "Directive expected at least 2 tokens, found %d" % len( toklist) if len(toklist) > 3: # no more than 3 tokens raise ParseFailure, "Directive expected no more than 3 tokens, found %d" % len( toklist) if toklist[-1] != ':': # last token should be a ':' raise ParseFailure, "Directive expected ':' but didn't find one" self.ID = None # No ID by default if len(toklist) == 3: self.ID = utils.stripquote(toklist[1]) # grab ID if given self.basetype = 'Directive' # the object can know its own basetype self.type = toklist[0] # the directive type of this instance self.request_collector() # request data collector reference self.hastokenparser = 1 # tell parser this object has a separate tokenparser() self.Action = action.action() # create new action instance self.defaultVarDict = { } # dictionary of variables used by action strings self.args = Args() # Container for arguments #self.args.actionList = [] # each directive will have a list of actions #self.args.act2okList = [] # a list of actions for failed state changing to ok #self.args.actelseList = [] # a list of actions for state remaining ok # Set up informational variables - these are common to all Directives # %(hostname)s = hostname # %(h)s = hostname (shorthand for '%(hostname)s') self.defaultVarDict['hostname'] = log.hostname self.defaultVarDict['h'] = log.hostname # Create initial variable dictionary self.Action.varDict = {} # Set default output displayed on console connections self.console_output = '%(state)s' # List of directives this directive is dependent on self.actiondependson = [] # action dependencies self.checkdependson = [] # check dependencies # directives keep state information about themselves self.state = State(self) self.requeueTime = None # specific requeue time can be specified self.args.numchecks = 1 # perform only 1 check at a time by default self.args.checkwait = 0 # time to wait in between multiple checks self.args.template = None # no template by default self.args.disabled = False # default "disabled" state to not disabled self.current_actionperiod = 0 # reset the current actionperiod self.lastactiontime = 0 # time previous actions were called self.history_size = 0 # keep no history by default self.history = None # keep historical data for checks, if required self.excludehosts = [ ] # chris 2002-12-24: hosts to exclude from directive execution self.actionmaxcalls = None # chris 2002-12-24: can set limit on number of action calls self.performedactions = 0 # chris 2003-10-03: clear actions called flag
class State: """Keep state of tokenization as config is being parsed.""" def __init__(self, Config): self.groupStack = utils.Stack() # Stack to store groups on temporarily self.direcStack = utils.Stack() # Stack to store direcs on temporarily self.direcStack.push(Config) self.Config = Config self.indent = 0 # Indentation level self.direc = None # current directive self.reset() # Reset state def reset(self): self.toklist = [] # clear token list self.toktypes = [] # clear token types list self.direcmode = 0 # whether currently parsing directive arguments self.direcindent = 0 # indent level of directive definition self.direcargs = [] # current directive arguments self.directypes = [] # current directive arguments (types) self.notfirstdirecline = 0 # first directive line marker def tokeneater(self, ttype, token, (srow, scol), (erow, ecol), line): """Eddie's token eater! Parses the tokens given to it (from tokenize.tokenize()) and uses them to create the configuration information.""" try: #DEBUG #print " " #print "direcmode:",self.direcmode #print "direcindent:",self.direcindent #print "indent:",self.indent #print "notfirstdirecline:",self.notfirstdirecline # The type of token toktype = tokenize.tok_name[ttype] #DEBUG: #print "%d,%d-%d,%d:\t%s\t%s" % \ # (srow, scol, erow, ecol, toktype, repr(token)) # Don't care about single CRs (empty lines) so skip over them if token == '\012' and len(self.toklist) == 0: return # Handle indentation/dedentations... if toktype == "INDENT": self.indent = self.indent + 1 if self.direcmode == 0: # if not waiting for directive args: self.direcStack.push(self.direc) # keep track of direc's self.reset() # reset state return if toktype == "DEDENT": self.indent = self.indent - 1 if self.indent < 0: # this should not happen... raise config.ParseFailure, "Indentation error." if self.direcmode == 0: # if not waiting for directive args: self.prevdirec = self.direcStack.pop( ) # Restore previous direc if self.prevdirec.type == 'Config': self.Config = self.groupStack.pop() self.direc = self.prevdirec self.reset() # reset state elif self.indent <= self.direcindent: # got all directive arguments # Now allow the directive to parse the tokens try: self.direc.Config = self.Config self.direc.tokenparser(self.direcargs, self.directypes, self.indent) except TemplateDirective: log.log( "<parseConfig>tokeneater(), directive is a Template, args: %s" % (dir(self.direc.args)), 8) if self.indent < self.direcindent: # back to previous directive level self.prevdirec = self.direcStack.pop() self.direc = self.prevdirec self.reset() # reset state return if toktype == "ERRORTOKEN": # Raise a ParseFailure for ERRORTOKEN raise config.ParseFailure, "Illegal characters in config." if toktype == "NAME": # Assign 'None' values properly if token == "None": token = None # Substitute ALIAS variables if possible elif self.Config.aliasDict.has_key(token): aval = self.Config.aliasDict[token] # replace token with value and fix toklist if type(aval) == type("string"): aval = '"%s"' % (aval) log.log( "<parseConfig>tokeneater(), ALIAS substituted %s for %s" % (aval, token), 8) token = aval if toktype != "COMMENT" and token != "\012": # If token not a comment, newline, indent or dedent then add to our list of # tokens. self.toklist.append(token) self.toktypes.append(toktype) # DEBUG #print "toklist:",self.toklist if self.direcmode > 0 and token == '\012': #self.direcargs = self.direcargs + self.toklist self.direcargs.append(self.toklist) #self.directypes = self.directypes + self.toktypes self.directypes.append(self.toktypes) self.toklist = [] # clear token list self.toktypes = [] # clear token types list self.notfirstdirecline = 1 # passed first directive line return # If waiting for directive arguments, and indent level is same as directive # indent level, and this not first directive line, directive must be ready # for creation... if self.direcmode > 0 and self.indent == self.direcindent and self.notfirstdirecline == 1: try: self.direc.Config = self.Config self.direc.tokenparser(self.direcargs, self.directypes, self.indent) except TemplateDirective: log.log( "<parseConfig>tokeneater(), directive is a Template, args: %s" % (dir(self.direc.args)), 8) savetoklist = self.toklist # save token list - not parsed yet savetoktypes = self.toktypes # save token types self.reset() # reset state self.toklist = savetoklist # restore token list self.toktypes = savetoktypes # restore token types return # Only continue if the last token is a ':' or CR if len(self.toklist) < 1 or (self.direcmode > 0 and token != '\012' ) or (self.direcmode == 0 and token != ':' and token != '\012'): return # If the only token is a CR, throw it away and continue # if len(self.toklist) == 1 and self.toklist[0] == '\012': # self.reset() # return # See if we can do anything with the current list of tokens. if self.toklist[0] == 'INCLUDE': # recursively read the INCLUDEd file file = utils.stripquote(self.toklist[1]) log.log( "<parseConfig>tokeneater(), reading INCLUDEd file '%s'" % file, 8) newstate = State(self.Config) newstate.filename = file # Start parsing the INCLUDEd file. if file[0] == '/': readFile(file, newstate) else: readFile(os.path.join(self.dir, file), newstate) # Reset state and token lists self.reset() # reset state return elif self.toklist[0] in ('group', 'Group', 'GROUP'): # Create new rule group newgrp = self.Config.newgroup(self.toklist, self.toktypes, self.Config) self.reset() # reset state self.direc = newgrp self.groupStack.push(self.Config) self.Config = newgrp return elif config.keywords.has_key(self.toklist[0]): # Create a new object (not a Directive) direc = config.keywords[self.toklist[0]](self.toklist, self.toktypes) self.direc = direc if direc == None: raise ParseFailure, "Object creation failed." # tell object who its parent is self.prevdirec = self.direcStack.top() self.direc.parent = self.prevdirec self.reset() # reset state try: if direc.hastokenparser: # some objects must wait for more multi-line arguments self.direcmode = 1 self.direcindent = self.indent except: pass # 'give' object to parent self.prevdirec = self.direcStack.top() self.prevdirec.give(direc) self.direc.scanperiod = config.scanperiod # set default scanperiod return elif config.directives.has_key(self.toklist[0]): # Create new directive direc = config.directives[self.toklist[0]](self.toklist) self.direc = direc if direc == None: raise ParseFailure, "Directive creation failed." # tell directive who its parent is self.prevdirec = self.direcStack.top() self.direc.parent = self.prevdirec self.reset() # reset state try: if direc.hastokenparser: # some objects must wait for more multi-line arguments self.direcmode = 1 self.direcindent = self.indent except: pass # 'give' object to parent self.prevdirec = self.direcStack.top() self.prevdirec.give(direc) self.direc.scanperiod = config.scanperiod # set default scanperiod return else: raise config.ParseFailure("Syntax error") self.reset() # reset state except config.ParseFailure, msg: parseFailure(msg, (srow, scol), (erow, ecol), line, self.filename) log.sendadminlog() sys.exit(-1)