syslog.LOG_ERR

Here are the examples of the python api syslog.LOG_ERR taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

151 Examples 7

Example 1

Project: thus
Source File: misc.py
View license
def execute(*args):
    """runs args* in shell mode. Output status is taken."""

    log_args = ['log-output', '-t', 'ubiquity']
    log_args.extend(args)

    try:
        status = subprocess.call(log_args)
    except IOError as e:
        syslog.syslog(syslog.LOG_ERR, ' '.join(log_args))
        syslog.syslog(syslog.LOG_ERR, "OS error({0}): {1}".format(e.errno, e.strerror))
        return False
    else:
        if status != 0:
            syslog.syslog(syslog.LOG_ERR, ' '.join(log_args))
            return False
        syslog.syslog(' '.join(log_args))
        return True

Example 2

Project: thus
Source File: misc.py
View license
def execute(*args):
    """runs args* in shell mode. Output status is taken."""

    log_args = ['log-output', '-t', 'ubiquity']
    log_args.extend(args)

    try:
        status = subprocess.call(log_args)
    except IOError as e:
        syslog.syslog(syslog.LOG_ERR, ' '.join(log_args))
        syslog.syslog(syslog.LOG_ERR, "OS error({0}): {1}".format(e.errno, e.strerror))
        return False
    else:
        if status != 0:
            syslog.syslog(syslog.LOG_ERR, ' '.join(log_args))
            return False
        syslog.syslog(' '.join(log_args))
        return True

Example 3

Project: laikaboss
Source File: laikamilter.py
View license
    def _addHeader(self,name,value):
        try:
            if value:    # add header
                self.addheader(name,value)
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            log = "%s Error adding header %s" % (self.uuid, repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
            log = "%s: %s" % (name,value)
            self.logger.writeLog(syslog.LOG_ERR, "%s Tried to Add: %s"%(self.uuid, str(log)))

Example 4

Project: laikaboss
Source File: laikamilter.py
View license
    def _getReturnToMTAValue(self, dispositioner):
        if (dispositioner.strScanResult.lower() in self.milterConfig.dispositionModes):
            rtnToMTA = self.milterConfig.dispositionModes[dispositioner.strScanResult.lower()]
        else: #Default if not included
            rtnToMTA = self.milterConfig.dispositionModes["default"]
            self.logger.writeLog(syslog.LOG_ERR, "Disposition: %s (lc) was not in available dispositions, using default (%s)"%(str(dispositioner.strScanResult.lower()), str(self.milterConfig.dispositionModes["default"])))
        
        return rtnToMTA

Example 5

Project: laikaboss
Source File: laikamilter.py
View license
    def _getSpecialHeaderLines(self, lname, val):
        if (lname == "subject"):
            self.subject = val
        if (lname == "message-id"):
            self.messageID = val
            self.messageID = self.messageID.replace("<", "")
            self.messageID = self.messageID.replace(">", "")
        if (lname == "date"):
            try:
                self.messageDate = formatdate(mktime_tz(parsedate_tz(val.split('\n')[0])), True)
            except:
                log = self.uuid+" Error Parsing "+str(val)+" to RFC822 Date"
                self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))

Example 6

Project: FuzzLabs
Source File: webserver.py
View license
def do_get(address, port, uri, secret, timeout=5):
    target = "http://" + address + ":" + str(port) + uri
    headers = {'X-FuzzLabs-Auth': secret}
    try:
        r = requests.get(target, headers=headers, timeout=timeout)
    except Exception, ex:
        syslog.syslog(syslog.LOG_ERR,
                      "failed to request data from engine: %s" % str(ex))
        return None
    if r.status_code != requests.codes.ok: return None
    data = None
    try:
        data = json.loads(r.text)
    except Exception, ex:
        return None
    return data

Example 7

Project: portage
Source File: mod_syslog.py
View license
def process(mysettings, key, logentries, fulltext):
	syslog.openlog("portage", syslog.LOG_ERR | syslog.LOG_WARNING | syslog.LOG_INFO | syslog.LOG_NOTICE, syslog.LOG_LOCAL5)
	for phase in EBUILD_PHASES:
		if not phase in logentries:
			continue
		for msgtype, msgcontent in logentries[phase]:
			if isinstance(msgcontent, basestring):
				msgcontent = [msgcontent]
			for line in msgcontent:
				line = "%s: %s: %s" % (key, phase, line)
				if sys.hexversion < 0x3000000 and not isinstance(line, bytes):
					# Avoid TypeError from syslog.syslog()
					line = line.encode(_encodings['content'],
						'backslashreplace')
				syslog.syslog(_pri[msgtype], line.rstrip("\n"))
	syslog.closelog()

