本文整理汇总了Python中tower_cli.utils.debug.log函数的典型用法代码示例。如果您正苦于以下问题:Python log函数的具体用法?Python log怎么用?Python log使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了log函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update
def update(self, inventory_source, monitor=False, timeout=None, **kwargs):
"""Update the given inventory source."""
# Establish that we are able to update this inventory source
# at all.
debug.log('Asking whether the inventory source can be updated.',
header='details')
r = client.get('%s%d/update/' % (self.endpoint, inventory_source))
if not r.json()['can_update']:
raise exc.BadRequest('Tower says it cannot run an update against '
'this inventory source.')
# Run the update.
debug.log('Updating the inventory source.', header='details')
r = client.post('%s%d/update/' % (self.endpoint, inventory_source))
# If we were told to monitor the project update's status, do so.
if monitor:
result = self.monitor(inventory_source, timeout=timeout)
inventory = client.get('/inventory_sources/%d/' %
result['inventory_source'])\
.json()['inventory']
result['inventory'] = int(inventory)
return result
# Done.
return {'status': 'ok'}
示例2: _get_auth_token
def _get_auth_token(self):
filename = os.path.expanduser('~/.tower_cli_token.json')
token_json = None
try:
with open(filename) as f:
token_json = json.load(f)
if not isinstance(token_json, dict) or self.cli_client.get_prefix() not in token_json or \
'token' not in token_json[self.cli_client.get_prefix()] or \
'expires' not in token_json[self.cli_client.get_prefix()] or \
dt.utcnow() > dt.strptime(token_json[self.cli_client.get_prefix()]['expires'], TOWER_DATETIME_FMT):
raise Exception("Current token expires.")
return 'Token ' + token_json[self.cli_client.get_prefix()]['token']
except Exception as e:
debug.log('Acquiring and caching auth token due to:\n%s' % str(e), fg='blue', bold=True)
if not isinstance(token_json, dict):
token_json = {}
token_json[self.cli_client.get_prefix()] = self._acquire_token()
if not isinstance(token_json[self.cli_client.get_prefix()], dict) or \
'token' not in token_json[self.cli_client.get_prefix()] or \
'expires' not in token_json[self.cli_client.get_prefix()]:
raise exc.AuthError('Invalid Tower auth token format: %s' % json.dumps(
token_json[self.cli_client.get_prefix()]
))
with open(filename, 'w') as f:
json.dump(token_json, f)
try:
os.chmod(filename, stat.S_IRUSR | stat.S_IWUSR)
except Exception as e:
warnings.warn(
'Unable to set permissions on {0} - {1} '.format(filename, e),
UserWarning
)
return 'Token ' + token_json[self.cli_client.get_prefix()]['token']
示例3: delete
def delete(self, pk=None, fail_on_missing=False, **kwargs):
"""Remove the given object.
If `fail_on_missing` is True, then the object's not being found is
considered a failure; otherwise, a success with no change is reported.
"""
# If we weren't given a primary key, determine which record we're
# deleting.
if not pk:
existing_data = self._lookup(fail_on_missing=fail_on_missing,
**kwargs)
if not existing_data:
return {'changed': False}
pk = existing_data['id']
# Attempt to delete the record.
# If it turns out the record doesn't exist, handle the 404
# appropriately (this is an okay response if `fail_on_missing` is
# False).
url = '%s%d/' % (self.endpoint, pk)
debug.log('DELETE %s' % url, fg='blue', bold=True)
try:
client.delete(url)
return {'changed': True}
except exc.NotFound:
if fail_on_missing:
raise
return {'changed': False}
示例4: convert
def convert(self, value, param, ctx):
"""Return the appropriate interger value. If a non-integer is
provided, attempt a name-based lookup and return the primary key.
"""
resource = tower_cli.get_resource(self.resource_name)
# Ensure that None is passed through without trying to
# do anything.
if value is None:
return None
# If we were already given an integer, do nothing.
# This ensures that the convert method is idempotent.
if isinstance(value, int):
return value
# Do we have a string that contains only digits?
# If so, then convert it to an integer and return it.
if re.match(r'^[\d]+$', value):
return int(value)
# Okay, we have a string. Try to do a name-based lookup on the
# resource, and return back the ID that we get from that.
#
# This has the chance of erroring out, which is fine.
try:
debug.log('The %s field is given as a name; '
'looking it up.' % param.name, header='details')
rel = resource.get(**{resource.unique_criterion: value})
except exc.TowerCLIError as ex:
raise exc.RelatedError('Could not get %s. %s' %
(self.resource_name, str(ex)))
# Done! Return the ID.
return rel['id']
示例5: create
def create(self, organization=None, monitor=False, timeout=None,
*args, **kwargs):
"""Create a new item of resource, with or w/o org.
This would be a shared class with user, but it needs the ability
to monitor if the flag is set.
"""
backup_endpoint = self.endpoint
if organization:
debug.log("using alternative endpoint specific to organization",
header='details')
# Get the organization from Tower, will lookup name if needed
org_resource = get_resource('organization')
org_data = org_resource.get(organization)
org_pk = org_data['id']
self.endpoint = '/organizations/%s%s' % (org_pk, backup_endpoint)
answer = super(Resource, self).create(*args, **kwargs)
self.endpoint = backup_endpoint
# if the monitor flag is set, wait for the SCM to update
if monitor:
project_id = answer['id']
return self.monitor(project_id, timeout=timeout)
return answer
示例6: create
def create(self, organization=None, monitor=False, timeout=None,
fail_on_found=False, force_on_exists=False,
**kwargs):
"""Create a new item of resource, with or w/o org.
This would be a shared class with user, but it needs the ability
to monitor if the flag is set.
"""
# First, run the create method, ignoring the organization given
answer = super(Resource, self).write(
create_on_missing=True,
fail_on_found=fail_on_found, force_on_exists=force_on_exists,
**kwargs
)
project_id = answer['id']
# If an organization is given, associate it here
if organization:
# Get the organization from Tower, will lookup name if needed
org_resource = get_resource('organization')
org_data = org_resource.get(organization)
org_pk = org_data['id']
debug.log("associating the project with its organization",
header='details', nl=1)
org_resource._assoc('projects', org_pk, project_id)
# if the monitor flag is set, wait for the SCM to update
if monitor:
return self.monitor(project_id, timeout=timeout)
return answer
示例7: update
def update(self, pk=None, create_on_missing=False, monitor=False,
timeout=None, name=None, organization=None):
"""Trigger a project update job within Ansible Tower.
Only meaningful on non-manual projects.
"""
# First, get the appropriate project.
# This should be uniquely identified at this point, and if not, then
# we just want the error that `get` will throw to bubble up.
project = self.get(pk, name=name, organization=organization)
pk = project['id']
# Determine whether this project is able to be updated.
debug.log('Asking whether the project can be updated.',
header='details')
result = client.get('/projects/%d/update/' % pk)
if not result.json()['can_update']:
raise exc.CannotStartJob('Cannot update project.')
# Okay, this project can be updated, according to Tower.
# Commence the update.
debug.log('Updating the project.', header='details')
result = client.post('/projects/%d/update/' % pk)
# If we were told to monitor the project update's status, do so.
if monitor:
return self.monitor(pk, timeout=timeout)
# Return the project update ID.
return {
'changed': True,
}
示例8: status
def status(self, pk=None, detail=False, **kwargs):
"""Print the current job status. This is used to check a running job.
You can look up the job with the same parameters used for a get
request."""
# Remove default values (anything where the value is None).
self._pop_none(kwargs)
# Search for the record if pk not given
if not pk:
job = self.get(include_debug_header=True, **kwargs)
# Get the job from Ansible Tower if pk given
else:
debug.log('Asking for job status.', header='details')
finished_endpoint = '%s%d/' % (self.endpoint, pk)
job = client.get(finished_endpoint).json()
# In most cases, we probably only want to know the status of the job
# and the amount of time elapsed. However, if we were asked for
# verbose information, provide it.
if detail:
return job
# Print just the information we need.
return adict({
'elapsed': job['elapsed'],
'failed': job['failed'],
'status': job['status'],
})
示例9: list
def list(self, all_pages=False, **kwargs):
"""Return a list of objects.
If one or more filters are provided through keyword arguments,
filter the results accordingly.
If no filters are provided, return all results.
"""
# If the `all_pages` flag is set, then ignore any page that might
# also be sent.
if all_pages:
kwargs.pop('page', None)
# Get the response.
debug.log('Getting records.', header='details')
response = self.read(**kwargs)
# Alter the "next" and "previous" to reflect simple integers,
# rather than URLs, since this endpoint just takes integers.
for key in ('next', 'previous'):
if not response[key]:
continue
match = re.search(r'page=(?P<num>[\d]+)', response[key])
response[key] = int(match.groupdict()['num'])
# If we were asked for all pages, keep retrieving pages until we
# have them all.
if all_pages and response['next']:
cursor = copy(response)
while cursor['next']:
cursor = self.list(**dict(kwargs, page=cursor['next']))
response['results'] += cursor['results']
# Done; return the response
return response
示例10: test_not_verbose_mode
def test_not_verbose_mode(self):
"""Establish that this method does nothing if we are not in
verbose mode.
"""
with settings.runtime_values(verbose=False):
with mock.patch.object(click, 'secho') as secho:
debug.log('foo bar baz')
self.assertEqual(secho.call_count, 0)
示例11: launch
def launch(self, monitor=False, wait=False, timeout=None, **kwargs):
"""Launch a new ad-hoc command.
Runs a user-defined command from Ansible Tower, immediately starts it,
and returns back an ID in order for its status to be monitored.
=====API DOCS=====
Launch a new ad-hoc command.
:param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched command rather
than exiting with a success.
:type monitor: bool
:param wait: Flag that if set, monitor the status of the job, but do not print while job is in progress.
:type wait: bool
:param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
of seconds.
:type timeout: int
:param `**kwargs`: Fields needed to create and launch an ad hoc command.
:returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
call if ``wait`` flag is on; dictionary of "id" and "changed" if none of the two flags are on.
:rtype: dict
:raises tower_cli.exceptions.TowerCLIError: When ad hoc commands are not available in Tower backend.
=====API DOCS=====
"""
# This feature only exists for versions 2.2 and up
r = client.get('/')
if 'ad_hoc_commands' not in r.json():
raise exc.TowerCLIError('Your host is running an outdated version'
'of Ansible Tower that can not run '
'ad-hoc commands (2.2 or earlier)')
# Pop the None arguments because we have no .write() method in
# inheritance chain for this type of resource. This is needed
self._pop_none(kwargs)
# Actually start the command.
debug.log('Launching the ad-hoc command.', header='details')
result = client.post(self.endpoint, data=kwargs)
command = result.json()
command_id = command['id']
# If we were told to monitor the command once it started, then call
# monitor from here.
if monitor:
return self.monitor(command_id, timeout=timeout)
elif wait:
return self.wait(command_id, timeout=timeout)
# Return the command ID and other response data
answer = OrderedDict((
('changed', True),
('id', command_id),
))
answer.update(result.json())
return answer
示例12: create
def create(self, **kwargs):
if (kwargs.get('user', False) or kwargs.get('team', False) or
kwargs.get('organization', False)):
debug.log('Checking Project API Details.', header='details')
r = client.options('/credentials/')
if 'organization' in r.json()['actions']['POST']:
for i in range(len(self.fields)):
if self.fields[i].name in ('user', 'team', 'credential'):
self.fields[i].no_lookup = True
return super(Resource, self).create(**kwargs)
示例13: test_extra_newlines
def test_extra_newlines(self):
"""Establish that extra newlines are correctly applied if they
are requested.
"""
s = 'All your base are belong to us.'
with mock.patch.object(click, 'secho') as secho:
with settings.runtime_values(verbose=True):
debug.log(s, nl=3)
self.assertEqual(secho.mock_calls[0][1][0],
'All your base are belong to us.\n\n')
示例14: get
def get(self, pk=None, **kwargs):
"""Get information about a role."""
if kwargs.pop('include_debug_header', True):
debug.log('Getting the role record.', header='details')
data, self.endpoint = self.data_endpoint(kwargs)
response = self.read(pk=pk, fail_on_no_results=True,
fail_on_multiple_results=True, **data)
item_dict = response['results'][0]
self.configure_display(item_dict)
return item_dict
示例15: update
def update(self, inventory_source, monitor=False, wait=False,
timeout=None, **kwargs):
"""Update the given inventory source.
=====API DOCS=====
Update the given inventory source.
:param inventory_source: Primary key or name of the inventory source to be updated.
:type inventory_source: str
:param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched inventory update
rather than exiting with a success.
:type monitor: bool
:param wait: Flag that if set, monitor the status of the inventory update, but do not print while it is
in progress.
:type wait: bool
:param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
of seconds.
:type timeout: int
:param `**kwargs`: Fields used to override underlyingl inventory source fields when creating and launching
an inventory update.
:returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
call if ``wait`` flag is on; dictionary of "status" if none of the two flags are on.
:rtype: dict
:raises tower_cli.exceptions.BadRequest: When the inventory source cannot be updated.
=====API DOCS=====
"""
# Establish that we are able to update this inventory source
# at all.
debug.log('Asking whether the inventory source can be updated.', header='details')
r = client.get('%s%d/update/' % (self.endpoint, inventory_source))
if not r.json()['can_update']:
raise exc.BadRequest('Tower says it cannot run an update against this inventory source.')
# Run the update.
debug.log('Updating the inventory source.', header='details')
r = client.post('%s%d/update/' % (self.endpoint, inventory_source), data={})
inventory_update_id = r.json()['inventory_update']
# If we were told to monitor the project update's status, do so.
if monitor or wait:
if monitor:
result = self.monitor(inventory_update_id, parent_pk=inventory_source, timeout=timeout)
elif wait:
result = self.wait(inventory_update_id, parent_pk=inventory_source, timeout=timeout)
inventory = client.get('/inventory_sources/%d/' % result['inventory_source']).json()['inventory']
result['inventory'] = int(inventory)
return result
# Done.
return {
'id': inventory_update_id,
'status': 'ok'
}