@Controller('/api/prometheus_receiver', secure=False)
class PrometheusReceiver(BaseController):
- # The receiver is needed in order to receive alert notifications (reports)
+ ''' The receiver is needed in order to receive alert notifications (reports) '''
notifications = []
@Endpoint('POST', path='/')
def fetch_alert(self, **notification):
notification['notified'] = datetime.now().isoformat()
+ notification['id'] = str(len(self.notifications))
self.notifications.append(notification)
@ApiController('/prometheus', Scope.PROMETHEUS)
class Prometheus(RESTController):
+
def _get_api_url(self):
return Settings.ALERTMANAGER_API_HOST.rstrip('/') + '/api/v1'
def list(self, **params):
return self._api_request('/alerts', params)
- @RESTController.Collection('POST')
- def get_notifications_since(self, **last_notification):
- notifications = PrometheusReceiver.notifications
- if last_notification not in notifications:
- return notifications[-1:]
- index = notifications.index(last_notification)
- return notifications[index + 1:]
+
+@ApiController('/prometheus/notifications', Scope.PROMETHEUS)
+class PrometheusNotifications(RESTController):
+
+ def list(self, **params):
+ if 'from' in params:
+ f = params['from']
+ if f == 'last':
+ return PrometheusReceiver.notifications[-1:]
+ return PrometheusReceiver.notifications[int(f) + 1:]
+ return PrometheusReceiver.notifications
import { TestBed } from '@angular/core/testing';
import { configureTestBed } from '../../../testing/unit-test-helper';
+import { PrometheusNotification } from '../models/prometheus-alerts';
import { PrometheusService } from './prometheus.service';
import { SettingsService } from './settings.service';
expect(req.request.method).toBe('GET');
});
- it('should call getNotificationSince', () => {
- service.getNotificationSince({}).subscribe();
- const req = httpTesting.expectOne('api/prometheus/get_notifications_since');
- expect(req.request.method).toBe('POST');
+ it('should call getNotificationSince without a notification', () => {
+ service.getNotifications().subscribe();
+ const req = httpTesting.expectOne('api/prometheus/notifications?from=last');
+ expect(req.request.method).toBe('GET');
+ });
+
+ it('should call getNotificationSince with notification', () => {
+ service.getNotifications({ id: '42' } as PrometheusNotification).subscribe();
+ const req = httpTesting.expectOne('api/prometheus/notifications?from=42');
+ expect(req.request.method).toBe('GET');
});
describe('ifAlertmanagerConfigured', () => {
return this.http.get<PrometheusAlert[]>(this.baseURL, { params });
}
- getNotificationSince(notification): Observable<PrometheusNotification[]> {
- return this.http.post<PrometheusNotification[]>(
- `${this.baseURL}/get_notifications_since`,
- notification
- );
+ getNotifications(notification?: PrometheusNotification): Observable<PrometheusNotification[]> {
+ const url = `${this.baseURL}/notifications?from=${
+ notification && notification.id ? notification.id : 'last'
+ }`;
+ return this.http.get<PrometheusNotification[]>(url);
}
}
commonAnnotations: object;
groupKey: string;
notified: string;
+ id: string;
alerts: PrometheusNotificationAlert[];
version: string;
receiver: string;
spyOn(window, 'setTimeout').and.callFake((fn: Function) => fn());
prometheusService = TestBed.get(PrometheusService);
- spyOn(prometheusService, 'getNotificationSince').and.callFake(() => of(notifications));
+ spyOn(prometheusService, 'getNotifications').and.callFake(() => of(notifications));
notifications = [prometheus.createNotification()];
});
describe('getLastNotification', () => {
it('returns an empty object on the first call', () => {
service.refresh();
- expect(prometheusService.getNotificationSince).toHaveBeenCalledWith({});
+ expect(prometheusService.getNotifications).toHaveBeenCalledWith(undefined);
expect(service['notifications'].length).toBe(1);
});
service.refresh();
notifications = [prometheus.createNotification(1, 'resolved')];
service.refresh();
- expect(prometheusService.getNotificationSince).toHaveBeenCalledWith(
- service['notifications'][0]
- );
+ expect(prometheusService.getNotifications).toHaveBeenCalledWith(service['notifications'][0]);
expect(service['notifications'].length).toBe(2);
notifications = [prometheus.createNotification(2)];
service.refresh();
notifications = [prometheus.createNotification(3, 'resolved')];
service.refresh();
- expect(prometheusService.getNotificationSince).toHaveBeenCalledWith(
- service['notifications'][2]
- );
+ expect(prometheusService.getNotifications).toHaveBeenCalledWith(service['notifications'][2]);
expect(service['notifications'].length).toBe(4);
});
});
}
refresh() {
- const last = this.getLastNotification();
this.prometheusService
- .getNotificationSince(last)
+ .getNotifications(_.last(this.notifications))
.subscribe((notifications) => this.handleNotifications(notifications));
}
- private getLastNotification() {
- return _.last(this.notifications) || {};
- }
-
private handleNotifications(notifications: PrometheusNotification[]) {
if (notifications.length === 0) {
return;
# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
from . import ControllerTestCase
from .. import mgr
from ..controllers import BaseController, Controller
-from ..controllers.prometheus import Prometheus, PrometheusReceiver
+from ..controllers.prometheus import Prometheus, PrometheusReceiver, PrometheusNotifications
@Controller('alertmanager/mocked/api/v1/alerts', secure=False)
'ALERTMANAGER_API_HOST': 'http://localhost:{}/alertmanager/mocked/'.format(54583)
}
mgr.get_module_option.side_effect = settings.get
- Prometheus._cp_config['tools.authenticate.on'] = False # pylint: disable=protected-access
- cls.setup_controllers([AlertManagerMockInstance, Prometheus, PrometheusReceiver])
+ Prometheus._cp_config['tools.authenticate.on'] = False
+ PrometheusNotifications._cp_config['tools.authenticate.on'] = False
+ cls.setup_controllers([AlertManagerMockInstance, Prometheus,
+ PrometheusNotifications, PrometheusReceiver])
def test_list(self):
self._get('/api/prometheus')
self.assertEqual(notification['name'], 'foo')
self.assertTrue(len(notification['notified']) > 20)
- def test_get_last_notification_with_empty_notifications(self):
+ def test_get_empty_list_with_no_notifications(self):
+ PrometheusReceiver.notifications = []
+ self._get('/api/prometheus/notifications')
+ self.assertStatus(200)
+ self.assertJsonBody([])
+ self._get('/api/prometheus/notifications?from=last')
+ self.assertStatus(200)
+ self.assertJsonBody([])
+
+ def test_get_all_notification(self):
+ PrometheusReceiver.notifications = []
+ self._post('/api/prometheus_receiver', {'name': 'foo'})
+ self._post('/api/prometheus_receiver', {'name': 'bar'})
+ self._get('/api/prometheus/notifications')
+ self.assertStatus(200)
+ self.assertJsonBody(PrometheusReceiver.notifications)
+
+ def test_get_last_notification_with_use_of_last_keyword(self):
PrometheusReceiver.notifications = []
self._post('/api/prometheus_receiver', {'name': 'foo'})
self._post('/api/prometheus_receiver', {'name': 'bar'})
- self._post('/api/prometheus/get_notifications_since', {})
+ self._get('/api/prometheus/notifications?from=last')
self.assertStatus(200)
last = PrometheusReceiver.notifications[1]
- self.assertEqual(self.jsonBody(), [last])
+ self.assertJsonBody([last])
- def test_get_no_notification_since_with_last_notification(self):
+ def test_get_no_notification_with_unknown_id(self):
PrometheusReceiver.notifications = []
self._post('/api/prometheus_receiver', {'name': 'foo'})
- notification = PrometheusReceiver.notifications[0]
- self._post('/api/prometheus/get_notifications_since', notification)
- self.assertBody('[]')
+ self._post('/api/prometheus_receiver', {'name': 'bar'})
+ self._get('/api/prometheus/notifications?from=42')
+ self.assertStatus(200)
+ self.assertJsonBody([])
- def test_get_empty_list_with_no_notifications(self):
+ def test_get_no_notification_since_with_last_notification(self):
PrometheusReceiver.notifications = []
- self._post('/api/prometheus/get_notifications_since', {})
- self.assertEqual(self.jsonBody(), [])
+ self._post('/api/prometheus_receiver', {'name': 'foo'})
+ notification = PrometheusReceiver.notifications[0]
+ self._get('/api/prometheus/notifications?from=' + notification['id'])
+ self.assertStatus(200)
+ self.assertJsonBody([])
def test_get_notifications_since_last_notification(self):
PrometheusReceiver.notifications = []
next_to_last = PrometheusReceiver.notifications[0]
self._post('/api/prometheus_receiver', {'name': 'foo'})
self._post('/api/prometheus_receiver', {'name': 'bar'})
- self._post('/api/prometheus/get_notifications_since', next_to_last)
+ self._get('/api/prometheus/notifications?from=' + next_to_last['id'])
foreLast = PrometheusReceiver.notifications[1]
last = PrometheusReceiver.notifications[2]
self.assertEqual(self.jsonBody(), [foreLast, last])