Example 8

Project: laikaboss
Source File: laikamilter.py
View license
    def _writeFileToDisk(self):
        if self.archiveFileName:
            try:
                fp = open(self.archiveFileName, "wb")
                fp.write(self.fileBuffer)
                fp.flush()
                fp.close()
            except IOError:
                log = self.uuid+" Could not open "+ self.archiveFileName+ " for writing"
                self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))

Example 9

Project: snmp_passpersist
Source File: snmp-asterisk.py
View license
    def setter(self, oid, type_, value):
        try:
            section, attr_name = self.getSectionAttr(oid)
        except:
            syslog.syslog(syslog.LOG_ERR, 'SipSnmp: unknown OID: %s' % oid)
            return False
        try:
            self.settings.set(section, attr_name, str(value))
            self.settings.write()
            self.update()
            self.snmp.commit()
            return True
        except Exception as e:
            syslog.syslog(syslog.LOG_ERR,
                          'SipSnmp: error calling set(%s, %s, %s): %s' %
                          (section, attr_name, str(value), str(e)))
            return False

Example 10

Project: thus
Source File: misc.py
View license
def set_groups_for_uid(uid):
    if uid == os.geteuid() or uid == os.getuid():
        return
    user = pwd.getpwuid(uid).pw_name
    try:
        os.setgroups([g.gr_gid for g in grp.getgrall() if user in g.gr_mem])
    except OSError:
        import traceback

        for line in traceback.format_exc().split('\n'):
            syslog.syslog(syslog.LOG_ERR, line)

Example 11

Project: thus
Source File: misc.py
View license
def get_release():
    if get_release.release_info is None:
        try:
            with open('/cdrom/.disk/info') as fp:
                line = fp.readline()
                if line:
                    line = line.split()
                    if line[2] == 'LTS':
                        line[1] += ' LTS'
                    get_release.release_info = ReleaseInfo(name=line[0], version=line[1])
        except Exception:
            syslog.syslog(syslog.LOG_ERR, 'Unable to determine the release.')

        if not get_release.release_info:
            get_release.release_info = ReleaseInfo(name='Ubuntu', version='')
    return get_release.release_info

Example 12

Project: infrastructure-puppet
Source File: log.py
View license
def exception():
    logfile = os.path.join(cfg.repo_dir, "error.log")
    tb = traceback.format_exc()
    # Send error message to syslog
    syslog.syslog(syslog.LOG_ERR, "{0} - {1}".format(cfg.script_name, tb))
    # Send error message to script log error.log 
    with open(logfile, "a") as handle:
        handle.write("[{0}] {1}".format(time.ctime(), tb))

Example 13

Project: laikaboss
Source File: laikamilter.py
View license
    def _addHeader(self,name,value):
        try:
            if value:    # add header
                self.addheader(name,value)
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            log = "%s Error adding header %s" % (self.uuid, repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
            log = "%s: %s" % (name,value)
            self.logger.writeLog(syslog.LOG_ERR, "%s Tried to Add: %s"%(self.uuid, str(log)))

Example 14

Project: backintime
Source File: logger.py
View license
def error(msg , parent = None, traceDepth = 0):
    if DEBUG:
        msg = '%s %s' %(_debugHeader(parent, traceDepth), msg)
    print('%sERROR%s: %s' %(bcolors.FAIL, bcolors.ENDC, msg), file=sys.stderr)
    for line in tools.wrapLine(msg):
        syslog.syslog(syslog.LOG_ERR, 'ERROR: ' + line)

Example 15

Project: laikaboss
Source File: laikamilter.py
View license
    def eoh(self):
        try:
            self._writeHeaderToFP()
        except:
            log = self.uuid+" Uncaught Exception in EOH"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 16

Project: neubot
Source File: system_posix.py
View license
def __logger(severity, message):

    ''' Log @message at the given @severity using syslog '''

    #
    # Implemented using syslog becuse SysLogHandler is
    # difficult to use: you need to know the path to the
    # system specific ``/dev/log``.
    #

    if severity == 'ERROR':
        syslog.syslog(syslog.LOG_ERR, message)
    elif severity == 'WARNING':
        syslog.syslog(syslog.LOG_WARNING, message)
    elif severity == 'DEBUG':
        syslog.syslog(syslog.LOG_DEBUG, message)
    else:
        syslog.syslog(syslog.LOG_INFO, message)

Example 17

Project: laikaboss
Source File: laikamilter.py
View license
    def _getSpecialHeaderLines(self, lname, val):
        if (lname == "subject"):
            self.subject = val
        if (lname == "message-id"):
            self.messageID = val
            self.messageID = self.messageID.replace("<", "")
            self.messageID = self.messageID.replace(">", "")
        if (lname == "date"):
            try:
                self.messageDate = formatdate(mktime_tz(parsedate_tz(val.split('\n')[0])), True)
            except:
                log = self.uuid+" Error Parsing "+str(val)+" to RFC822 Date"
                self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))

