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

[CHANGES] Rewritten display of alerts and silences to use vuejs #124

Merged
merged 4 commits into from
Feb 13, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
6 changes: 6 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ contributors:
* License: licenses/LICENSE.moment.mit.txt (MIT License)
* Homepage: http://momentjs.com/

This product contains Vue.js, distributed by Yuxi (Evan) You and other
contributors:

* License: licenses/LICENSE.vuejs.mit.txt (MIT License)
* Homepage: https://vuejs.org

Dependencies
============

Expand Down
21 changes: 21 additions & 0 deletions licenses/LICENSE.vuejs.mit.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2013-present, Yuxi (Evan) You

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
23 changes: 11 additions & 12 deletions promgen/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import datetime

from django import forms

from dateutil import parser
from promgen import models, plugins


Expand Down Expand Up @@ -37,39 +37,38 @@ class ImportRuleForm(forms.Form):
class SilenceForm(forms.Form):
def validate_datetime(value):
try:
datetime.datetime.strptime(value, '%Y-%m-%d %H:%M')
parser.parse(value)
except:
raise forms.ValidationError('Invalid timestamp')

next = forms.CharField(required=False)
duration = forms.CharField(required=False)
start = forms.CharField(required=False, validators=[validate_datetime])
stop = forms.CharField(required=False, validators=[validate_datetime])
startsAt = forms.CharField(required=False, validators=[validate_datetime])
endsAt = forms.CharField(required=False, validators=[validate_datetime])
comment = forms.CharField(required=False)
created_by = forms.CharField(required=False)
createdBy = forms.CharField(required=False)

def clean_comment(self):
if self.cleaned_data['comment']:
return self.cleaned_data['comment']
return "Silenced from Promgen"

def clean_created_by(self):
if self.cleaned_data['created_by']:
return self.cleaned_data['created_by']
def clean_createdBy(self):
if self.cleaned_data['createdBy']:
return self.cleaned_data['createdBy']
return "Promgen"

def clean(self):
duration = self.data.get('duration')
start = self.data.get('start')
stop = self.data.get('stop')
start = self.data.get('startsAt')
stop = self.data.get('endsAt')

if duration:
# No further validation is required if only duration is set
return

if not all([start, stop]):
raise forms.ValidationError('Both start and end are required')
elif datetime.datetime.strptime(start, '%Y-%m-%d %H:%M') > datetime.datetime.strptime(stop, '%Y-%m-%d %H:%M'):
elif parser.parse(start) > parser.parse(stop):
raise forms.ValidationError('Start time and end time is mismatch')


Expand Down
6 changes: 5 additions & 1 deletion promgen/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@ def silence(labels, duration=None, **kwargs):
else:
raise Exception('Unknown time modifier')
kwargs['endsAt'] = end.isoformat()
kwargs.pop('startsAt', False)
else:
local_timezone = pytz.timezone(settings.PROMGEN.get('timezone', 'UTC'))
for key in ['startsAt', 'endsAt']:
Expand All @@ -448,4 +449,7 @@ def silence(labels, duration=None, **kwargs):

logger.debug('Sending silence for %s', kwargs)
url = urljoin(settings.PROMGEN['alertmanager']['url'], '/api/v1/silences')
util.post(url, json=kwargs).raise_for_status()
response = util.post(url, json=kwargs)
response.raise_for_status()
return response

77 changes: 75 additions & 2 deletions promgen/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@
# These sources are released under the terms of the MIT license: see LICENSE

import concurrent.futures
import json
import logging
from urllib.parse import urljoin

from django.http import JsonResponse
import requests
from dateutil import parser
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.template import defaultfilters
from django.views.generic import View
from django.views.generic.base import TemplateView
from promgen import models, util
from promgen import forms, models, prometheus, util
from requests.exceptions import HTTPError

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -174,3 +180,70 @@ def get(self, request):
return JsonResponse(
{"status": "success", "data": {"resultType": resultType, "result": data}}
)


class ProxyAlerts(View):
def get(self, request):
alerts = []
try:
url = urljoin(settings.PROMGEN["alertmanager"]["url"], "/api/v1/alerts")
response = util.get(url)
except requests.exceptions.ConnectionError:
logger.error("Error connecting to %s", url)
return JsonResponse({})

data = response.json().get("data", [])
if data is None:
# Return an empty alert-all if there are no active alerts from AM
return JsonResponse({})

for alert in data:
alert.setdefault("annotations", {})
# Humanize dates for frontend
for key in ["startsAt", "endsAt"]:
if key in alert:
alert[key] = parser.parse(alert[key])
# Convert any links to <a> for frontend
for k, v in alert["annotations"].items():
alert["annotations"][k] = defaultfilters.urlize(v)
alerts.append(alert)
return JsonResponse({"data": data}, safe=False)


class ProxySilences(View):
def get(self, request):
try:
url = urljoin(settings.PROMGEN["alertmanager"]["url"], "/api/v1/silences")
response = util.get(url, params={"silenced": False})
except requests.exceptions.ConnectionError:
logger.error("Error connecting to %s", url)
return JsonResponse({})
else:
return HttpResponse(response.content, content_type="application/json")

def post(self, request):
body = json.loads(request.body.decode("utf-8"))
body.setdefault("comment", "Silenced from Promgen")
body.setdefault("createdBy", request.user.email)

form = forms.SilenceForm(body)
if not form.is_valid():
return JsonResponse({"status": form.errors}, status=400)

response = prometheus.silence(body.pop("labels"), **form.cleaned_data)

return HttpResponse(
response.text, status=response.status_code, content_type="application/json"
)


class ProxyDeleteSilence(View):
def delete(self, request, silence_id):
url = urljoin(
settings.PROMGEN["alertmanager"]["url"], "/api/v1/silence/%s" % silence_id
)
response = util.delete(url)
return HttpResponse(
response.text, status=response.status_code, content_type="application/json"
)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

del line

98 changes: 0 additions & 98 deletions promgen/static/css/bootstrap-datetimepicker-standalone.css

This file was deleted.

5 changes: 0 additions & 5 deletions promgen/static/css/bootstrap-datetimepicker.min.css

This file was deleted.

8 changes: 8 additions & 0 deletions promgen/static/css/promgen.css
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,11 @@ a[rel]:after {
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(400px,1fr));
}

[v-cloak] {
display: none;
}

.dl-horizontal {
word-wrap: break-word;
}
2 changes: 0 additions & 2 deletions promgen/static/js/bootstrap-datetimepicker.min.js

This file was deleted.

Loading