Run black/isort on ara-plugins

There will be a follow up patch to add black/isort CI.

Change-Id: If3834babdb62ec12235676756ae82f81cd6cae28
This commit is contained in:
David Moreau Simard 2018-10-02 15:52:58 -05:00
parent b9792cfe57
commit 013324348c
No known key found for this signature in database
GPG Key ID: CBEB466764A9E621
1 changed files with 64 additions and 87 deletions

View File

@ -15,19 +15,20 @@
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
from __future__ import absolute_import, division, print_function
import datetime
import json
import logging
import os
import six
from ara.clients.offline import AraOfflineClient
from ara.clients.http import AraHttpClient
import six
from ansible import __version__ as ansible_version
from ansible.plugins.callback import CallbackBase
from ara.clients.http import AraHttpClient
from ara.clients.offline import AraOfflineClient
# To retrieve Ansible CLI options
try:
from __main__ import cli
@ -77,13 +78,14 @@ class CallbackModule(CallbackBase):
"""
Saves data from an Ansible run into a database
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'awesome'
CALLBACK_NAME = 'ara_default'
CALLBACK_TYPE = "awesome"
CALLBACK_NAME = "ara_default"
def __init__(self):
super(CallbackModule, self).__init__()
self.log = logging.getLogger('ara.plugins.callback.default')
self.log = logging.getLogger("ara.plugins.callback.default")
self.result = None
self.task = None
@ -111,7 +113,7 @@ class CallbackModule(CallbackBase):
raise Exception("Unsupported API client: %s. Please use 'offline' or 'http'" % api_client)
def v2_playbook_on_start(self, playbook):
self.log.debug('v2_playbook_on_start')
self.log.debug("v2_playbook_on_start")
path = os.path.abspath(playbook._file_name)
if self._options is not None:
@ -121,13 +123,10 @@ class CallbackModule(CallbackBase):
# Create the playbook
self.playbook = self.client.post(
'/api/v1/playbooks',
"/api/v1/playbooks",
ansible_version=ansible_version,
parameters=parameters,
file=dict(
path=path,
content=self._read_file(path)
)
file=dict(path=path, content=self._read_file(path)),
)
# Record all the files involved in the playbook
@ -136,7 +135,7 @@ class CallbackModule(CallbackBase):
return self.playbook
def v2_playbook_on_play_start(self, play):
self.log.debug('v2_playbook_on_play_start')
self.log.debug("v2_playbook_on_play_start")
self._end_task()
self._end_play()
@ -144,11 +143,7 @@ class CallbackModule(CallbackBase):
self._load_files(play._loader._FILE_CACHE.keys())
# Create the play
self.play = self.client.post(
'/api/v1/plays',
name=play.name,
playbook=self.playbook['id']
)
self.play = self.client.post("/api/v1/plays", name=play.name, playbook=self.playbook["id"])
# Record all the hosts involved in the play
self._load_hosts(play._variable_manager._inventory._restriction)
@ -156,16 +151,16 @@ class CallbackModule(CallbackBase):
return self.play
def v2_playbook_on_task_start(self, task, is_conditional, handler=False):
self.log.debug('v2_playbook_on_task_start')
self.log.debug("v2_playbook_on_task_start")
self._end_task()
pathspec = task.get_path()
if pathspec:
path, lineno = pathspec.split(':', 1)
path, lineno = pathspec.split(":", 1)
lineno = int(lineno)
else:
# Task doesn't have a path, default to "something"
path = self.playbook['path']
path = self.playbook["path"]
lineno = 1
# Ensure this task's file was added to the playbook -- files that are
@ -173,40 +168,40 @@ class CallbackModule(CallbackBase):
self._load_files([path])
# Find the task file (is there a better way?)
task_file = self.playbook['file']['id']
for file in self.playbook['files']:
if file['path'] == path:
task_file = file['id']
task_file = self.playbook["file"]["id"]
for file in self.playbook["files"]:
if file["path"] == path:
task_file = file["id"]
break
self.task = self.client.post(
'/api/v1/tasks',
"/api/v1/tasks",
name=task.get_name(),
action=task.action,
play=self.play['id'],
playbook=self.playbook['id'],
play=self.play["id"],
playbook=self.playbook["id"],
file=task_file,
tags=task._attributes['tags'],
tags=task._attributes["tags"],
lineno=lineno,
handler=handler
handler=handler,
)
return self.task
def v2_runner_on_ok(self, result, **kwargs):
self._load_result(result, 'ok', **kwargs)
self._load_result(result, "ok", **kwargs)
def v2_runner_on_unreachable(self, result, **kwargs):
self._load_result(result, 'unreachable', **kwargs)
self._load_result(result, "unreachable", **kwargs)
def v2_runner_on_failed(self, result, **kwargs):
self._load_result(result, 'failed', **kwargs)
self._load_result(result, "failed", **kwargs)
def v2_runner_on_skipped(self, result, **kwargs):
self._load_result(result, 'skipped', **kwargs)
self._load_result(result, "skipped", **kwargs)
def v2_playbook_on_stats(self, stats):
self.log.debug('v2_playbook_on_stats')
self.log.debug("v2_playbook_on_stats")
self._load_stats(stats)
self._end_task()
@ -216,9 +211,7 @@ class CallbackModule(CallbackBase):
def _end_task(self):
if self.task is not None:
self.client.patch(
'/api/v1/tasks/%s' % self.task['id'],
completed=True,
ended=datetime.datetime.now().isoformat()
"/api/v1/tasks/%s" % self.task["id"], completed=True, ended=datetime.datetime.now().isoformat()
)
self.task = None
self.loop_items = []
@ -226,52 +219,41 @@ class CallbackModule(CallbackBase):
def _end_play(self):
if self.play is not None:
self.client.patch(
'/api/v1/plays/%s' % self.play['id'],
completed=True,
ended=datetime.datetime.now().isoformat()
"/api/v1/plays/%s" % self.play["id"], completed=True, ended=datetime.datetime.now().isoformat()
)
self.play = None
def _end_playbook(self):
self.playbook = self.client.patch(
'/api/v1/playbooks/%s' % self.playbook['id'],
completed=True,
ended=datetime.datetime.now().isoformat()
"/api/v1/playbooks/%s" % self.playbook["id"], completed=True, ended=datetime.datetime.now().isoformat()
)
def _load_files(self, files):
self.log.debug('Loading %s file(s)...' % len(files))
playbook_files = [file['path'] for file in self.playbook['files']]
self.log.debug("Loading %s file(s)..." % len(files))
playbook_files = [file["path"] for file in self.playbook["files"]]
for file in files:
if file not in playbook_files:
self.client.post(
'/api/v1/playbooks/%s/files' % self.playbook['id'],
path=file,
content=self._read_file(file)
"/api/v1/playbooks/%s/files" % self.playbook["id"], path=file, content=self._read_file(file)
)
def _get_or_create_host(self, host):
self.log.debug('Getting or creating host: %s' % host)
self.log.debug("Getting or creating host: %s" % host)
# Don't query the API if we already have this host
for playbook_host in self.playbook['hosts']:
if host == playbook_host['name']:
for playbook_host in self.playbook["hosts"]:
if host == playbook_host["name"]:
return playbook_host
# TODO: Implement logic for computing the host alias
playbook_host = self.client.post(
'/api/v1/hosts',
name=host,
alias=host,
playbook=self.playbook['id']
)
playbook_host = self.client.post("/api/v1/hosts", name=host, alias=host, playbook=self.playbook["id"])
# Refresh cached playbook
self.playbook = self.client.get('/api/v1/playbooks/%s' % self.playbook['id'])
self.playbook = self.client.get("/api/v1/playbooks/%s" % self.playbook["id"])
return playbook_host
def _load_hosts(self, hosts):
self.log.debug('Loading %s hosts(s)...' % len(hosts))
self.log.debug("Loading %s hosts(s)..." % len(hosts))
for host in hosts:
self._get_or_create_host(host)
@ -299,34 +281,29 @@ class CallbackModule(CallbackBase):
results = json.loads(self._dump_results(result._result))
self.result = self.client.post(
'/api/v1/results',
task=self.task['id'],
host=host['id'],
"/api/v1/results",
task=self.task["id"],
host=host["id"],
content=results,
status=status,
started=self.task['started'],
started=self.task["started"],
ended=datetime.datetime.now().isoformat(),
changed=result._result.get('changed', False),
failed=result._result.get('failed', False),
skipped=result._result.get('skipped', False),
unreachable=result._result.get('unreachable', False),
ignore_errors=kwargs.get('ignore_errors', False)
changed=result._result.get("changed", False),
failed=result._result.get("failed", False),
skipped=result._result.get("skipped", False),
unreachable=result._result.get("unreachable", False),
ignore_errors=kwargs.get("ignore_errors", False),
)
if self.task['action'] == 'setup' and 'ansible_facts' in result._result:
self.client.patch(
'/api/v1/hosts/%s' % host['id'],
facts=result._result['ansible_facts']
)
if self.task["action"] == "setup" and "ansible_facts" in result._result:
self.client.patch("/api/v1/hosts/%s" % host["id"], facts=result._result["ansible_facts"])
def _read_file(self, path):
try:
with open(path, 'r') as fd:
with open(path, "r") as fd:
content = fd.read()
except IOError as e:
self.log.error("Unable to open {0} for reading: {1}".format(
path, six.text_type(e)
))
self.log.error("Unable to open {0} for reading: {1}".format(path, six.text_type(e)))
content = """ARA was not able to read this file successfully.
Refer to the logs for more information"""
return content
@ -337,12 +314,12 @@ class CallbackModule(CallbackBase):
host = self._get_or_create_host(hostname)
host_stats = stats.summarize(hostname)
self.client.post(
'/api/v1/stats',
playbook=self.playbook['id'],
host=host['id'],
changed=host_stats['changed'],
unreachable=host_stats['unreachable'],
failed=host_stats['failures'],
ok=host_stats['ok'],
skipped=host_stats['skipped']
"/api/v1/stats",
playbook=self.playbook["id"],
host=host["id"],
changed=host_stats["changed"],
unreachable=host_stats["unreachable"],
failed=host_stats["failures"],
ok=host_stats["ok"],
skipped=host_stats["skipped"],
)