Example 18

Project: snmp_passpersist
Source File: snmp-asterisk.py
View license
    def setter(self, oid, type_, value):
        try:
            section, attr_name = self.getSectionAttr(oid)
        except:
            syslog.syslog(syslog.LOG_ERR, 'SipSnmp: unknown OID: %s' % oid)
            return False
        try:
            self.settings.set(section, attr_name, str(value))
            self.settings.write()
            self.update()
            self.snmp.commit()
            return True
        except Exception as e:
            syslog.syslog(syslog.LOG_ERR,
                          'SipSnmp: error calling set(%s, %s, %s): %s' %
                          (section, attr_name, str(value), str(e)))
            return False

Example 19

Project: thus
Source File: misc.py
View license
def get_release():
    if get_release.release_info is None:
        try:
            with open('/cdrom/.disk/info') as fp:
                line = fp.readline()
                if line:
                    line = line.split()
                    if line[2] == 'LTS':
                        line[1] += ' LTS'
                    get_release.release_info = ReleaseInfo(name=line[0], version=line[1])
        except Exception:
            syslog.syslog(syslog.LOG_ERR, 'Unable to determine the release.')

        if not get_release.release_info:
            get_release.release_info = ReleaseInfo(name='Ubuntu', version='')
    return get_release.release_info

Example 20

Project: neubot
Source File: unix.py
View license
def main():
    ''' Wrapper around the real __main() '''
    try:
        __main()
    except SystemExit:
        raise
    except:
        try:
            why = asyncore.compact_traceback()
            syslog.syslog(syslog.LOG_ERR, 'Unhandled exception: %s' % str(why))
        except:
            pass
        sys.exit(1)

Example 21

Project: infrastructure-puppet
Source File: log.py
View license
def exception():
    logfile = os.path.join(cfg.repo_dir, "error.log")
    tb = traceback.format_exc()
    # Send error message to syslog
    syslog.syslog(syslog.LOG_ERR, "{0} - {1}".format(cfg.script_name, tb))
    # Send error message to script log error.log 
    with open(logfile, "a") as handle:
        handle.write("[{0}] {1}".format(time.ctime(), tb))

Example 22

Project: thus
Source File: misc.py
View license
@raise_privileges
def get_install_medium():
    if not get_install_medium.medium:
        try:
            if os.access('/cdrom', os.W_OK):
                get_install_medium.medium = 'USB'
            else:
                get_install_medium.medium = 'CD'
        except Exception:
            syslog.syslog(
                syslog.LOG_ERR, "Unable to determine install medium.")
            get_install_medium.medium = 'CD'
    return get_install_medium.medium

Example 23

Project: Cnchi
Source File: extra.py
View license
def set_groups_for_uid(uid):
    """ Set groups for user id uid """
    if uid == os.geteuid() or uid == os.getuid():
        return

    user = pwd.getpwuid(uid).pw_name

    try:
        os.setgroups([g.gr_gid for g in grp.getgrall() if user in g.gr_mem])
    except OSError:
        import traceback

        for line in traceback.format_exc().split('\n'):
            syslog.syslog(syslog.LOG_ERR, line)

Example 24

Project: laikaboss
Source File: laikamilter.py
View license
    def _writeFileToDisk(self):
        if self.archiveFileName:
            try:
                fp = open(self.archiveFileName, "wb")
                fp.write(self.fileBuffer)
                fp.flush()
                fp.close()
            except IOError:
                log = self.uuid+" Could not open "+ self.archiveFileName+ " for writing"
                self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))

Example 25

Project: Cnchi
Source File: extra.py
View license
def set_groups_for_uid(uid):
    """ Set groups for user id uid """
    if uid == os.geteuid() or uid == os.getuid():
        return

    user = pwd.getpwuid(uid).pw_name

    try:
        os.setgroups([g.gr_gid for g in grp.getgrall() if user in g.gr_mem])
    except OSError:
        import traceback

        for line in traceback.format_exc().split('\n'):
            syslog.syslog(syslog.LOG_ERR, line)

