Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formatting #324

Merged
merged 3 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.idea/
__pycache__/
2 changes: 2 additions & 0 deletions changelogs/fragments/324_formatting.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
trivial:
- Format with black, remove unused variables
7 changes: 5 additions & 2 deletions hacking/find_grafana_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@
def get_by_major(version):
if version.startswith("v"):
version = version[1:]
return (version[0], version, int(version.replace('.', '')))
return (version[0], version, int(version.replace(".", "")))


def get_grafana_releases():
r = requests.get('https://api.github.com/repos/grafana/grafana/releases?per_page=50', headers={"Accept": "application/vnd.github.v3+json"})
r = requests.get(
"https://api.github.com/repos/grafana/grafana/releases?per_page=50",
headers={"Accept": "application/vnd.github.v3+json"},
)
if r.status_code != 200:
raise Exception("Failed to get releases from GitHub")
return r.json()
Expand Down
115 changes: 68 additions & 47 deletions plugins/callback/grafana_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.

from __future__ import (absolute_import, division, print_function)
from __future__ import absolute_import, division, print_function

__metaclass__ = type

DOCUMENTATION = '''
DOCUMENTATION = """
name: grafana_annotations
type: notification
short_description: send ansible events as annotations on charts to grafana over http api.
Expand Down Expand Up @@ -104,7 +105,7 @@
default: []
type: list
elements: integer
'''
"""

import json
import socket
Expand Down Expand Up @@ -148,7 +149,7 @@


def to_millis(dt):
return int(dt.strftime('%s')) * 1000
return int(dt.strftime("%s")) * 1000

Check warning on line 152 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L152

Added line #L152 was not covered by tests


class CallbackModule(CallbackBase):
Expand All @@ -161,15 +162,15 @@
"""

CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'community.grafana.grafana_annotations'
CALLBACK_TYPE = "aggregate"
CALLBACK_NAME = "community.grafana.grafana_annotations"
CALLBACK_NEEDS_WHITELIST = True

def __init__(self, display=None):

super(CallbackModule, self).__init__(display=display)

self.headers = {'Content-Type': 'application/json'}
self.headers = {"Content-Type": "application/json"}

Check warning on line 173 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L173

Added line #L173 was not covered by tests
self.force_basic_auth = False
self.hostname = socket.gethostname()
self.username = getpass.getuser()
Expand All @@ -178,37 +179,42 @@

def set_options(self, task_keys=None, var_options=None, direct=None):

