本文整理汇总了Python中up2date_client.up2dateLog.initLog函数的典型用法代码示例。如果您正苦于以下问题:Python initLog函数的具体用法?Python initLog怎么用?Python initLog使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了initLog函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: read_all_fqdns
def read_all_fqdns():
def flatten_dict(d):
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, subvalue in flatten_dict(value).items():
yield key + "." + subkey, subvalue
else:
yield key, value
return dict(items())
fqdns = set()
ret = {}
ret["class"] = "FQDN"
interfaces = flatten_dict(read_network_interfaces())
ips = []
for ipv4 in list(value for key, value in interfaces.iteritems() if key.endswith('ipaddr') and not key.startswith('lo')):
if ipv4:
ips.append(ipv4)
for ipv6 in list(value for key, value in interfaces.iteritems() if key.endswith('ipv6') and not key.startswith('lo')):
if ipv6:
ips.append(ipv6[0]['addr'])
for ip in ips:
try:
fqdns.add(socket.gethostbyaddr(ip)[0])
except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
up2dateLog.initLog().log_me("Error resolving address: %s\n" % (e))
ret["name"] = list(fqdns)
return ret
开发者ID:m47ik,项目名称:uyuni,代码行数:32,代码来源:hardware.py
示例2: writeCachedLogin
def writeCachedLogin():
"""
Pickle loginInfo to a file
Returns:
True -- wrote loginInfo to a pickle file
False -- did _not_ write loginInfo to a pickle file
"""
log = up2dateLog.initLog()
log.log_debug("writeCachedLogin() invoked")
if not loginInfo:
log.log_debug("writeCachedLogin() loginInfo is None, so bailing.")
return False
data = {'time': time.time(),
'loginInfo': loginInfo}
pcklDir = os.path.dirname(pcklAuthFileName)
if not os.access(pcklDir, os.W_OK):
try:
os.mkdir(pcklDir)
os.chmod(pcklDir, int('0700', 8))
except:
log.log_me("Unable to write pickled loginInfo to %s" % pcklDir)
return False
pcklAuth = open(pcklAuthFileName, 'wb')
os.chmod(pcklAuthFileName, int('0600', 8))
pickle.dump(data, pcklAuth)
pcklAuth.close()
expireTime = data['time'] + float(loginInfo['X-RHN-Auth-Expire-Offset'])
log.log_debug("Wrote pickled loginInfo at ", data['time'], " with expiration of ",
expireTime, " seconds.")
return True
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:31,代码来源:up2dateAuth.py
示例3: _initialize_dmi_data
def _initialize_dmi_data():
""" Initialize _dmi_data unless it already exist and returns it """
global _dmi_data, _dmi_not_available
if _dmi_data is None:
if _dmi_not_available:
# do not try to initialize it again and again if not available
return None
else :
dmixml = dmidecode.dmidecodeXML()
dmixml.SetResultType(dmidecode.DMIXML_DOC)
# Get all the DMI data and prepare a XPath context
try:
data = dmixml.QuerySection('all')
dmi_warn = dmi_warnings()
if dmi_warn:
dmidecode.clear_warnings()
log = up2dateLog.initLog()
log.log_debug("dmidecode warnings: %s" % dmi_warn)
except:
# DMI decode FAIL, this can happend e.g in PV guest
_dmi_not_available = 1
dmi_warn = dmi_warnings()
if dmi_warn:
dmidecode.clear_warnings()
return None
_dmi_data = data.xpathNewContext()
return _dmi_data
开发者ID:jdobes,项目名称:spacewalk,代码行数:27,代码来源:hardware.py
示例4: updateLoginInfo
def updateLoginInfo(timeout=None):
log = up2dateLog.initLog()
log.log_me("updateLoginInfo() login info")
# NOTE: login() updates the loginInfo object
login(forceUpdate=True, timeout=timeout)
if not loginInfo:
raise up2dateErrors.AuthenticationError("Unable to authenticate")
return loginInfo
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:8,代码来源:up2dateAuth.py
示例5: updatePackageProfile
def updatePackageProfile(timeout=None):
""" get a list of installed packages and send it to rhnServer """
log = up2dateLog.initLog()
log.log_me("Updating package profile")
packages = pkgUtils.getInstalledPackageList(getArch=1)
s = rhnserver.RhnServer(timeout=timeout)
if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
# for older satellites and hosted - convert to old format
packages = convertPackagesFromHashToList(packages)
s.registration.update_packages(up2dateAuth.getSystemId(), packages)
开发者ID:Bearlock,项目名称:spacewalk,代码行数:10,代码来源:rhnPackageInfo.py
示例6: exceptionHandler
def exceptionHandler(type, value, tb):
log = up2dateLog.initLog()
sys.stderr.write(utf8_encode(_("An error has occurred:") + "\n"))
if hasattr(value, "errmsg"):
sys.stderr.write(utf8_encode(value.errmsg) + "\n")
log.log_exception(type, value, tb)
else:
sys.stderr.write(utf8_encode(str(type) + "\n"))
log.log_exception(type, value, tb)
sys.stderr.write(utf8_encode(_("See /var/log/up2date for more information") + "\n"))
开发者ID:aronparsons,项目名称:spacewalk,代码行数:11,代码来源:rhncli.py
示例7: __exceptionHandler
def __exceptionHandler(type, value, tb):
log = up2dateLog.initLog()
print _("An error has occurred:")
if hasattr(value, "errmsg"):
print value.errmsg
log.log_exception(type, value, tb)
else:
print type
log.log_exception(type, value, tb)
print _("See /var/log/up2date for more information")
开发者ID:bjmingyang,项目名称:spacewalk,代码行数:11,代码来源:rhncli.py
示例8: _testRhnLogin
def _testRhnLogin(self):
try:
up2dateAuth.updateLoginInfo()
return True
except up2dateErrors.ServerCapabilityError:
print sys.exc_info()[1]
return False
except up2dateErrors.AuthenticationError:
return False
except up2dateErrors.RhnServerException:
log = up2dateLog.initLog()
log.log_me('There was a RhnServerException while testing login:\n')
log.log_exception(*sys.exc_info())
return False
开发者ID:aronparsons,项目名称:spacewalk,代码行数:14,代码来源:rhncli.py
示例9: _request1
def _request1(self, methodname, params):
self.log = up2dateLog.initLog()
while 1:
try:
ret = self._request(methodname, params)
except rpclib.InvalidRedirectionError:
raise
except xmlrpclib.Fault:
raise
except httplib.BadStatusLine:
self.log.log_me("Error: Server Unavailable. Please try later.")
stdoutMsgCallback(
_("Error: Server Unavailable. Please try later."))
sys.exit(-1)
except:
server = self.serverList.next()
if server == None:
# since just because we failed, the server list could
# change (aka, firstboot, they get an option to reset the
# the server configuration) so reset the serverList
self.serverList.resetServerIndex()
raise
msg = "An error occurred talking to %s:\n" % self._host
msg = msg + "%s\n%s\n" % (sys.exc_info()[0], sys.exc_info()[1])
msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server()
self.log.log_me(msg)
# try a different url
# use the next serverURL
parse_res = urlparse.urlsplit(self.serverList.server())
typ = parse_res.scheme
self._host = parse_res.netloc
self._handler = parse_res.path
typ = typ.lower()
if typ not in ("http", "https"):
raise_with_tb(rpclib.InvalidRedirectionError(
"Redirected to unsupported protocol %s" % typ))
self._orig_handler = self._handler
self._type = typ
self._uri = self.serverList.server()
if not self._handler:
self._handler = "/RPC2"
self._allow_redirect = 1
continue
# if we get this far, we succedded
break
return ret
开发者ID:phurrelmann,项目名称:spacewalk,代码行数:48,代码来源:rpcServer.py
示例10: readCachedLogin
def readCachedLogin():
"""
Read pickle info from a file
Caches authorization info for connecting to the server.
"""
log = up2dateLog.initLog()
log.log_debug("readCachedLogin invoked")
if not os.access(pcklAuthFileName, os.R_OK):
log.log_debug("Unable to read pickled loginInfo at: %s" % pcklAuthFileName)
return False
pcklAuth = open(pcklAuthFileName, 'rb')
try:
data = pickle.load(pcklAuth)
except (EOFError, ValueError):
log.log_debug("Unexpected EOF. Probably an empty file, \
regenerate auth file")
pcklAuth.close()
return False
pcklAuth.close()
# Check if system_id has changed
try:
idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['system_id']
cidVer = "ID-%s" % data['loginInfo']['X-RHN-Server-Id']
if idVer != cidVer:
log.log_debug("system id version changed: %s vs %s" % (idVer, cidVer))
return False
except:
pass
createdTime = data['time']
li = data['loginInfo']
currentTime = time.time()
expireTime = createdTime + float(li['X-RHN-Auth-Expire-Offset'])
#Check if expired, offset is stored in "X-RHN-Auth-Expire-Offset"
log.log_debug("Checking pickled loginInfo, currentTime=", currentTime,
", createTime=", createdTime, ", expire-offset=",
float(li['X-RHN-Auth-Expire-Offset']))
if (currentTime > expireTime):
log.log_debug("Pickled loginInfo has expired, created = %s, expire = %s." \
%(createdTime, expireTime))
return False
_updateLoginInfo(li)
log.log_debug("readCachedLogin(): using pickled loginInfo set to expire at ", expireTime)
return True
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:43,代码来源:up2dateAuth.py
示例11: get_hal_system_and_smbios
def get_hal_system_and_smbios():
try:
if using_gudev:
props = get_computer_info()
else:
computer = get_hal_computer()
props = computer.GetAllProperties()
except Exception:
log = up2dateLog.initLog()
msg = "Error reading system and smbios information: %s\n" % (sys.exc_info()[1])
log.log_debug(msg)
return {}
system_and_smbios = {}
for key in props:
if key.startswith('system'):
system_and_smbios[ustr(key)] = ustr(props[key])
system_and_smbios.update(get_smbios())
return system_and_smbios
开发者ID:jdobes,项目名称:spacewalk,代码行数:20,代码来源:hardware.py
示例12: update_count
def update_count(problem_dir):
problem_dir = os.path.normpath(os.path.abspath(problem_dir))
basename = os.path.basename(problem_dir)
log = up2dateLog.initLog()
if not (os.path.exists(problem_dir) and os.path.isdir(problem_dir)):
log.log_me("The specified path [%s] is not a valid directory." % problem_dir)
return -1
server = rhnserver.RhnServer()
if not server.capabilities.hasCapability('abrt'):
return -1
systemid = up2dateAuth.getSystemId()
crash_count_path = os.path.join(problem_dir, 'count')
if not (os.path.exists(crash_count_path) and os.path.isfile(crash_count_path)):
log.log_me("The problem directory [%s] does not contain any crash count information." % problem_dir)
return 0
crash_count = _readline(crash_count_path)
server.abrt.update_crash_count(systemid, basename, crash_count)
return 1
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:22,代码来源:abrt.py
示例13: login
def login(systemId=None, forceUpdate=False, timeout=None):
log = up2dateLog.initLog()
log.log_debug("login(forceUpdate=%s) invoked" % (forceUpdate))
if not forceUpdate and not loginInfo:
if readCachedLogin():
return loginInfo
server = rhnserver.RhnServer(timeout=timeout)
# send up the capabality info
headerlist = clientCaps.caps.headerFormat()
for (headerName, value) in headerlist:
server.add_header(headerName, value)
if systemId == None:
systemId = getSystemId()
if not systemId:
return None
maybeUpdateVersion()
log.log_me("logging into up2date server")
li = server.up2date.login(systemId)
# figure out if were missing any needed caps
server.capabilities.validate()
_updateLoginInfo(li) #update global var, loginInfo
writeCachedLogin() #pickle global loginInfo
if loginInfo:
log.log_me("successfully retrieved authentication token "
"from up2date server")
log.log_debug("logininfo:", loginInfo)
return loginInfo
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:36,代码来源:up2dateAuth.py
示例14: runTransaction
def runTransaction(ts, rpmCallback, transdir=None):
cfg = config.initUp2dateConfig()
if transdir == None:
transdir = cfg['storageDir']
deps = ts.check()
if deps:
raise up2dateErrors.DependencyError(
"Dependencies should have already been resolved, "\
"but they are not.", deps)
rc = ts.run(rpmCallback, transdir)
if rc:
errors = "\n"
for e in rc:
try:
errors = errors + e[1] + "\n"
except:
errors = errors + str(e) + "\n"
raise up2dateErrors.TransactionError(
"Failed running transaction of packages: %s" % errors, deps=rc)
elif type(rc) == type([]) and not len(rc):
# let the user know whats wrong
log = up2dateLog.initLog()
log.log_me("Failed running rpm transaction - %pre %pro failure ?.")
raise up2dateErrors.RpmError("Failed running rpm transaction")
开发者ID:ChrisPortman,项目名称:mrepo,代码行数:24,代码来源:rpmUtils.py
示例15: report
def report(problem_dir):
problem_dir = os.path.normpath(os.path.abspath(problem_dir))
basename = os.path.basename(problem_dir)
log = up2dateLog.initLog()
if not (os.path.exists(problem_dir) and os.path.isdir(problem_dir)):
log.log_me("The specified path [%s] is not a valid directory." % problem_dir)
return -1
crash_items = ['analyzer', 'cmdline', 'reason']
if os.path.exists(os.path.join(problem_dir, 'vmcore')):
crash_items = ['analyzer', 'vmcore-dmesg.txt']
for item in crash_items:
item_path = os.path.join(problem_dir, item)
if not os.path.exists(item_path):
log.log_me("Crash directory [%s] is incomplete or invalid" % problem_dir)
return -1
server = rhnserver.RhnServer()
if not server.capabilities.hasCapability('abrt'):
return -1
systemid = up2dateAuth.getSystemId()
# Package information
pkg_data = {}
for item in ['package', 'pkg_name', 'pkg_epoch', 'pkg_version', 'pkg_release', 'pkg_arch']:
pkg_item_path = os.path.join(problem_dir, item)
if os.path.exists(pkg_item_path):
filecontent = _readline(pkg_item_path)
if filecontent:
pkg_data[item] = filecontent
# Crash information
crash_data = {'crash': basename, 'path': problem_dir}
# Crash count
crash_count = _readline(os.path.join(problem_dir, 'count'))
if crash_count:
crash_data['count'] = crash_count
# Create record about the crash
r = server.abrt.create_crash(systemid, crash_data, pkg_data)
if (r < 0): # Error creating new crash report
log.log_me("Error creating new crash report.")
return -1
# Upload every particular file in the problem directory to the server
for i in os.listdir(problem_dir):
path = os.path.join(problem_dir, i)
if not os.path.isfile(path):
continue
filesize = os.stat(path).st_size
crash_file_data = {'filename': os.path.basename(i),
'path': path,
'filesize': filesize,
'filecontent': base64.encodestring(bstr("")),
'content-encoding': 'base64'}
if server.abrt.is_crashfile_upload_enabled(systemid) and filesize <= server.abrt.get_crashfile_uploadlimit(systemid):
f = open(path, 'r')
try:
crash_file_data['filecontent'] = base64.encodestring(f.read())
finally:
f.close()
server.abrt.upload_crash_file(systemid, basename, crash_file_data)
return 1
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:71,代码来源:abrt.py
示例16: initiate
def initiate(kickstart_host, base, extra_append, static_device="", system_record="", preserve_files=[], cache_only=False):
log = up2dateLog.initLog()
log.log_me("initiating spacewalkkoan kickstart")
return spacewalkkoan.initiate(kickstart_host, base, extra_append=extra_append,
static_device=static_device, system_record=system_record, preserve_files=preserve_files)
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:5,代码来源:kickstart.py
示例17: __init__
def __init__(self, errmsg):
errmsg = ustr(errmsg)
PmBaseError.__init__(self, errmsg)
self.value = 'rhn-plugin: ' + self.premsg + errmsg
self.log = up2dateLog.initLog()
开发者ID:Bearlock,项目名称:spacewalk,代码行数:5,代码来源:up2dateErrors.py
示例18: solveDep
def solveDep(self, unknowns, availList,
msgCallback = None,
progressCallback = None,
refreshCallback = None):
self.cfg = config.initUp2dateConfig()
self.log = up2dateLog.initLog()
self.log.log_me("solving dep for: %s" % unknowns)
self.refreshCallback = refreshCallback
self.progressCallback = progressCallback
self.msgCallback = msgCallback
self.availList = availList
availList.sort()
self.availListHash = {}
for p in self.availList:
if self.availListHash.has_key(tuple(p[:4])):
self.availListHash[tuple(p[:4])].append(p)
else:
self.availListHash[tuple(p[:4])] = [p]
self.retDict = {}
self.getSolutions(unknowns,
progressCallback = self.progressCallback,
msgCallback = self.msgCallback)
reslist = []
self.depToPkg = DictOfLists()
self.depsNotAvailable = DictOfLists()
# self.depToPkg = {}
#FIXME: this should be cached, I dont really need to query the db
# for this everytime
self.installedPkgList = rpmUtils.getInstalledPackageList(getArch=1)
self.installedPkgHash = {}
for pkg in self.installedPkgList:
if self.installedPkgHash.has_key(pkg[0]):
self.installedPkgHash[pkg[0]].append(pkg)
else:
self.installedPkgHash[pkg[0]] = [pkg]
# we didnt get any results, bow out...
if not len(self.retDict):
return (reslist, self.depToPkg)
newList = []
availListNVRE = map(lambda p: p[:4], self.availList)
failedDeps = []
solutionPkgs = []
pkgs = []
for dep in self.retDict.keys():
# skip the rest if we didnt get a result
if len(self.retDict[dep]) == 0:
continue
solutions = self.retDict[dep]
# fixme, grab the first package that satisfies the dep
# but make sure we match nvre against the list of avail packages
# so we grab the right version of the package
# if we only get one soltution, use it. No point in jumping
# though other hoops
if len(solutions) == 1:
for solution in solutions:
pkgs.append(solution)
# we've got more than one possible solution, do some work
# to figure out if I want one, some, or all of them
elif len(solutions) > 1:
# try to install the new version of whatever arch is
# installed
solutionsInstalled = self.__getSolutionsInstalled(solutions)
found = 0
if len(solutionsInstalled):
for p in solutionsInstalled:
pkgs.append(p)
self.depToPkg[dep] = p
found = 1
if found:
break
# we dont have any of possible solutions installed, pick one
else:
# this is where we could do all sort of heuristics to pick
# best one. For now, grab the first one in the list thats
# available
#FIXME: we need to arch score here for multilib/kernel
# packages that dont have a version installed
# This tends to happen a lot when isntalling into
# empty chroots (aka, pick which of the kernels to
# install).
# ie, this is the pure heuristic approach...
shortest = solutions[0]
for solution in solutions:
#.........这里部分代码省略.........
开发者ID:ChrisPortman,项目名称:mrepo,代码行数:101,代码来源:genericSolveDep.py
示例19: logDeltaPackages
def logDeltaPackages(pkgs):
log = up2dateLog.initLog()
log.log_me("Adding packages to package profile: %s" %
pprint_pkglist(pkgs['added']))
log.log_me("Removing packages from package profile: %s" %
pprint_pkglist(pkgs['removed']))
开发者ID:Bearlock,项目名称:spacewalk,代码行数:6,代码来源:rhnPackageInfo.py
示例20: getInstalledPackageList
def getInstalledPackageList(msgCallback = None, progressCallback = None,
getArch=None, getInfo = None):
""" Return list of packages. Package is hash with keys name, epoch,
version, release and optionaly arch and cookie
"""
pkg_list = []
if msgCallback != None:
msgCallback(_("Getting list of packages installed on the system"))
_ts = transaction.initReadOnlyTransaction()
count = 0
total = 0
dbmatch = _ts.dbMatch()
for h in dbmatch:
if h == None:
break
count = count + 1
total = count
count = 0
dbmatch = _ts.dbMatch()
for h in dbmatch:
if h == None:
break
if not (is_utf8(sstr(h['name'])) and is_utf8(sstr(h['version']))
and is_utf8(sstr(h['release']))):
log = up2dateLog.initLog()
log.log_me("Package with invalid character set found. Skipping: '%s-%s-%s'" %
(h['name'].decode('UTF-8', errors='replace'),
h['version'].decode('UTF-8', errors='replace'),
h['release'].decode('UTF-8', errors='replace')))
continue
package = {
'name': sstr(h['name']),
'epoch': h['epoch'],
'version': sstr(h['version']),
'release': sstr(h['release']),
'installtime': h['installtime']
}
if package['epoch'] == None:
package['epoch'] = ""
else: # convert it to string
package['epoch'] = "%s" % package['epoch']
if getArch:
package['arch'] = h['arch']
# the arch on gpg-pubkeys is "None"...
if package['arch']:
package['arch'] = sstr(package['arch'])
pkg_list.append(package)
elif getInfo:
if h['arch']:
package['arch'] = sstr(h['arch'])
if h['cookie']:
package['cookie'] = sstr(h['cookie'])
pkg_list.append(package)
else:
pkg_list.append(package)
if progressCallback != None:
progressCallback(count, total)
count = count + 1
dbmatch = None
_ts.ts.closeDB()
pkg_list.sort(key=lambda x:(x['name'], x['epoch'], x['version'], x['release']))
return pkg_list
开发者ID:m47ik,项目名称:uyuni,代码行数:68,代码来源:rpmUtils.py
注:本文中的up2date_client.up2dateLog.initLog函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论