Example 26

Project: infrastructure-puppet
Source File: log.py
View license
def exception():
    logfile = os.path.join(cfg.repo_dir, "error.log")
    tb = traceback.format_exc()
    # Send error message to syslog
    syslog.syslog(syslog.LOG_ERR, "{0} - {1}".format(cfg.script_name, tb))
    # Send error message to script log error.log 
    with open(logfile, "a") as handle:
        handle.write("[{0}] {1}".format(time.ctime(), tb))

Example 27

Project: FuzzLabs
Source File: EngineThread.py
View license
    def do_get(self, address, port, uri, secret, timeout=5):
        target = "http://" + address + ":" + str(port) + uri
        headers = {'X-FuzzLabs-Auth': secret}
        try:
            r = requests.get(target, headers=headers, timeout=timeout)
        except Exception, ex:
            syslog.syslog(syslog.LOG_ERR,
                          "failed to request data from engine: %s" % str(ex))
            return None
        if r.status_code != requests.codes.ok: return None
        data = None
        try:
            data = json.loads(r.text)
        except Exception, ex:
            return None
        return data

Example 28

Project: laikaboss
Source File: laikamilter.py
View license
    def body(self,chunk):        # copy body to temp file
        try:
            if (isinstance(chunk, str)):
                chunk = chunk.replace("\r\n", "\n")
            self.fpb.write(chunk)
            self.fpb.flush()
        except:
            log = self.uuid+" Uncaught Exception in Body"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 29

Project: FuzzLabs
Source File: EngineThread.py
View license
    def engine_offline(self):
        syslog.syslog(syslog.LOG_ERR,
                      "engine %s offline, disabling" % self.engine.name)
        self.enqueue({
            "item":   "engine",
            "action": "disable",
            "data":   self.engine
        })

Example 30

Project: laikaboss
Source File: laikamilter.py
View license
    def _checkFilePath(self, path):
        try:
            if not os.path.exists(path):
                os.makedirs(path)
        except OSError:
            log = "Could not create "+ path
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))

Example 31

Project: neubot
Source File: unix.py
View license
def _download_and_verify_update(server='releases.neubot.org'):
    '''
     Wrapper around __download_and_verify_update() that catches
     and handles exceptions.
    '''
    try:
        channel = CONFIG['channel']
        return __download_and_verify_update(server, channel)
    except:
        why = asyncore.compact_traceback()
        syslog.syslog(syslog.LOG_ERR,
                      '_download_and_verify_update: %s' %
                      str(why))
        return None

Example 32

Project: laikaboss
Source File: laikamilter.py
View license
    def header(self,name,val):
        try:
            lname = name.lower()
            tname = name.strip()
            tval  = val.strip()
            headerstring = "%s: %s\n"%(name, 
                                      val
                                     )
            self.headers.append(headerstring)
            
            self._getSpecialHeaderLines(lname, val)
        except:
            log = self.uuid+" Uncaught Exception in Header"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 33

Project: portage-funtoo
Source File: mod_syslog.py
View license
def process(mysettings, key, logentries, fulltext):
	syslog.openlog("portage", syslog.LOG_ERR | syslog.LOG_WARNING | syslog.LOG_INFO | syslog.LOG_NOTICE, syslog.LOG_LOCAL5)
	for phase in EBUILD_PHASES:
		if not phase in logentries:
			continue
		for msgtype,msgcontent in logentries[phase]:
			if isinstance(msgcontent, basestring):
				msgcontent = [msgcontent]
			for line in msgcontent:
				line = "%s: %s: %s" % (key, phase, line)
				if sys.hexversion < 0x3000000 and not isinstance(line, bytes):
					# Avoid TypeError from syslog.syslog()
					line = line.encode(_encodings['content'], 
						'backslashreplace')
				syslog.syslog(_pri[msgtype], line.rstrip("\n"))
	syslog.closelog()

Example 34

Project: laikaboss
Source File: laikamilter.py
View license
    def body(self,chunk):        # copy body to temp file
        try:
            if (isinstance(chunk, str)):
                chunk = chunk.replace("\r\n", "\n")
            self.fpb.write(chunk)
            self.fpb.flush()
        except:
            log = self.uuid+" Uncaught Exception in Body"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 35