super(CallbackModule, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
super(CallbackModule, self).set_options(

Check warning on line 182 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L182

Added line #L182 was not covered by tests
task_keys=task_keys, var_options=var_options, direct=direct
)

self.grafana_api_key = self.get_option('grafana_api_key')
self.grafana_url = self.get_option('grafana_url')
self.validate_grafana_certs = self.get_option('validate_certs')
self.http_agent = self.get_option('http_agent')
self.grafana_user = self.get_option('grafana_user')
self.grafana_password = self.get_option('grafana_password')
self.dashboard_id = self.get_option('grafana_dashboard_id')
self.panel_ids = self.get_option('grafana_panel_ids')
self.grafana_api_key = self.get_option("grafana_api_key")
self.grafana_url = self.get_option("grafana_url")
self.validate_grafana_certs = self.get_option("validate_certs")
self.http_agent = self.get_option("http_agent")
self.grafana_user = self.get_option("grafana_user")
self.grafana_password = self.get_option("grafana_password")
self.dashboard_id = self.get_option("grafana_dashboard_id")
self.panel_ids = self.get_option("grafana_panel_ids")

Check warning on line 193 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L186-L193

Added lines #L186 - L193 were not covered by tests

if self.grafana_api_key:
self.headers['Authorization'] = "Bearer %s" % self.grafana_api_key
self.headers["Authorization"] = "Bearer %s" % self.grafana_api_key

Check warning on line 196 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L196

Added line #L196 was not covered by tests
else:
self.force_basic_auth = True

if self.grafana_url is None:
self.disabled = True
self._display.warning('Grafana URL was not provided. The '
'Grafana URL can be provided using '
'the `GRAFANA_URL` environment variable.')
self._display.debug('Grafana URL: %s' % self.grafana_url)
self._display.warning(

Check warning on line 202 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L202

Added line #L202 was not covered by tests
"Grafana URL was not provided. The "
"Grafana URL can be provided using "
"the `GRAFANA_URL` environment variable."
)
self._display.debug("Grafana URL: %s" % self.grafana_url)

Check warning on line 207 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L207

Added line #L207 was not covered by tests

def v2_playbook_on_start(self, playbook):
self.playbook = playbook._file_name
text = PLAYBOOK_START_TXT.format(playbook=self.playbook, hostname=self.hostname,
username=self.username)
text = PLAYBOOK_START_TXT.format(

Check warning on line 211 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L211

Added line #L211 was not covered by tests
playbook=self.playbook, hostname=self.hostname, username=self.username
)
data = {
'time': to_millis(self.start_time),
'text': text,
'tags': ['ansible', 'ansible_event_start', self.playbook, self.hostname]
"time": to_millis(self.start_time),
"text": text,
"tags": ["ansible", "ansible_event_start", self.playbook, self.hostname],
}
self._send_annotation(data)

Expand All @@ -223,30 +229,39 @@
if self.errors == 0:
status = "OK"

text = PLAYBOOK_STATS_TXT.format(playbook=self.playbook, hostname=self.hostname,
duration=duration.total_seconds(),
status=status, username=self.username,
summary=json.dumps(summarize_stat))
text = PLAYBOOK_STATS_TXT.format(

Check warning on line 232 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L232

Added line #L232 was not covered by tests
playbook=self.playbook,
hostname=self.hostname,
duration=duration.total_seconds(),
status=status,
username=self.username,
summary=json.dumps(summarize_stat),
)

data = {
'time': to_millis(self.start_time),
'timeEnd': to_millis(end_time),
'isRegion': True,
'text': text,
'tags': ['ansible', 'ansible_report', self.playbook, self.hostname]
"time": to_millis(self.start_time),
"timeEnd": to_millis(end_time),
"isRegion": True,
"text": text,
"tags": ["ansible", "ansible_report", self.playbook, self.hostname],
}
self._send_annotations(data)

def v2_runner_on_failed(self, result, ignore_errors=False, **kwargs):
text = PLAYBOOK_ERROR_TXT.format(playbook=self.playbook, hostname=self.hostname,
username=self.username, task=result._task,
host=result._host.name, result=self._dump_results(result._result))
text = PLAYBOOK_ERROR_TXT.format(

Check warning on line 251 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L251

Added line #L251 was not covered by tests
playbook=self.playbook,
hostname=self.hostname,
username=self.username,
task=result._task,
host=result._host.name,
result=self._dump_results(result._result),
)
if ignore_errors:
return
data = {
'time': to_millis(datetime.now()),
'text': text,
'tags': ['ansible', 'ansible_event_failure', self.playbook, self.hostname]
"time": to_millis(datetime.now()),
"text": text,
"tags": ["ansible", "ansible_event_failure", self.playbook, self.hostname],
}
self.errors += 1
self._send_annotations(data)
Expand All @@ -263,10 +278,16 @@

def _send_annotation(self, annotation):
try:
open_url(self.grafana_url, data=json.dumps(annotation), headers=self.headers,
method="POST",
validate_certs=self.validate_grafana_certs,
url_username=self.grafana_user, url_password=self.grafana_password,
http_agent=self.http_agent, force_basic_auth=self.force_basic_auth)
open_url(

Check warning on line 281 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L281

Added line #L281 was not covered by tests
self.grafana_url,
data=json.dumps(annotation),
headers=self.headers,
method="POST",
validate_certs=self.validate_grafana_certs,
url_username=self.grafana_user,
url_password=self.grafana_password,
http_agent=self.http_agent,
force_basic_auth=self.force_basic_auth,
)
except Exception as e:
self._display.error(u'Could not submit message to Grafana: %s' % to_text(e))
self._display.error("Could not submit message to Grafana: %s" % to_text(e))

Check warning on line 293 in plugins/callback/grafana_annotations.py

View check run for this annotation

Codecov / codecov/patch

plugins/callback/grafana_annotations.py#L293

Added line #L293 was not covered by tests
6 changes: 3 additions & 3 deletions plugins/doc_fragments/api_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@
# Copyright: (c) 2019, Rémi REY (@rrey)
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import (absolute_import, division, print_function)
from __future__ import absolute_import, division, print_function

__metaclass__ = type


class ModuleDocFragment(object):

DOCUMENTATION = r'''options:
DOCUMENTATION = r"""options:
grafana_api_key:
description:
- The Grafana API key.
- If set, C(url_username) and C(url_password) will be ignored.
type: str
'''
"""
6 changes: 3 additions & 3 deletions plugins/doc_fragments/basic_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
# Copyright: (c) 2019, Rémi REY (@rrey)
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import (absolute_import, division, print_function)
from __future__ import absolute_import, division, print_function

__metaclass__ = type


class ModuleDocFragment(object):

DOCUMENTATION = r'''options:
DOCUMENTATION = r"""options:
url:
description:
- The Grafana URL.
Expand Down Expand Up @@ -49,4 +49,4 @@ class ModuleDocFragment(object):
- This should only set to C(false) used on personally controlled sites using self-signed certificates.
type: bool
default: true
'''
"""
Loading
Loading