本文整理汇总了Python中salt.log.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dns_check
def dns_check(addr, safe=False):
'''
Return the ip resolved by dns, but do not exit on failure, only raise an
exception.
'''
try:
socket.inet_aton(addr)
except socket.error:
# Not a valid ip adder, check DNS
try:
addr = socket.gethostbyname(addr)
except socket.gaierror:
err = ('This master address: \'{0}\' was previously resolvable but '
'now fails to resolve! The previously resolved ip addr '
'will continue to be used').format(addr)
if safe:
import salt.log
if salt.log.is_console_configured():
# If logging is not configured it also means that either
# the master or minion instance calling this hasn't even
# started running
log.error(err)
raise SaltClientError
else:
err = err.format(addr)
sys.stderr.write(err)
sys.exit(42)
return addr
示例2: load_agents
def load_agents(config):
'''
Load the agents specified in /etc/salt/alert from the
salt.ext.alert.agents package. Each module must define a
load_agents() function that accepts the parsed YAML configuration
for the agents.
'''
ignore_modules = ['alert.time', 'alert.subscriptions', 'alert.verbs']
agents = {}
for key, value in config.iteritems():
if key.startswith('alert.') and key not in ignore_modules:
modname = AGENTS_MODULE + '._' + key[6:]
log.trace('load %s', modname)
try:
mod = __import__(modname, fromlist=[AGENTS_MODULE])
except ImportError, ex:
log.trace('not an agent module: %s', modname, exc_info=ex)
continue
try:
new_agents = mod.load_agents(value)
except AttributeError, ex:
log.error('not an agent module: %s', modname, exc_info=ex)
continue
common = set(agents.keys()) & set(new_agents.keys())
if len(common) != 0:
raise ValueError(
'agent name(s) collide in config: {}'.format(
', '.join(["'{}'".format(x) for x in common])))
agents.update(new_agents)
log.trace('loaded alert agent(s): %s', new_agents.keys())
示例3: main
def main():
"""
Start computer service.
.. code-block:: bash
hs-computer --server|--node|--all
"""
salt.log.setup_console_logger()
parser = option_parser()
shell = Shell(parser)
try:
shell.exec_command()
except Exception as err:
log.error("shell command failed: {0!r}".format(
err)
)
except KeyboardInterrupt:
raise SystemExit('\nExiting gracefully on Ctrl-c')
finally:
# TODO: need cleanup
log.trace("TODO cleanup work")
return
示例4: daemonize
def daemonize():
'''
Daemonize a process
'''
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as exc:
log.error(
'fork #1 failed: {0} ({1})'.format(exc.errno, exc.strerror)
)
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(18)
# do second fork
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as exc:
log.error(
'fork #2 failed: {0} ({1})'.format(
exc.errno, exc.strerror
)
)
sys.exit(1)
示例5: start
def start(self):
log.debug("starting monitor with {} task{}".format(len(self.tasks), "" if len(self.tasks) == 1 else "s"))
if self.tasks:
for task in self.tasks:
threading.Thread(target=task.run).start()
else:
log.error("no monitor tasks to run")
示例6: __init__
def __init__(self,
tgt='',
expr_form='glob',
env=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None):
log.debug('New instance of {0} created.'.format(
self.__class__.__name__))
if opts is None:
log.error('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.tgt = tgt
self.expr_form = expr_form
self.env = env
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
log.debug('Init settings: tgt: \"{0}\", expr_form: \"{1}\", env: \"{2}\", use_cached_grains: {3}, use_cached_pillar: {4}, grains_fallback: {5}, pillar_fallback: {6}'.format(tgt, expr_form, env, use_cached_grains, use_cached_pillar, grains_fallback, pillar_fallback))
示例7: ec2_tags
def ec2_tags():
boto_version = StrictVersion(boto.__version__)
required_boto_version = StrictVersion('2.8.0')
if boto_version < required_boto_version:
log.error("Installed boto version %s < %s, can't find ec2_tags",
boto_version, required_boto_version)
return None
if not _on_ec2():
log.info("Not an EC2 instance, skipping")
return None
instance_id, region = _get_instance_info()
credentials = _get_credentials()
# Connect to EC2 and parse the Roles tags for this instance
try:
conn = boto.ec2.connect_to_region(
region,
aws_access_key_id=credentials['access_key'],
aws_secret_access_key=credentials['secret_key'],
)
except Exception, e:
log.error("Could not get AWS connection: %s", e)
return None
示例8: ec2_tags
def ec2_tags():
log = logging.getLogger(__name__)
# ************* REQUEST VALUES *************
instanceid = _get_instance_id()
method = 'GET'
service = 'ec2'
region = _get_region()
host = 'ec2.'+region+'.amazonaws.com'
endpoint = 'https://ec2.'+region+'.amazonaws.com'
params = [('Action','DescribeTags')]
params.append( ('Filter.1.Name','resource-id') )
params.append( ('Filter.1.Value.1',instanceid) )
params.append( ('Version','2015-04-15') )
request_parameters = urllib.urlencode(params)
creds = _get_role_credentials()
access_key = creds['AccessKeyId']
secret_key = creds['SecretAccessKey']
token = creds['Token']
if access_key is None or secret_key is None or token is None:
log.error('No role credentials found.')
return None
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
# Calculate AWS Signature V4
canonical_uri = '/'
canonical_querystring = request_parameters
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n' + 'x-amz-security-token:' + token + '\n'
signed_headers = 'host;x-amz-date;x-amz-security-token'
payload_hash = hashlib.sha256('').hexdigest()
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request).hexdigest()
signing_key = _getSignatureKey(secret_key, datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
request_url = endpoint + '?' + canonical_querystring
r = urllib2.Request(request_url)
r.add_header('x-amz-date',amzdate)
r.add_header('Authorization',authorization_header)
r.add_header('x-amz-security-token',token)
try:
result = urllib2.urlopen(r)
except Exception, e:
log.error('Could not complete EC2 API request.')
return None
示例9: _match
def _match(target, pattern, regex_match=False):
if regex_match:
try:
return re.match(pattern.lower(), str(target).lower())
except Exception:
log.error('Invalid regex \'{0}\' in match'.format(pattern))
return False
else:
return fnmatch.fnmatch(str(target).lower(), pattern.lower())
示例10: _thread_multi_return
def _thread_multi_return(class_, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
# this seems awkward at first, but it's a workaround for Windows
# multiprocessing communication.
if not minion_instance:
minion_instance = class_(opts)
ret = {
'return': {},
'success': {},
}
for ind in range(0, len(data['fun'])):
for index in range(0, len(data['arg'][ind])):
try:
arg = eval(data['arg'][ind][index])
if isinstance(arg, bool):
data['arg'][ind][index] = str(data['arg'][ind][index])
elif isinstance(arg, (dict, int, list, string_types)):
data['arg'][ind][index] = arg
else:
data['arg'][ind][index] = str(data['arg'][ind][index])
except Exception:
pass
ret['success'][data['fun'][ind]] = False
try:
func = minion_instance.functions[data['fun'][ind]]
args, kwargs = detect_kwargs(func, data['arg'][ind], data)
ret['return'][data['fun'][ind]] = func(*args, **kwargs)
ret['success'][data['fun'][ind]] = True
except Exception as exc:
trb = traceback.format_exc()
log.warning(
'The minion function caused an exception: {0}'.format(
exc
)
)
ret['return'][data['fun'][ind]] = trb
ret['jid'] = data['jid']
minion_instance._return_pub(ret)
if data['ret']:
for returner in set(data['ret'].split(',')):
ret['id'] = opts['id']
try:
minion_instance.returners['{0}.returner'.format(
returner
)](ret)
except Exception as exc:
log.error(
'The return failed for job {0} {1}'.format(
data['jid'],
exc
)
)
示例11: do_image
def do_image(self):
try:
name = "{0}_image".format(self.CRUD_MAP[self.args.mode])
function = getattr(self.image, name)
function()
except Exception as err:
log.error('call function{0} failed: {1!r}'.format(
name, err)
)
raise RunTimeFailture("call do_image failure")
示例12: get_id
def get_id():
'''
Guess the id of the minion.
- If socket.getfqdn() returns us something other than localhost, use it
- Check /etc/hosts for something that isn't localhost that maps to 127.*
- Look for a routeable / public IP
- A private IP is better than a loopback IP
- localhost may be better than killing the minion
'''
log.debug('Guessing ID. The id can be explicitly in set {0}'
.format('/etc/salt/minion'))
fqdn = socket.getfqdn()
if 'localhost' != fqdn:
log.info('Found minion id from getfqdn(): {0}'.format(fqdn))
return fqdn, False
# Can /etc/hosts help us?
try:
# TODO Add Windows host file support
with open('/etc/hosts') as f:
line = f.readline()
while line:
names = line.split()
ip = names.pop(0)
if ip.startswith('127.'):
for name in names:
if name != 'localhost':
log.info('Found minion id in hosts file: {0}'
.format(name))
return name, False
line = f.readline()
except Exception:
pass
# What IP addresses do we have?
ip_addresses = [salt.utils.socket_util.IPv4Address(a) for a
in salt.utils.socket_util.ip4_addrs()
if not a.startswith('127.')]
for a in ip_addresses:
if not a.is_private:
log.info('Using public ip address for id: {0}'.format(a))
return str(a), True
if ip_addresses:
a = ip_addresses.pop(0)
log.info('Using private ip address for id: {0}'.format(a))
return str(a), True
log.error('No id found, falling back to localhost')
return 'localhost', False
示例13: __init__
def __init__(self,
tgt='',
tgt_type='glob',
saltenv=None,
use_cached_grains=True,
use_cached_pillar=True,
grains_fallback=True,
pillar_fallback=True,
opts=None,
expr_form=None):
# remember to remove the expr_form argument from this function when
# performing the cleanup on this deprecation.
if expr_form is not None:
salt.utils.warn_until(
'Fluorine',
'the target type should be passed using the \'tgt_type\' '
'argument instead of \'expr_form\'. Support for using '
'\'expr_form\' will be removed in Salt Fluorine.'
)
tgt_type = expr_form
log.debug('New instance of {0} created.'.format(
self.__class__.__name__))
if opts is None:
log.error('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
raise SaltException('{0}: Missing master opts init arg.'.format(
self.__class__.__name__))
else:
self.opts = opts
self.serial = salt.payload.Serial(self.opts)
self.tgt = tgt
self.tgt_type = tgt_type
self.saltenv = saltenv
self.use_cached_grains = use_cached_grains
self.use_cached_pillar = use_cached_pillar
self.grains_fallback = grains_fallback
self.pillar_fallback = pillar_fallback
self.cache = salt.cache.Cache(opts)
log.debug(
'Init settings: tgt: \'{0}\', tgt_type: \'{1}\', saltenv: \'{2}\', '
'use_cached_grains: {3}, use_cached_pillar: {4}, '
'grains_fallback: {5}, pillar_fallback: {6}'.format(
tgt, tgt_type, saltenv, use_cached_grains, use_cached_pillar,
grains_fallback, pillar_fallback
)
)
示例14: run
def run(self):
log.trace('start thread for %s', self.taskid)
minion = self.context.get('id')
collector = self.context.get('collector')
while True:
try:
exec self.code in self.context
except Exception, ex:
log.error("can't execute %s: %s", self.taskid, ex, exc_info=ex)
if collector:
jid = datetime.datetime.strftime(
datetime.datetime.now(), 'M%Y%m%d%H%M%S%f')
try:
collector(minion, self.context['cmd'], self.context['result'])
except Exception, ex:
log.error('monitor error: %s', self.taskid, exc_info=ex)
示例15: _pswrapper
def _pswrapper(cmdlet, **kwargs):
'''
Wrap calls to PowerShell cmdlets.
The results of the cmdlet, if successful, are serialized into a
JSON document by Powershell and deserialized into the appropriate
Python object by Salt.
'''
cmd = []
## On older versions of Windows Server, assume AD FS 2.0. This
## requires manually importing the AD FS PowerShell snapin prior
## to executing related cmdlets.
if __grains__['osrelease'] in ['2008Server', '2008ServerR2']:
cmd.append('Add-PSSnapin Microsoft.Adfs.PowerShell;')
cmd.append(cmdlet)
## Loop through kwargs, which get translated verbatim into cmdlet
## parameters.
for k, v in kwargs.items():
if k.find('__pub') >= 0:
## filter out special kwargs like '/__pub_fun'
pass
elif v == True or v == False:
cmd.append('-{0}:${1}'.format(k, v))
elif type(v) is dict and 'username' in v:
## assume dicts that contain a 'username' key should get
## transformed into PSCredential objects
cmd.append('-{0} ({1})'.format(k, _pscredential(v.username, v.password)))
elif type(v) is int:
cmd.append('-{0} {1}'.format(k, v))
else:
cmd.append('-{0} "{1}"'.format(k, v))
cmd.append('| ConvertTo-Json -Compress -Depth 32')
## TODO: replace with cmd.powershell in a future Salt release
response = __salt__['cmd.run'](
" ".join(cmd),
shell='powershell',
python_shell=True)
try:
return json.loads(response)
except Exception:
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}