Project: neubot
Source File: unix.py
View license
def main():
    ''' Wrapper around the real __main() '''
    try:
        __main()
    except SystemExit:
        raise
    except:
        try:
            why = asyncore.compact_traceback()
            syslog.syslog(syslog.LOG_ERR, 'Unhandled exception: %s' % str(why))
        except:
            pass
        sys.exit(1)

Example 36

Project: laikaboss
Source File: laikamilter.py
View license
    def _getReturnToMTAValue(self, dispositioner):
        if (dispositioner.strScanResult.lower() in self.milterConfig.dispositionModes):
            rtnToMTA = self.milterConfig.dispositionModes[dispositioner.strScanResult.lower()]
        else: #Default if not included
            rtnToMTA = self.milterConfig.dispositionModes["default"]
            self.logger.writeLog(syslog.LOG_ERR, "Disposition: %s (lc) was not in available dispositions, using default (%s)"%(str(dispositioner.strScanResult.lower()), str(self.milterConfig.dispositionModes["default"])))
        
        return rtnToMTA

Example 37

Project: neubot
Source File: system_posix.py
View license
def __logger(severity, message):

    ''' Log @message at the given @severity using syslog '''

    #
    # Implemented using syslog becuse SysLogHandler is
    # difficult to use: you need to know the path to the
    # system specific ``/dev/log``.
    #

    if severity == 'ERROR':
        syslog.syslog(syslog.LOG_ERR, message)
    elif severity == 'WARNING':
        syslog.syslog(syslog.LOG_WARNING, message)
    elif severity == 'DEBUG':
        syslog.syslog(syslog.LOG_DEBUG, message)
    else:
        syslog.syslog(syslog.LOG_INFO, message)

Example 38

Project: laikaboss
Source File: laikamilter.py
View license
    def _checkFilePath(self, path):
        try:
            if not os.path.exists(path):
                os.makedirs(path)
        except OSError:
            log = "Could not create "+ path
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))

Example 39

Project: neubot
Source File: unix.py
View license
def _download_and_verify_update(server='releases.neubot.org'):
    '''
     Wrapper around __download_and_verify_update() that catches
     and handles exceptions.
    '''
    try:
        channel = CONFIG['channel']
        return __download_and_verify_update(server, channel)
    except:
        why = asyncore.compact_traceback()
        syslog.syslog(syslog.LOG_ERR,
                      '_download_and_verify_update: %s' %
                      str(why))
        return None

Example 40

Project: thus
Source File: misc.py
View license
@raise_privileges
def get_install_medium():
    if not get_install_medium.medium:
        try:
            if os.access('/cdrom', os.W_OK):
                get_install_medium.medium = 'USB'
            else:
                get_install_medium.medium = 'CD'
        except Exception:
            syslog.syslog(
                syslog.LOG_ERR, "Unable to determine install medium.")
            get_install_medium.medium = 'CD'
    return get_install_medium.medium

Example 41

Project: thus
Source File: misc.py
View license
def set_groups_for_uid(uid):
    if uid == os.geteuid() or uid == os.getuid():
        return
    user = pwd.getpwuid(uid).pw_name
    try:
        os.setgroups([g.gr_gid for g in grp.getgrall() if user in g.gr_mem])
    except OSError:
        import traceback

        for line in traceback.format_exc().split('\n'):
            syslog.syslog(syslog.LOG_ERR, line)

Example 42

Project: laikaboss
Source File: laikamilter.py
View license
    def header(self,name,val):
        try:
            lname = name.lower()
            tname = name.strip()
            tval  = val.strip()
            headerstring = "%s: %s\n"%(name, 
                                      val
                                     )
            self.headers.append(headerstring)
            
            self._getSpecialHeaderLines(lname, val)
        except:
            log = self.uuid+" Uncaught Exception in Header"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 43

Project: infrastructure-puppet
Source File: log.py
View license
def exception():
    logfile = os.path.join(cfg.repo_dir, "error.log")
    tb = traceback.format_exc()
    # Send error message to syslog
    syslog.syslog(syslog.LOG_ERR, "{0} - {1}".format(cfg.script_name, tb))
    # Send error message to script log error.log 
    with open(logfile, "a") as handle:
        handle.write("[{0}] {1}".format(time.ctime(), tb))

Example 44

Project: FuzzLabs
Source File: EngineThread.py
View license
    def enqueue(self, item):
        try:
            self.dqueue.put(item, True, 1)
        except Queue.Full:
            self.enqueue(item)
        except Exception, ex:
            syslog.syslog(syslog.LOG_ERR,
                          "failed to process job: %s" % str(ex))
            return False
        return True

Example 45

Project: laikaboss
Source File: laikamilter.py
View license
    def eoh(self):
        try:
            self._writeHeaderToFP()
        except:
            log = self.uuid+" Uncaught Exception in EOH"
            self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log)))
        return Milter.CONTINUE

Example 46

Project: FuzzLabs
Source File: DatabaseThread.py
View license
    def handle_job(self, db, engine, active, data):
        if not engine or not data: return

        for job in data:
            c = 0
            try:
                c = db.query(Job).filter(
                            (Job.engine_id == engine.id) &\
                            (Job.job_id == job["job_id"])
                            ).count()
            except Exception, ex:
                syslog.syslog(syslog.LOG_ERR,
                              'failed to get number of jobs: %s' %\
                              str(ex))
                return
            if c == 0:
                try:
                    # TODO: UPDATE TO NEW STRUCTURE
                    n_job = Job(job_id      = job["job_id"],
                                name        = job["name"],
                                engine_id   = engine.id,
                                status      = job["status"],
                                node        = job["node"],
                                c_m_index   = job["c_m_index"],
                                t_m_index   = job["t_m_index"],
                                crashes     = job["crashes"],
                                warnings    = job["warnings"],
                                job_loaded  = job["job_loaded"],
                                job_started = job["job_started"],
                                job_stopped = job["job_stopped"],
                                session     = json.dumps(job["session"]),
                                target      = json.dumps(job["target"]),
                                conditions  = json.dumps(job["conditions"]),
                                requests    = json.dumps(job["request"]),
                                agent       = json.dumps(job.get("agent")))
                    db.add(n_job)
                    db.commit()
                except Exception, ex: 
                    syslog.syslog(syslog.LOG_ERR,
                                  'failed to add job to the database: %s' %\
                                  str(ex))
                    continue
            else:
                try:
                    n_job = db.query(Job).filter(
                                    (Job.engine_id == engine.id) &\
                                    (Job.job_id == job["job_id"])).one()

                    n_job.name        = job["name"]
                    n_job.status      = job["status"]
                    n_job.c_m_index   = job["c_m_index"]
                    n_job.t_m_index   = job["t_m_index"]
                    n_job.crashes     = job["crashes"]
                    n_job.warnings    = job["warnings"]
                    n_job.job_loaded  = job["job_loaded"]
                    n_job.job_started = job["job_started"]
                    n_job.job_stopped = job["job_stopped"]
                    n_job.node        = job["node"]
                    n_job.session     = json.dumps(job["session"])
                    n_job.target      = json.dumps(job["target"])
                    n_job.conditions  = json.dumps(job["conditions"])
                    n_job.requests    = json.dumps(job["request"])
                    n_job.agent       = json.dumps(job.get("agent"))

                    db.add(n_job)
                    db.commit()
                except Exception, ex: 
                    syslog.syslog(syslog.LOG_ERR,
                                  'failed to update job in database: %s' %\
                                  str(ex))
                    continue

Example 47

Project: python-pyhsm
Source File: validation_server.py
View license
def args_fixup():
    """
    Various cleanups/initializations based on result of parse_args().
    """
    global saved_key_handle
    saved_key_handle = args.hmac_kh

    args.key_handle = pyhsm.util.key_handle_to_int(args.hmac_kh)

    if not (args.mode_otp or args.mode_short_otp or args.mode_totp or args.mode_hotp or args.mode_pwhash):
        my_log_message(args, syslog.LOG_ERR, 'No validation mode enabled')
        sys.exit(1)

    global client_ids
    if args.clients_file != None:
        if not args.mode_otp:
            my_log_message(args, syslog.LOG_ERR, 'Clients file should only be used with --otp.')
            sys.exit(1)
        client_ids = load_clients_file(args.clients_file)
        if not client_ids:
            my_log_message(args, syslog.LOG_ERR, 'Failed loading clients file "%s"' % (args.clients_file))
            sys.exit(1)
    else:
        # we accept failure to load this file when the default is used
        loaded_client_ids = load_clients_file(default_clients_file)
        if loaded_client_ids:
            args.clients_file = default_clients_file
            client_ids = loaded_client_ids

Example 48

Project: laikaboss
Source File: laikamilter.py
View license
    def _dispositionMessage(self):
        self.startTimeZMQ = time.time()
        if (not self._checkOKToContinueWithOpenFiles()):
            self.disposition = "Over Process File Handle Limit"
            self.logger.writeLog(syslog.LOG_ERR, "Disposition: %s"%(str(self.disposition)))
            rtnToMTA = self.milterConfig.dispositionModes["OverLimit".lower()]
        else:
            dispositioner = Dispositioner(self.logger)
            success = dispositioner.zmqGetFlagswithRetry(self.milterConfig.zmqMaxRetry, self)
            self.disposition = dispositioner.strScanResult
            self.scanPerformedOn = dispositioner.scanServerToUse
            self.rulesMatched = ' '.join(dispositioner.match)
            self.warnings = dispositioner.warnings
            self.attachments = dispositioner.attachements
            self._dispositionMessage_AttachmentHelper()
            self.dispositions = dispositioner.dispositions
            self.logger.writeLog(syslog.LOG_DEBUG, "%s Disposition: %s"%(self.uuid, str(dispositioner.dispositions)))
            rtnToMTA = self._getReturnToMTAValue(dispositioner)
            dispositioner.close()
        self.endTimeZMQ = time.time()
        return rtnToMTA

Example 49

Project: python-pyhsm
Source File: yubikey_ksm.py
View license
    def log_error(self, fmt, *fmt_args):
        """ Log to syslog. """
        msg = self.my_address_string() + " - - " + fmt % fmt_args
        my_log_message(self.verbose, syslog.LOG_ERR, msg)

Example 50

Project: downburst
Source File: create.py
View license
def create(args):
    log.debug('Connecting to libvirt...')
    conn = libvirt.open(args.connect)
    if conn is None:
        raise exc.LibvirtConnectionError()

    meta_data = meta.gen_meta(
        name=args.name,
        extra_meta=args.meta_data,
        nokey=args.nokey,
        )

    user_data = meta.gen_user(
        name=args.name,
        extra_user=args.user_data,
        )

    if args.distro:
        distro = args.distro
    else:
        distro = meta_data.get('downburst', {}).get('distro')

    if distro is None:
        distro = "ubuntu"

    if args.distroversion:
        distroversion = args.distroversion
    else:
        distroversion = meta_data.get('downburst', {}).get('distroversion')

    # If ubuntu distroversion contains non version (IE: quantal) convert to version:
    if distroversion:
        if distro == 'ubuntu' and ('.' not in distroversion):
            handler = discover.UbuntuHandler()
            distroversion = handler.get_version(distroversion)

    if distroversion is None:
        defaultversion = dict(
            ubuntu="12.04",
            fedora="17",
            centos="6.3",
            opensuse="12.2",
            sles="11-sp2",
            rhel="6.3",
            debian='6.0'
            )
        distroversion = defaultversion[distro]

    if args.arch:
        arch = args.arch
    else:
        arch = meta_data.get('downburst', {}).get('arch')

    if arch == "x86_64":
        arch = "amd64"

    if arch is None:
        arch = "amd64"

    # check if the vm exists already, complain if so. this would
    # normally use conn.lookupByName, but that logs on all errors;
    # avoid the noise.
    if args.name in conn.listDefinedDomains():
        raise exc.VMExistsError(args.name)

    log.debug('Opening libvirt pool...')

    # Check if pool with same name of guest exists, use it if it does
    pool = ''
    pools = conn.listStoragePools()
    for poolentry in pools:
        if poolentry == args.name:
            pool = conn.storagePoolLookupByName(poolentry)
            break
    if not pool:
        pool = conn.storagePoolLookupByName('default')

    vol, raw = image.ensure_cloud_image(pool=pool, distro=distro, distroversion=distroversion, arch=arch, forcenew=args.forcenew)

    if args.wait:
        user_data.append("""\
#!/bin/sh
# eject the cdrom (containing the cloud-init metadata)
# as a signal that we've reached full functionality;
# this is used by ``downburst create --wait``
exec eject /dev/cdrom
""")

    capacity = meta_data.get('downburst', {}).get('disk-size', '10G')
    capacity = dehumanize.parse(capacity)
    additional_disks = meta_data.get('downburst', {}).get('additional-disks')
    additional_disks_size = meta_data.get('downburst', {}).get('additional-disks-size', '10G')
    additional_disks_size = dehumanize.parse(additional_disks_size)
    ceph_cluster_name = meta_data.get('downburst', {}).get('ceph-cluster-name')
    ceph_cluster_monitors = meta_data.get('downburst', {}).get('ceph-cluster-monitors')
    ceph_cluster_pool = meta_data.get('downburst', {}).get('ceph-cluster-pool')
    ceph_cluster_user = meta_data.get('downburst', {}).get('ceph-cluster-user')
    ceph_cluster_secret = meta_data.get('downburst', {}).get('ceph-cluster-secret')
    rbd_disks = meta_data.get('downburst', {}).get('rbd-disks')
    rbd_disks_size = dehumanize.parse(meta_data.get('downburst', {}).get('rbd-disks-size'))
    rbd_details = dict()
    rbd_details['ceph_cluster_name'] = ceph_cluster_name
    rbd_details['ceph_cluster_monitors'] = ceph_cluster_monitors
    rbd_details['ceph_cluster_pool'] = ceph_cluster_pool
    rbd_details['ceph_cluster_user'] = ceph_cluster_user
    rbd_details['ceph_cluster_secret'] = ceph_cluster_secret


    clonexml = template.volume_clone(
        name='{name}.img'.format(name=args.name),
        parent_vol=vol,
        capacity=capacity,
        raw=raw,
        )
    clone = pool.createXML(etree.tostring(clonexml), flags=0)

    iso_vol = iso.create_meta_iso(
        pool=pool,
        name=args.name,
        meta_data=meta_data,
        user_data=user_data,
        )

    # We want the range to be 2 - X depending on disk count.
    # Since there is already a boot volume we want the image
    # names to be appended with -2, -3, -4, etc... for the
    # additional disks.
    additional_disks_key = []
    if additional_disks is not None:
        for disknum in range(1, additional_disks + 1):
            disknum += 1
            diskname = args.name + '-' + str(disknum) + '.img'
            diskxml = template.volume(
                name=diskname,
                capacity=additional_disks_size,
                format_='raw',
                sparse=False,
                )
            additional_disks_key.append(pool.createXML(etree.tostring(diskxml), flags=0).key())
    if not additional_disks_key:
        additional_disks_key = None

    rbd_disks_key = []
    if rbd_disks:
        assert ceph_cluster_name != None, "Unable to setup RBD Storage Pool. Pool name Required but is: %s" % pool
        try:
            rbdpool = conn.storagePoolLookupByName(ceph_cluster_name)
        except libvirt.libvirtError:
            poolxml = template.rbd_pool(
                name=ceph_cluster_name,
                monitorlist=ceph_cluster_monitors,
                pool=ceph_cluster_pool,
                user=ceph_cluster_user,
                secret=ceph_cluster_secret,
                )
            conn.storagePoolCreateXML(etree.tostring(poolxml), 0)
            rbdpool = conn.storagePoolLookupByName(ceph_cluster_name)

        if not additional_disks:
            additional_disks = 0
        for rbdnum in range(1 + additional_disks, additional_disks + rbd_disks + 1):
            rbdnum += 1
            rbdname = '{name}-{rbdnum}'.format(name=args.name, rbdnum=rbdnum)
            rbdxml = template.rbd_volume(
                name=rbdname,
                capacity=rbd_disks_size,
                pool=ceph_cluster_pool,
                )
            rbd_disks_key.append(rbdpool.createXML(etree.tostring(rbdxml), flags=0).key())
    if not rbd_disks_key:
        rbd_disks_key = None

    ram = meta_data.get('downburst', {}).get('ram')
    ram = dehumanize.parse(ram)
    cpus = meta_data.get('downburst', {}).get('cpus')
    networks = meta_data.get('downburst', {}).get('networks')
    domainxml = template.domain(
        name=args.name,
        disk_key=clone.key(),
        iso_key=iso_vol.key(),
        ram=ram,
        cpus=cpus,
        networks=networks,
        additional_disks_key=additional_disks_key,
        rbd_disks_key=rbd_disks_key,
        rbd_details=rbd_details,
        hypervisor=args.hypervisor
        )
    dom = conn.defineXML(etree.tostring(domainxml))
    dom.create()
    try:
        env = os.environ
        pid = os.getpid()
        # os.getppid() wont return the correct value:
        ppid = open('/proc/{pid}/stat'.format(pid=pid)).read().split()[3]
        ppcmdline = open('/proc/{ppid}/cmdline'.format(ppid=ppid)).read().split(b'\x00')

    except IndexError, IOError:
        log.exception('Something went wrong getting PPID/cmdlineinfo')
        ppcmdline = 'ERROR_RETREIVING'

    syslog_message = 'Created guest: {name} on {host} by User: {username} PPCMD: {pcmd}'.format(
                    name=args.name,
                    host=args.connect,
                    username=env.get('USER'),
                    pcmd=ppcmdline)
    syslog.syslog(syslog.LOG_ERR, syslog_message)

    if args.wait:
        log.debug('Waiting for vm to be initialized...')
        wait.wait_for_cdrom_eject(dom)