Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c466542990 | ||
|
|
9cb8c37298 | ||
|
|
f6f7e15735 | ||
|
|
c712133df0 | ||
|
|
fc016bd682 | ||
|
|
0e586e4152 | ||
|
|
ea425773e0 | ||
|
|
10949b11f4 | ||
|
|
0e022d04b1 | ||
|
|
3319e158b5 | ||
|
|
f467a77ae2 | ||
|
|
56048725e4 | ||
|
|
425c1d3674 | ||
|
|
8838f6f2ad | ||
|
|
139a78b2f6 | ||
|
|
dd5e3ee7ee | ||
|
|
9f8f7bb45e | ||
|
|
27e246859e | ||
|
|
f1688ac87a | ||
|
|
54779e1db8 | ||
|
|
be9087bee3 | ||
|
|
4ab5724fc1 | ||
|
|
45a47940ad | ||
|
|
1777d69495 | ||
|
|
8676b83fe3 | ||
|
|
b67701ff6d | ||
|
|
eb9acef9b5 | ||
|
|
00aec70fb8 | ||
|
|
18d28fc362 | ||
|
|
eb3545e994 | ||
|
|
ad71c8db34 | ||
|
|
6da281bf4e | ||
|
|
3dd8ba1a99 | ||
|
|
2503d21522 | ||
|
|
36a3419aec | ||
|
|
7353fad809 | ||
|
|
b5a26caa08 | ||
|
|
d7206546af | ||
|
|
4fa86a2c46 | ||
|
|
a6ed23b169 | ||
|
|
d9201c5084 | ||
|
|
d0ba8261e3 | ||
|
|
f89447badc | ||
|
|
14c42f6e6d | ||
|
|
7a05bdcb82 | ||
|
|
5eb7763052 | ||
|
|
8c73ae6035 | ||
|
|
6954e9dde7 | ||
|
|
f6336eac4e | ||
|
|
0331c18401 | ||
|
|
1f8fd29dad | ||
|
|
5877c4b2be | ||
|
|
c6d0809ecc | ||
|
|
cf8a601104 | ||
|
|
96a0eebc0c | ||
|
|
2af3425b9e | ||
|
|
31bf2aeb80 | ||
|
|
787f6f0d74 | ||
|
|
17a431321c | ||
|
|
05e9add16d | ||
|
|
c4ef56511d | ||
|
|
cfa2c8ef6f | ||
|
|
f36b6863ce | ||
|
|
24482cf7a0 | ||
|
|
d661a0ea6d | ||
|
|
a0ec6941ab | ||
|
|
5e711fb3b9 | ||
|
|
ab66e7ec8a | ||
|
|
08aba6cd51 | ||
|
|
d3805cd77a | ||
|
|
dd70136e6c | ||
|
|
a94c480c22 | ||
|
|
10fd4ecd6b | ||
|
|
9287e2f9e2 | ||
|
|
257f859825 | ||
|
|
3a4ab62ddd | ||
|
|
a4e9d8e9b0 | ||
|
|
3be6d04d29 | ||
|
|
b59ff6f89e | ||
|
|
813fea93ee | ||
|
|
8f50e44b45 | ||
|
|
fb2448c15a | ||
|
|
db575aad13 | ||
|
|
6ed93d4b82 | ||
|
|
634123d723 | ||
|
|
75c25ac053 |
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
examples
|
.examples
|
||||||
Dockerfile
|
Dockerfile
|
||||||
.github
|
.github
|
||||||
.idea
|
.idea
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
## Usage
|
||||||
|
```console
|
||||||
|
docker-compose up
|
||||||
|
```
|
||||||
|
Once you've done the above, you should be able to access the Grafana dashboard at `http://localhost:3000`.
|
||||||
|
|
||||||
|
## Queries
|
||||||
|
Gatus uses Prometheus counters.
|
||||||
|
|
||||||
|
Total results per minute:
|
||||||
|
```
|
||||||
|
sum(rate(gatus_results_total[5m])*60) by (key)
|
||||||
|
```
|
||||||
|
|
||||||
|
Total successful results per minute:
|
||||||
|
```
|
||||||
|
sum(rate(gatus_results_total{success="true"}[5m])*60) by (key)
|
||||||
|
```
|
||||||
|
|
||||||
|
Total unsuccessful results per minute:
|
||||||
|
```
|
||||||
|
sum(rate(gatus_results_total{success="true"}[5m])*60) by (key)
|
||||||
|
```
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
metrics: true
|
metrics: true
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
interval: 30s
|
interval: 30s
|
||||||
@@ -15,7 +15,6 @@
|
|||||||
"editable": true,
|
"editable": true,
|
||||||
"gnetId": null,
|
"gnetId": null,
|
||||||
"graphTooltip": 0,
|
"graphTooltip": 0,
|
||||||
"id": 2,
|
|
||||||
"links": [],
|
"links": [],
|
||||||
"panels": [
|
"panels": [
|
||||||
{
|
{
|
||||||
@@ -24,20 +23,26 @@
|
|||||||
"dashLength": 10,
|
"dashLength": 10,
|
||||||
"dashes": false,
|
"dashes": false,
|
||||||
"datasource": null,
|
"datasource": null,
|
||||||
|
"description": "Number of results per minute",
|
||||||
"fill": 1,
|
"fill": 1,
|
||||||
"fillGradient": 0,
|
"fillGradient": 0,
|
||||||
"gridPos": {
|
"gridPos": {
|
||||||
"h": 14,
|
"h": 7,
|
||||||
"w": 12,
|
"w": 12,
|
||||||
"x": 0,
|
"x": 0,
|
||||||
"y": 0
|
"y": 0
|
||||||
},
|
},
|
||||||
"id": 2,
|
"id": 2,
|
||||||
|
"interval": "",
|
||||||
"legend": {
|
"legend": {
|
||||||
|
"alignAsTable": false,
|
||||||
"avg": false,
|
"avg": false,
|
||||||
"current": false,
|
"current": false,
|
||||||
|
"hideEmpty": false,
|
||||||
|
"hideZero": false,
|
||||||
"max": false,
|
"max": false,
|
||||||
"min": false,
|
"min": false,
|
||||||
|
"rightSide": false,
|
||||||
"show": true,
|
"show": true,
|
||||||
"total": false,
|
"total": false,
|
||||||
"values": false
|
"values": false
|
||||||
@@ -58,9 +63,13 @@
|
|||||||
"steppedLine": false,
|
"steppedLine": false,
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"expr": "sum(rate(gatus_tasks[30s])) by (service)",
|
"expr": "sum(rate(gatus_results_total[5m])*60) by (key)",
|
||||||
|
"format": "time_series",
|
||||||
|
"hide": false,
|
||||||
|
"instant": false,
|
||||||
"interval": "30s",
|
"interval": "30s",
|
||||||
"legendFormat": "{{service}}",
|
"intervalFactor": 1,
|
||||||
|
"legendFormat": "{{key}}",
|
||||||
"refId": "A"
|
"refId": "A"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -68,7 +77,7 @@
|
|||||||
"timeFrom": null,
|
"timeFrom": null,
|
||||||
"timeRegions": [],
|
"timeRegions": [],
|
||||||
"timeShift": null,
|
"timeShift": null,
|
||||||
"title": "All tasks executed over time",
|
"title": "Total results per minute",
|
||||||
"tooltip": {
|
"tooltip": {
|
||||||
"shared": true,
|
"shared": true,
|
||||||
"sort": 0,
|
"sort": 0,
|
||||||
@@ -84,6 +93,7 @@
|
|||||||
},
|
},
|
||||||
"yaxes": [
|
"yaxes": [
|
||||||
{
|
{
|
||||||
|
"decimals": null,
|
||||||
"format": "short",
|
"format": "short",
|
||||||
"label": null,
|
"label": null,
|
||||||
"logBase": 1,
|
"logBase": 1,
|
||||||
@@ -119,93 +129,6 @@
|
|||||||
"x": 12,
|
"x": 12,
|
||||||
"y": 0
|
"y": 0
|
||||||
},
|
},
|
||||||
"id": 3,
|
|
||||||
"legend": {
|
|
||||||
"avg": false,
|
|
||||||
"current": false,
|
|
||||||
"max": false,
|
|
||||||
"min": false,
|
|
||||||
"show": true,
|
|
||||||
"total": false,
|
|
||||||
"values": false
|
|
||||||
},
|
|
||||||
"lines": true,
|
|
||||||
"linewidth": 1,
|
|
||||||
"nullPointMode": "null",
|
|
||||||
"options": {
|
|
||||||
"dataLinks": []
|
|
||||||
},
|
|
||||||
"percentage": false,
|
|
||||||
"pointradius": 2,
|
|
||||||
"points": false,
|
|
||||||
"renderer": "flot",
|
|
||||||
"seriesOverrides": [],
|
|
||||||
"spaceLength": 10,
|
|
||||||
"stack": false,
|
|
||||||
"steppedLine": false,
|
|
||||||
"targets": [
|
|
||||||
{
|
|
||||||
"expr": "sum(rate(gatus_tasks{success=\"false\"}[30s])) by (service)",
|
|
||||||
"interval": "30s",
|
|
||||||
"legendFormat": "{{service}}",
|
|
||||||
"refId": "A"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"thresholds": [],
|
|
||||||
"timeFrom": null,
|
|
||||||
"timeRegions": [],
|
|
||||||
"timeShift": null,
|
|
||||||
"title": "Unsuccessful tasks",
|
|
||||||
"tooltip": {
|
|
||||||
"shared": true,
|
|
||||||
"sort": 0,
|
|
||||||
"value_type": "individual"
|
|
||||||
},
|
|
||||||
"type": "graph",
|
|
||||||
"xaxis": {
|
|
||||||
"buckets": null,
|
|
||||||
"mode": "time",
|
|
||||||
"name": null,
|
|
||||||
"show": true,
|
|
||||||
"values": []
|
|
||||||
},
|
|
||||||
"yaxes": [
|
|
||||||
{
|
|
||||||
"format": "short",
|
|
||||||
"label": null,
|
|
||||||
"logBase": 1,
|
|
||||||
"max": null,
|
|
||||||
"min": null,
|
|
||||||
"show": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"format": "short",
|
|
||||||
"label": null,
|
|
||||||
"logBase": 1,
|
|
||||||
"max": null,
|
|
||||||
"min": null,
|
|
||||||
"show": true
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"yaxis": {
|
|
||||||
"align": false,
|
|
||||||
"alignLevel": null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"aliasColors": {},
|
|
||||||
"bars": false,
|
|
||||||
"dashLength": 10,
|
|
||||||
"dashes": false,
|
|
||||||
"datasource": null,
|
|
||||||
"fill": 1,
|
|
||||||
"fillGradient": 0,
|
|
||||||
"gridPos": {
|
|
||||||
"h": 7,
|
|
||||||
"w": 12,
|
|
||||||
"x": 12,
|
|
||||||
"y": 7
|
|
||||||
},
|
|
||||||
"id": 5,
|
"id": 5,
|
||||||
"legend": {
|
"legend": {
|
||||||
"avg": false,
|
"avg": false,
|
||||||
@@ -232,10 +155,10 @@
|
|||||||
"steppedLine": false,
|
"steppedLine": false,
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"expr": "sum(rate(gatus_tasks{success=\"true\"}[30s])) by (service)",
|
"expr": "sum(rate(gatus_results_total{success=\"true\"}[5m])*60) by (key)",
|
||||||
"instant": false,
|
"instant": false,
|
||||||
"interval": "30s",
|
"interval": "30s",
|
||||||
"legendFormat": "{{service}}",
|
"legendFormat": "{{key}}",
|
||||||
"refId": "A"
|
"refId": "A"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -243,7 +166,183 @@
|
|||||||
"timeFrom": null,
|
"timeFrom": null,
|
||||||
"timeRegions": [],
|
"timeRegions": [],
|
||||||
"timeShift": null,
|
"timeShift": null,
|
||||||
"title": "Successful tasks",
|
"title": "Successful results per minute",
|
||||||
|
"tooltip": {
|
||||||
|
"shared": true,
|
||||||
|
"sort": 0,
|
||||||
|
"value_type": "individual"
|
||||||
|
},
|
||||||
|
"type": "graph",
|
||||||
|
"xaxis": {
|
||||||
|
"buckets": null,
|
||||||
|
"mode": "time",
|
||||||
|
"name": null,
|
||||||
|
"show": true,
|
||||||
|
"values": []
|
||||||
|
},
|
||||||
|
"yaxes": [
|
||||||
|
{
|
||||||
|
"decimals": null,
|
||||||
|
"format": "short",
|
||||||
|
"label": null,
|
||||||
|
"logBase": 1,
|
||||||
|
"max": null,
|
||||||
|
"min": null,
|
||||||
|
"show": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"format": "short",
|
||||||
|
"label": null,
|
||||||
|
"logBase": 1,
|
||||||
|
"max": null,
|
||||||
|
"min": null,
|
||||||
|
"show": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"yaxis": {
|
||||||
|
"align": false,
|
||||||
|
"alignLevel": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cacheTimeout": null,
|
||||||
|
"colorBackground": false,
|
||||||
|
"colorPostfix": false,
|
||||||
|
"colorPrefix": false,
|
||||||
|
"colorValue": true,
|
||||||
|
"colors": [
|
||||||
|
"#299c46",
|
||||||
|
"rgba(237, 129, 40, 0.89)",
|
||||||
|
"#d44a3a"
|
||||||
|
],
|
||||||
|
"datasource": null,
|
||||||
|
"format": "none",
|
||||||
|
"gauge": {
|
||||||
|
"maxValue": 100,
|
||||||
|
"minValue": 0,
|
||||||
|
"show": false,
|
||||||
|
"thresholdLabels": false,
|
||||||
|
"thresholdMarkers": true
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 7,
|
||||||
|
"w": 12,
|
||||||
|
"x": 0,
|
||||||
|
"y": 7
|
||||||
|
},
|
||||||
|
"id": 7,
|
||||||
|
"interval": "",
|
||||||
|
"links": [],
|
||||||
|
"mappingType": 1,
|
||||||
|
"mappingTypes": [
|
||||||
|
{
|
||||||
|
"name": "value to text",
|
||||||
|
"value": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "range to text",
|
||||||
|
"value": 2
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"maxDataPoints": 100,
|
||||||
|
"nullPointMode": "connected",
|
||||||
|
"nullText": null,
|
||||||
|
"options": {},
|
||||||
|
"postfix": "",
|
||||||
|
"postfixFontSize": "50%",
|
||||||
|
"prefix": "",
|
||||||
|
"prefixFontSize": "50%",
|
||||||
|
"rangeMaps": [
|
||||||
|
{
|
||||||
|
"from": "null",
|
||||||
|
"text": "N/A",
|
||||||
|
"to": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"sparkline": {
|
||||||
|
"fillColor": "rgba(31, 118, 189, 0.18)",
|
||||||
|
"full": false,
|
||||||
|
"lineColor": "rgb(31, 120, 193)",
|
||||||
|
"show": true,
|
||||||
|
"ymax": null,
|
||||||
|
"ymin": null
|
||||||
|
},
|
||||||
|
"tableColumn": "",
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "rate(gatus_results_total{success=\"false\"}[1m])*60",
|
||||||
|
"format": "time_series",
|
||||||
|
"instant": false,
|
||||||
|
"intervalFactor": 1,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"thresholds": "1,2",
|
||||||
|
"timeFrom": null,
|
||||||
|
"timeShift": null,
|
||||||
|
"title": "Unsuccessful results",
|
||||||
|
"type": "singlestat",
|
||||||
|
"valueFontSize": "150%",
|
||||||
|
"valueMaps": [
|
||||||
|
{
|
||||||
|
"op": "=",
|
||||||
|
"text": "N/A",
|
||||||
|
"value": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"valueName": "current"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"aliasColors": {},
|
||||||
|
"bars": false,
|
||||||
|
"dashLength": 10,
|
||||||
|
"dashes": false,
|
||||||
|
"datasource": null,
|
||||||
|
"fill": 1,
|
||||||
|
"fillGradient": 0,
|
||||||
|
"gridPos": {
|
||||||
|
"h": 7,
|
||||||
|
"w": 12,
|
||||||
|
"x": 12,
|
||||||
|
"y": 7
|
||||||
|
},
|
||||||
|
"id": 3,
|
||||||
|
"legend": {
|
||||||
|
"avg": false,
|
||||||
|
"current": false,
|
||||||
|
"max": false,
|
||||||
|
"min": false,
|
||||||
|
"show": true,
|
||||||
|
"total": false,
|
||||||
|
"values": false
|
||||||
|
},
|
||||||
|
"lines": true,
|
||||||
|
"linewidth": 1,
|
||||||
|
"nullPointMode": "null",
|
||||||
|
"options": {
|
||||||
|
"dataLinks": []
|
||||||
|
},
|
||||||
|
"percentage": false,
|
||||||
|
"pointradius": 2,
|
||||||
|
"points": false,
|
||||||
|
"renderer": "flot",
|
||||||
|
"seriesOverrides": [],
|
||||||
|
"spaceLength": 10,
|
||||||
|
"stack": false,
|
||||||
|
"steppedLine": false,
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum(rate(gatus_results_total{success=\"false\"}[5m])*60) by (key)",
|
||||||
|
"interval": "30s",
|
||||||
|
"legendFormat": "{{key}} ",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"thresholds": [],
|
||||||
|
"timeFrom": null,
|
||||||
|
"timeRegions": [],
|
||||||
|
"timeShift": null,
|
||||||
|
"title": "Unsuccessful results per minute",
|
||||||
"tooltip": {
|
"tooltip": {
|
||||||
"shared": true,
|
"shared": true,
|
||||||
"sort": 0,
|
"sort": 0,
|
||||||
@@ -289,12 +388,12 @@
|
|||||||
"list": []
|
"list": []
|
||||||
},
|
},
|
||||||
"time": {
|
"time": {
|
||||||
"from": "now-30m",
|
"from": "now-1h",
|
||||||
"to": "now"
|
"to": "now"
|
||||||
},
|
},
|
||||||
"timepicker": {},
|
"timepicker": {},
|
||||||
"timezone": "",
|
"timezone": "",
|
||||||
"title": "Gatus",
|
"title": "Gatus",
|
||||||
"uid": "KPI7Qj1Wk",
|
"uid": "KPI7Qj1Wk",
|
||||||
"version": 3
|
"version": 1
|
||||||
}
|
}
|
||||||
@@ -3,14 +3,14 @@ alerting:
|
|||||||
webhook-url: "http://mattermost:8065/hooks/tokengoeshere"
|
webhook-url: "http://mattermost:8065/hooks/tokengoeshere"
|
||||||
insecure: true
|
insecure: true
|
||||||
|
|
||||||
services:
|
endpoints:
|
||||||
- name: example
|
- name: example
|
||||||
url: http://example.org
|
url: https://example.org
|
||||||
interval: 1m
|
interval: 1m
|
||||||
alerts:
|
alerts:
|
||||||
- type: mattermost
|
- type: mattermost
|
||||||
enabled: true
|
enabled: true
|
||||||
description: "healthcheck failed 3 times in a row"
|
description: "health check failed 3 times in a row"
|
||||||
send-on-resolved: true
|
send-on-resolved: true
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
storage:
|
storage:
|
||||||
type: postgres
|
type: postgres
|
||||||
file: "postgres://username:password@postgres:5432/gatus?sslmode=disable"
|
path: "postgres://username:password@postgres:5432/gatus?sslmode=disable"
|
||||||
|
|
||||||
services:
|
endpoints:
|
||||||
- name: back-end
|
- name: back-end
|
||||||
group: core
|
group: core
|
||||||
url: "https://example.org/"
|
url: "https://example.org/"
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
storage:
|
storage:
|
||||||
type: sqlite
|
type: sqlite
|
||||||
file: /data/data.db
|
path: /data/data.db
|
||||||
|
|
||||||
services:
|
endpoints:
|
||||||
- name: back-end
|
- name: back-end
|
||||||
group: core
|
group: core
|
||||||
url: "https://example.org/"
|
url: "https://example.org/"
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
services:
|
endpoints:
|
||||||
- name: example
|
- name: example
|
||||||
url: http://example.org
|
url: https://example.org
|
||||||
interval: 30s
|
interval: 30s
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
services:
|
endpoints:
|
||||||
- name: example
|
- name: example
|
||||||
url: http://example.org
|
url: https://example.org
|
||||||
interval: 30s
|
interval: 30s
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
@@ -1,18 +1,25 @@
|
|||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
|
kind: ConfigMap
|
||||||
|
metadata:
|
||||||
|
name: gatus
|
||||||
|
namespace: kube-system
|
||||||
data:
|
data:
|
||||||
config.yaml: |
|
config.yaml: |
|
||||||
metrics: true
|
metrics: true
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
interval: 1m
|
interval: 5m
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
|
- "[BODY].status == UP"
|
||||||
|
|
||||||
- name: github
|
- name: github
|
||||||
url: https://api.github.com/healthz
|
url: https://api.github.com/healthz
|
||||||
interval: 5m
|
interval: 5m
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
|
|
||||||
- name: cat-fact
|
- name: cat-fact
|
||||||
url: "https://cat-fact.herokuapp.com/facts/random"
|
url: "https://cat-fact.herokuapp.com/facts/random"
|
||||||
interval: 5m
|
interval: 5m
|
||||||
@@ -23,11 +30,14 @@ data:
|
|||||||
- "[BODY].text == pat(*cat*)"
|
- "[BODY].text == pat(*cat*)"
|
||||||
- "[STATUS] == pat(2*)"
|
- "[STATUS] == pat(2*)"
|
||||||
- "[CONNECTED] == true"
|
- "[CONNECTED] == true"
|
||||||
|
|
||||||
- name: example
|
- name: example
|
||||||
url: https://example.com/
|
url: https://example.com/
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
kind: ConfigMap
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ServiceAccount
|
||||||
metadata:
|
metadata:
|
||||||
name: gatus
|
name: gatus
|
||||||
namespace: kube-system
|
namespace: kube-system
|
||||||
@@ -41,14 +51,16 @@ spec:
|
|||||||
replicas: 1
|
replicas: 1
|
||||||
selector:
|
selector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
k8s-app: gatus
|
app: gatus
|
||||||
template:
|
template:
|
||||||
metadata:
|
metadata:
|
||||||
labels:
|
labels:
|
||||||
k8s-app: gatus
|
app: gatus
|
||||||
name: gatus
|
name: gatus
|
||||||
namespace: kube-system
|
namespace: kube-system
|
||||||
spec:
|
spec:
|
||||||
|
serviceAccountName: gatus
|
||||||
|
terminationGracePeriodSeconds: 5
|
||||||
containers:
|
containers:
|
||||||
- image: twinproduction/gatus
|
- image: twinproduction/gatus
|
||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
@@ -84,4 +96,4 @@ spec:
|
|||||||
protocol: TCP
|
protocol: TCP
|
||||||
targetPort: 8080
|
targetPort: 8080
|
||||||
selector:
|
selector:
|
||||||
k8s-app: gatus
|
app: gatus
|
||||||
|
Before Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 17 KiB |
@@ -5,3 +5,8 @@ ignore:
|
|||||||
coverage:
|
coverage:
|
||||||
status:
|
status:
|
||||||
patch: off
|
patch: off
|
||||||
|
project:
|
||||||
|
default:
|
||||||
|
target: 75%
|
||||||
|
threshold: null
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ jobs:
|
|||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
go-version: 1.16
|
go-version: 1.17
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
- name: Build binary to make sure it works
|
- name: Build binary to make sure it works
|
||||||
@@ -25,9 +25,9 @@ jobs:
|
|||||||
- name: Test
|
- name: Test
|
||||||
# We're using "sudo" because one of the tests leverages ping, which requires super-user privileges.
|
# We're using "sudo" because one of the tests leverages ping, which requires super-user privileges.
|
||||||
# As for the 'env "PATH=$PATH" "GOROOT=$GOROOT"', we need it to use the same "go" executable that
|
# As for the 'env "PATH=$PATH" "GOROOT=$GOROOT"', we need it to use the same "go" executable that
|
||||||
# was configured by the "Set up Go 1.15" step (otherwise, it'd use sudo's "go" executable)
|
# was configured by the "Set up Go" step (otherwise, it'd use sudo's "go" executable)
|
||||||
run: sudo env "PATH=$PATH" "GOROOT=$GOROOT" go test -mod vendor ./... -race -coverprofile=coverage.txt -covermode=atomic
|
run: sudo env "PATH=$PATH" "GOROOT=$GOROOT" go test -mod vendor ./... -race -coverprofile=coverage.txt -covermode=atomic
|
||||||
- name: Codecov
|
- name: Codecov
|
||||||
uses: codecov/codecov-action@v1.5.2
|
uses: codecov/codecov-action@v2.1.0
|
||||||
with:
|
with:
|
||||||
file: ./coverage.txt
|
files: ./coverage.txt
|
||||||
@@ -26,7 +26,7 @@ jobs:
|
|||||||
- name: Build and push docker image
|
- name: Build and push docker image
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v2
|
||||||
with:
|
with:
|
||||||
platforms: linux/amd64,linux/arm/v7,linux/arm64
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
pull: true
|
pull: true
|
||||||
push: true
|
push: true
|
||||||
tags: |
|
tags: |
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
.idea
|
.idea
|
||||||
.vscode
|
.vscode
|
||||||
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
gatus
|
gatus
|
||||||
db.db
|
config/config.yml
|
||||||
config/config.yml
|
|
||||||
db.db-shm
|
|
||||||
db.db-wal
|
|
||||||
memory.db
|
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2021 TwiN
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
||||||
@@ -1,15 +1,25 @@
|
|||||||
package alert
|
package alert
|
||||||
|
|
||||||
// Alert is the service's alert configuration
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrAlertWithInvalidDescription is the error with which Gatus will panic if an alert has an invalid character
|
||||||
|
ErrAlertWithInvalidDescription = errors.New("alert description must not have \" or \\")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Alert is a core.Endpoint's alert configuration
|
||||||
type Alert struct {
|
type Alert struct {
|
||||||
// Type of alert (required)
|
// Type of alert (required)
|
||||||
Type Type `yaml:"type"`
|
Type Type `yaml:"type"`
|
||||||
|
|
||||||
// Enabled defines whether or not the alert is enabled
|
// Enabled defines whether the alert is enabled
|
||||||
//
|
//
|
||||||
// This is a pointer, because it is populated by YAML and we need to know whether it was explicitly set to a value
|
// This is a pointer, because it is populated by YAML and we need to know whether it was explicitly set to a value
|
||||||
// or not for provider.ParseWithDefaultAlert to work.
|
// or not for provider.ParseWithDefaultAlert to work.
|
||||||
Enabled *bool `yaml:"enabled"`
|
Enabled *bool `yaml:"enabled,omitempty"`
|
||||||
|
|
||||||
// FailureThreshold is the number of failures in a row needed before triggering the alert
|
// FailureThreshold is the number of failures in a row needed before triggering the alert
|
||||||
FailureThreshold int `yaml:"failure-threshold"`
|
FailureThreshold int `yaml:"failure-threshold"`
|
||||||
@@ -31,7 +41,7 @@ type Alert struct {
|
|||||||
|
|
||||||
// ResolveKey is an optional field that is used by some providers (i.e. PagerDuty's dedup_key) to resolve
|
// ResolveKey is an optional field that is used by some providers (i.e. PagerDuty's dedup_key) to resolve
|
||||||
// ongoing/triggered incidents
|
// ongoing/triggered incidents
|
||||||
ResolveKey string
|
ResolveKey string `yaml:"-"`
|
||||||
|
|
||||||
// Triggered is used to determine whether an alert has been triggered. When an alert is resolved, this value
|
// Triggered is used to determine whether an alert has been triggered. When an alert is resolved, this value
|
||||||
// should be set back to false. It is used to prevent the same alert from going out twice.
|
// should be set back to false. It is used to prevent the same alert from going out twice.
|
||||||
@@ -41,7 +51,21 @@ type Alert struct {
|
|||||||
// applied for alerts that are already triggered and has become "healthy" again is to prevent a case where, for
|
// applied for alerts that are already triggered and has become "healthy" again is to prevent a case where, for
|
||||||
// some reason, the alert provider always returns errors when trying to send the resolved notification
|
// some reason, the alert provider always returns errors when trying to send the resolved notification
|
||||||
// (SendOnResolved).
|
// (SendOnResolved).
|
||||||
Triggered bool
|
Triggered bool `yaml:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAndSetDefaults validates the alert's configuration and sets the default value of fields that have one
|
||||||
|
func (alert *Alert) ValidateAndSetDefaults() error {
|
||||||
|
if alert.FailureThreshold <= 0 {
|
||||||
|
alert.FailureThreshold = 3
|
||||||
|
}
|
||||||
|
if alert.SuccessThreshold <= 0 {
|
||||||
|
alert.SuccessThreshold = 2
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(alert.GetDescription(), "\"\\") {
|
||||||
|
return ErrAlertWithInvalidDescription
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDescription retrieves the description of the alert
|
// GetDescription retrieves the description of the alert
|
||||||
|
|||||||
@@ -1,6 +1,55 @@
|
|||||||
package alert
|
package alert
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAlert_ValidateAndSetDefaults(t *testing.T) {
|
||||||
|
invalidDescription := "\""
|
||||||
|
scenarios := []struct {
|
||||||
|
name string
|
||||||
|
alert Alert
|
||||||
|
expectedError error
|
||||||
|
expectedSuccessThreshold int
|
||||||
|
expectedFailureThreshold int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid-empty",
|
||||||
|
alert: Alert{
|
||||||
|
Description: nil,
|
||||||
|
FailureThreshold: 0,
|
||||||
|
SuccessThreshold: 0,
|
||||||
|
},
|
||||||
|
expectedError: nil,
|
||||||
|
expectedFailureThreshold: 3,
|
||||||
|
expectedSuccessThreshold: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-description",
|
||||||
|
alert: Alert{
|
||||||
|
Description: &invalidDescription,
|
||||||
|
FailureThreshold: 10,
|
||||||
|
SuccessThreshold: 5,
|
||||||
|
},
|
||||||
|
expectedError: ErrAlertWithInvalidDescription,
|
||||||
|
expectedFailureThreshold: 10,
|
||||||
|
expectedSuccessThreshold: 5,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.name, func(t *testing.T) {
|
||||||
|
if err := scenario.alert.ValidateAndSetDefaults(); err != scenario.expectedError {
|
||||||
|
t.Errorf("expected error %v, got %v", scenario.expectedError, err)
|
||||||
|
}
|
||||||
|
if scenario.alert.SuccessThreshold != scenario.expectedSuccessThreshold {
|
||||||
|
t.Errorf("expected success threshold %v, got %v", scenario.expectedSuccessThreshold, scenario.alert.SuccessThreshold)
|
||||||
|
}
|
||||||
|
if scenario.alert.FailureThreshold != scenario.expectedFailureThreshold {
|
||||||
|
t.Errorf("expected failure threshold %v, got %v", scenario.expectedFailureThreshold, scenario.alert.FailureThreshold)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAlert_IsEnabled(t *testing.T) {
|
func TestAlert_IsEnabled(t *testing.T) {
|
||||||
if (Alert{Enabled: nil}).IsEnabled() {
|
if (Alert{Enabled: nil}).IsEnabled() {
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ const (
|
|||||||
// TypeDiscord is the Type for the discord alerting provider
|
// TypeDiscord is the Type for the discord alerting provider
|
||||||
TypeDiscord Type = "discord"
|
TypeDiscord Type = "discord"
|
||||||
|
|
||||||
|
// TypeEmail is the Type for the email alerting provider
|
||||||
|
TypeEmail Type = "email"
|
||||||
|
|
||||||
// TypeMattermost is the Type for the mattermost alerting provider
|
// TypeMattermost is the Type for the mattermost alerting provider
|
||||||
TypeMattermost Type = "mattermost"
|
TypeMattermost Type = "mattermost"
|
||||||
|
|
||||||
@@ -31,4 +34,7 @@ const (
|
|||||||
|
|
||||||
// TypeTwilio is the Type for the twilio alerting provider
|
// TypeTwilio is the Type for the twilio alerting provider
|
||||||
TypeTwilio Type = "twilio"
|
TypeTwilio Type = "twilio"
|
||||||
|
|
||||||
|
// TypeOpsgenie is the Type for the opsgenie alerting provider
|
||||||
|
TypeOpsgenie Type = "opsgenie"
|
||||||
)
|
)
|
||||||
@@ -5,8 +5,10 @@ import (
|
|||||||
"github.com/TwiN/gatus/v3/alerting/provider"
|
"github.com/TwiN/gatus/v3/alerting/provider"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/discord"
|
"github.com/TwiN/gatus/v3/alerting/provider/discord"
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/provider/email"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v3/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v3/alerting/provider/messagebird"
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/provider/opsgenie"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/pagerduty"
|
"github.com/TwiN/gatus/v3/alerting/provider/pagerduty"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/slack"
|
"github.com/TwiN/gatus/v3/alerting/provider/slack"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/teams"
|
"github.com/TwiN/gatus/v3/alerting/provider/teams"
|
||||||
@@ -17,31 +19,37 @@ import (
|
|||||||
// Config is the configuration for alerting providers
|
// Config is the configuration for alerting providers
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// Custom is the configuration for the custom alerting provider
|
// Custom is the configuration for the custom alerting provider
|
||||||
Custom *custom.AlertProvider `yaml:"custom"`
|
Custom *custom.AlertProvider `yaml:"custom,omitempty"`
|
||||||
|
|
||||||
// Discord is the configuration for the discord alerting provider
|
// Discord is the configuration for the discord alerting provider
|
||||||
Discord *discord.AlertProvider `yaml:"discord"`
|
Discord *discord.AlertProvider `yaml:"discord,omitempty"`
|
||||||
|
|
||||||
|
// Email is the configuration for the email alerting provider
|
||||||
|
Email *email.AlertProvider `yaml:"email,omitempty"`
|
||||||
|
|
||||||
// Mattermost is the configuration for the mattermost alerting provider
|
// Mattermost is the configuration for the mattermost alerting provider
|
||||||
Mattermost *mattermost.AlertProvider `yaml:"mattermost"`
|
Mattermost *mattermost.AlertProvider `yaml:"mattermost,omitempty"`
|
||||||
|
|
||||||
// Messagebird is the configuration for the messagebird alerting provider
|
// Messagebird is the configuration for the messagebird alerting provider
|
||||||
Messagebird *messagebird.AlertProvider `yaml:"messagebird"`
|
Messagebird *messagebird.AlertProvider `yaml:"messagebird,omitempty"`
|
||||||
|
|
||||||
// PagerDuty is the configuration for the pagerduty alerting provider
|
// PagerDuty is the configuration for the pagerduty alerting provider
|
||||||
PagerDuty *pagerduty.AlertProvider `yaml:"pagerduty"`
|
PagerDuty *pagerduty.AlertProvider `yaml:"pagerduty,omitempty"`
|
||||||
|
|
||||||
// Slack is the configuration for the slack alerting provider
|
// Slack is the configuration for the slack alerting provider
|
||||||
Slack *slack.AlertProvider `yaml:"slack"`
|
Slack *slack.AlertProvider `yaml:"slack,omitempty"`
|
||||||
|
|
||||||
// Teams is the configuration for the teams alerting provider
|
// Teams is the configuration for the teams alerting provider
|
||||||
Teams *teams.AlertProvider `yaml:"teams"`
|
Teams *teams.AlertProvider `yaml:"teams,omitempty"`
|
||||||
|
|
||||||
// Telegram is the configuration for the telegram alerting provider
|
// Telegram is the configuration for the telegram alerting provider
|
||||||
Telegram *telegram.AlertProvider `yaml:"telegram"`
|
Telegram *telegram.AlertProvider `yaml:"telegram,omitempty"`
|
||||||
|
|
||||||
// Twilio is the configuration for the twilio alerting provider
|
// Twilio is the configuration for the twilio alerting provider
|
||||||
Twilio *twilio.AlertProvider `yaml:"twilio"`
|
Twilio *twilio.AlertProvider `yaml:"twilio,omitempty"`
|
||||||
|
|
||||||
|
// Opsgenie is the configuration for the opsgenie alerting provider
|
||||||
|
Opsgenie *opsgenie.AlertProvider `yaml:"opsgenie,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAlertingProviderByAlertType returns an provider.AlertProvider by its corresponding alert.Type
|
// GetAlertingProviderByAlertType returns an provider.AlertProvider by its corresponding alert.Type
|
||||||
@@ -59,6 +67,12 @@ func (config Config) GetAlertingProviderByAlertType(alertType alert.Type) provid
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return config.Discord
|
return config.Discord
|
||||||
|
case alert.TypeEmail:
|
||||||
|
if config.Email == nil {
|
||||||
|
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return config.Email
|
||||||
case alert.TypeMattermost:
|
case alert.TypeMattermost:
|
||||||
if config.Mattermost == nil {
|
if config.Mattermost == nil {
|
||||||
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
||||||
@@ -71,6 +85,12 @@ func (config Config) GetAlertingProviderByAlertType(alertType alert.Type) provid
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return config.Messagebird
|
return config.Messagebird
|
||||||
|
case alert.TypeOpsgenie:
|
||||||
|
if config.Opsgenie == nil {
|
||||||
|
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return config.Opsgenie
|
||||||
case alert.TypePagerDuty:
|
case alert.TypePagerDuty:
|
||||||
if config.PagerDuty == nil {
|
if config.PagerDuty == nil {
|
||||||
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
||||||
|
|||||||
@@ -2,11 +2,9 @@ package custom
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
@@ -26,7 +24,7 @@ type AlertProvider struct {
|
|||||||
// ClientConfig is the configuration of the client used to communicate with the provider's target
|
// ClientConfig is the configuration of the client used to communicate with the provider's target
|
||||||
ClientConfig *client.Config `yaml:"client"`
|
ClientConfig *client.Config `yaml:"client"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,11 +36,6 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.URL) > 0 && provider.ClientConfig != nil
|
return len(provider.URL) > 0 && provider.ClientConfig != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *AlertProvider {
|
|
||||||
return provider
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAlertStatePlaceholderValue returns the Placeholder value for ALERT_TRIGGERED_OR_RESOLVED if configured
|
// GetAlertStatePlaceholderValue returns the Placeholder value for ALERT_TRIGGERED_OR_RESOLVED if configured
|
||||||
func (provider *AlertProvider) GetAlertStatePlaceholderValue(resolved bool) string {
|
func (provider *AlertProvider) GetAlertStatePlaceholderValue(resolved bool) string {
|
||||||
status := "TRIGGERED"
|
status := "TRIGGERED"
|
||||||
@@ -57,7 +50,7 @@ func (provider *AlertProvider) GetAlertStatePlaceholderValue(resolved bool) stri
|
|||||||
return status
|
return status
|
||||||
}
|
}
|
||||||
|
|
||||||
func (provider *AlertProvider) buildHTTPRequest(serviceName, alertDescription string, resolved bool) *http.Request {
|
func (provider *AlertProvider) buildHTTPRequest(endpointName, alertDescription string, resolved bool) *http.Request {
|
||||||
body := provider.Body
|
body := provider.Body
|
||||||
providerURL := provider.URL
|
providerURL := provider.URL
|
||||||
method := provider.Method
|
method := provider.Method
|
||||||
@@ -65,8 +58,11 @@ func (provider *AlertProvider) buildHTTPRequest(serviceName, alertDescription st
|
|||||||
if strings.Contains(body, "[ALERT_DESCRIPTION]") {
|
if strings.Contains(body, "[ALERT_DESCRIPTION]") {
|
||||||
body = strings.ReplaceAll(body, "[ALERT_DESCRIPTION]", alertDescription)
|
body = strings.ReplaceAll(body, "[ALERT_DESCRIPTION]", alertDescription)
|
||||||
}
|
}
|
||||||
if strings.Contains(body, "[SERVICE_NAME]") {
|
if strings.Contains(body, "[SERVICE_NAME]") { // XXX: Remove this in v4.0.0
|
||||||
body = strings.ReplaceAll(body, "[SERVICE_NAME]", serviceName)
|
body = strings.ReplaceAll(body, "[SERVICE_NAME]", endpointName)
|
||||||
|
}
|
||||||
|
if strings.Contains(body, "[ENDPOINT_NAME]") {
|
||||||
|
body = strings.ReplaceAll(body, "[ENDPOINT_NAME]", endpointName)
|
||||||
}
|
}
|
||||||
if strings.Contains(body, "[ALERT_TRIGGERED_OR_RESOLVED]") {
|
if strings.Contains(body, "[ALERT_TRIGGERED_OR_RESOLVED]") {
|
||||||
if resolved {
|
if resolved {
|
||||||
@@ -78,8 +74,11 @@ func (provider *AlertProvider) buildHTTPRequest(serviceName, alertDescription st
|
|||||||
if strings.Contains(providerURL, "[ALERT_DESCRIPTION]") {
|
if strings.Contains(providerURL, "[ALERT_DESCRIPTION]") {
|
||||||
providerURL = strings.ReplaceAll(providerURL, "[ALERT_DESCRIPTION]", alertDescription)
|
providerURL = strings.ReplaceAll(providerURL, "[ALERT_DESCRIPTION]", alertDescription)
|
||||||
}
|
}
|
||||||
if strings.Contains(providerURL, "[SERVICE_NAME]") {
|
if strings.Contains(providerURL, "[SERVICE_NAME]") { // XXX: Remove this in v4.0.0
|
||||||
providerURL = strings.ReplaceAll(providerURL, "[SERVICE_NAME]", serviceName)
|
providerURL = strings.ReplaceAll(providerURL, "[SERVICE_NAME]", endpointName)
|
||||||
|
}
|
||||||
|
if strings.Contains(providerURL, "[ENDPOINT_NAME]") {
|
||||||
|
providerURL = strings.ReplaceAll(providerURL, "[ENDPOINT_NAME]", endpointName)
|
||||||
}
|
}
|
||||||
if strings.Contains(providerURL, "[ALERT_TRIGGERED_OR_RESOLVED]") {
|
if strings.Contains(providerURL, "[ALERT_TRIGGERED_OR_RESOLVED]") {
|
||||||
if resolved {
|
if resolved {
|
||||||
@@ -99,27 +98,17 @@ func (provider *AlertProvider) buildHTTPRequest(serviceName, alertDescription st
|
|||||||
return request
|
return request
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send a request to the alert provider and return the body
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
func (provider *AlertProvider) Send(serviceName, alertDescription string, resolved bool) ([]byte, error) {
|
request := provider.buildHTTPRequest(endpoint.Name, alert.GetDescription(), resolved)
|
||||||
if os.Getenv("MOCK_ALERT_PROVIDER") == "true" {
|
|
||||||
if os.Getenv("MOCK_ALERT_PROVIDER_ERROR") == "true" {
|
|
||||||
return nil, errors.New("error")
|
|
||||||
}
|
|
||||||
return []byte("{}"), nil
|
|
||||||
}
|
|
||||||
request := provider.buildHTTPRequest(serviceName, alertDescription, resolved)
|
|
||||||
response, err := client.GetHTTPClient(provider.ClientConfig).Do(request)
|
response, err := client.GetHTTPClient(provider.ClientConfig).Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return err
|
||||||
}
|
}
|
||||||
if response.StatusCode > 399 {
|
if response.StatusCode > 399 {
|
||||||
body, err := ioutil.ReadAll(response.Body)
|
body, _ := io.ReadAll(response.Body)
|
||||||
if err != nil {
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
return nil, fmt.Errorf("call to provider alert returned status code %d", response.StatusCode)
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
|
||||||
}
|
}
|
||||||
return ioutil.ReadAll(response.Body)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
package custom
|
package custom
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
"io"
|
||||||
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -13,27 +16,104 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
if invalidProvider.IsValid() {
|
if invalidProvider.IsValid() {
|
||||||
t.Error("provider shouldn't have been valid")
|
t.Error("provider shouldn't have been valid")
|
||||||
}
|
}
|
||||||
validProvider := AlertProvider{URL: "http://example.com"}
|
validProvider := AlertProvider{URL: "https://example.com"}
|
||||||
if !validProvider.IsValid() {
|
if !validProvider.IsValid() {
|
||||||
t.Error("provider should've been valid")
|
t.Error("provider should've been valid")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
|
defer client.InjectHTTPClient(nil)
|
||||||
|
firstDescription := "description-1"
|
||||||
|
secondDescription := "description-2"
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
|
err := scenario.Provider.Send(
|
||||||
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
|
&scenario.Alert,
|
||||||
|
&core.Result{
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scenario.Resolved,
|
||||||
|
)
|
||||||
|
if scenario.ExpectedError && err == nil {
|
||||||
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAlertProvider_buildHTTPRequestWhenResolved(t *testing.T) {
|
func TestAlertProvider_buildHTTPRequestWhenResolved(t *testing.T) {
|
||||||
const (
|
const (
|
||||||
ExpectedURL = "http://example.com/service-name?event=RESOLVED&description=alert-description"
|
ExpectedURL = "https://example.com/endpoint-name?event=RESOLVED&description=alert-description"
|
||||||
ExpectedBody = "service-name,alert-description,RESOLVED"
|
ExpectedBody = "endpoint-name,alert-description,RESOLVED"
|
||||||
)
|
)
|
||||||
customAlertProvider := &AlertProvider{
|
customAlertProvider := &AlertProvider{
|
||||||
URL: "http://example.com/[SERVICE_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
URL: "https://example.com/[ENDPOINT_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
||||||
Body: "[SERVICE_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
Body: "[ENDPOINT_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
||||||
Headers: nil,
|
Headers: nil,
|
||||||
}
|
}
|
||||||
request := customAlertProvider.buildHTTPRequest("service-name", "alert-description", true)
|
request := customAlertProvider.buildHTTPRequest("endpoint-name", "alert-description", true)
|
||||||
if request.URL.String() != ExpectedURL {
|
if request.URL.String() != ExpectedURL {
|
||||||
t.Error("expected URL to be", ExpectedURL, "was", request.URL.String())
|
t.Error("expected URL to be", ExpectedURL, "was", request.URL.String())
|
||||||
}
|
}
|
||||||
body, _ := ioutil.ReadAll(request.Body)
|
body, _ := io.ReadAll(request.Body)
|
||||||
if string(body) != ExpectedBody {
|
if string(body) != ExpectedBody {
|
||||||
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
||||||
}
|
}
|
||||||
@@ -41,43 +121,32 @@ func TestAlertProvider_buildHTTPRequestWhenResolved(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_buildHTTPRequestWhenTriggered(t *testing.T) {
|
func TestAlertProvider_buildHTTPRequestWhenTriggered(t *testing.T) {
|
||||||
const (
|
const (
|
||||||
ExpectedURL = "http://example.com/service-name?event=TRIGGERED&description=alert-description"
|
ExpectedURL = "https://example.com/endpoint-name?event=TRIGGERED&description=alert-description"
|
||||||
ExpectedBody = "service-name,alert-description,TRIGGERED"
|
ExpectedBody = "endpoint-name,alert-description,TRIGGERED"
|
||||||
)
|
)
|
||||||
customAlertProvider := &AlertProvider{
|
customAlertProvider := &AlertProvider{
|
||||||
URL: "http://example.com/[SERVICE_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
URL: "https://example.com/[ENDPOINT_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
||||||
Body: "[SERVICE_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
Body: "[ENDPOINT_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
||||||
Headers: map[string]string{"Authorization": "Basic hunter2"},
|
Headers: map[string]string{"Authorization": "Basic hunter2"},
|
||||||
}
|
}
|
||||||
request := customAlertProvider.buildHTTPRequest("service-name", "alert-description", false)
|
request := customAlertProvider.buildHTTPRequest("endpoint-name", "alert-description", false)
|
||||||
if request.URL.String() != ExpectedURL {
|
if request.URL.String() != ExpectedURL {
|
||||||
t.Error("expected URL to be", ExpectedURL, "was", request.URL.String())
|
t.Error("expected URL to be", ExpectedURL, "was", request.URL.String())
|
||||||
}
|
}
|
||||||
body, _ := ioutil.ReadAll(request.Body)
|
body, _ := io.ReadAll(request.Body)
|
||||||
if string(body) != ExpectedBody {
|
if string(body) != ExpectedBody {
|
||||||
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProvider(t *testing.T) {
|
|
||||||
provider := AlertProvider{URL: "http://example.com"}
|
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, true)
|
|
||||||
if customAlertProvider == nil {
|
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
|
||||||
}
|
|
||||||
if customAlertProvider.URL != "http://example.com" {
|
|
||||||
t.Error("expected URL to be http://example.com, got", customAlertProvider.URL)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAlertProvider_buildHTTPRequestWithCustomPlaceholder(t *testing.T) {
|
func TestAlertProvider_buildHTTPRequestWithCustomPlaceholder(t *testing.T) {
|
||||||
const (
|
const (
|
||||||
ExpectedURL = "http://example.com/service-name?event=test&description=alert-description"
|
ExpectedURL = "https://example.com/endpoint-name?event=test&description=alert-description"
|
||||||
ExpectedBody = "service-name,alert-description,test"
|
ExpectedBody = "endpoint-name,alert-description,test"
|
||||||
)
|
)
|
||||||
customAlertProvider := &AlertProvider{
|
customAlertProvider := &AlertProvider{
|
||||||
URL: "http://example.com/[SERVICE_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
URL: "https://example.com/[ENDPOINT_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
||||||
Body: "[SERVICE_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
Body: "[ENDPOINT_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
||||||
Headers: nil,
|
Headers: nil,
|
||||||
Placeholders: map[string]map[string]string{
|
Placeholders: map[string]map[string]string{
|
||||||
"ALERT_TRIGGERED_OR_RESOLVED": {
|
"ALERT_TRIGGERED_OR_RESOLVED": {
|
||||||
@@ -85,11 +154,11 @@ func TestAlertProvider_buildHTTPRequestWithCustomPlaceholder(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
request := customAlertProvider.buildHTTPRequest("service-name", "alert-description", true)
|
request := customAlertProvider.buildHTTPRequest("endpoint-name", "alert-description", true)
|
||||||
if request.URL.String() != ExpectedURL {
|
if request.URL.String() != ExpectedURL {
|
||||||
t.Error("expected URL to be", ExpectedURL, "was", request.URL.String())
|
t.Error("expected URL to be", ExpectedURL, "was", request.URL.String())
|
||||||
}
|
}
|
||||||
body, _ := ioutil.ReadAll(request.Body)
|
body, _ := io.ReadAll(request.Body)
|
||||||
if string(body) != ExpectedBody {
|
if string(body) != ExpectedBody {
|
||||||
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
||||||
}
|
}
|
||||||
@@ -97,8 +166,8 @@ func TestAlertProvider_buildHTTPRequestWithCustomPlaceholder(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_GetAlertStatePlaceholderValueDefaults(t *testing.T) {
|
func TestAlertProvider_GetAlertStatePlaceholderValueDefaults(t *testing.T) {
|
||||||
customAlertProvider := &AlertProvider{
|
customAlertProvider := &AlertProvider{
|
||||||
URL: "http://example.com/[SERVICE_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
URL: "https://example.com/[ENDPOINT_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
||||||
Body: "[SERVICE_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
Body: "[ENDPOINT_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
||||||
Headers: nil,
|
Headers: nil,
|
||||||
Placeholders: nil,
|
Placeholders: nil,
|
||||||
}
|
}
|
||||||
@@ -109,3 +178,35 @@ func TestAlertProvider_GetAlertStatePlaceholderValueDefaults(t *testing.T) {
|
|||||||
t.Error("expected TRIGGERED, got", customAlertProvider.GetAlertStatePlaceholderValue(false))
|
t.Error("expected TRIGGERED, got", customAlertProvider.GetAlertStatePlaceholderValue(false))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAlertProvider_isBackwardCompatibleWithServiceRename checks if the custom alerting provider still supports
|
||||||
|
// service placeholders after the migration from "service" to "endpoint"
|
||||||
|
//
|
||||||
|
// XXX: Remove this in v4.0.0
|
||||||
|
func TestAlertProvider_isBackwardCompatibleWithServiceRename(t *testing.T) {
|
||||||
|
const (
|
||||||
|
ExpectedURL = "https://example.com/endpoint-name?event=TRIGGERED&description=alert-description"
|
||||||
|
ExpectedBody = "endpoint-name,alert-description,TRIGGERED"
|
||||||
|
)
|
||||||
|
customAlertProvider := &AlertProvider{
|
||||||
|
URL: "https://example.com/[SERVICE_NAME]?event=[ALERT_TRIGGERED_OR_RESOLVED]&description=[ALERT_DESCRIPTION]",
|
||||||
|
Body: "[SERVICE_NAME],[ALERT_DESCRIPTION],[ALERT_TRIGGERED_OR_RESOLVED]",
|
||||||
|
}
|
||||||
|
request := customAlertProvider.buildHTTPRequest("endpoint-name", "alert-description", false)
|
||||||
|
if request.URL.String() != ExpectedURL {
|
||||||
|
t.Error("expected URL to be", ExpectedURL, "was", request.URL.String())
|
||||||
|
}
|
||||||
|
body, _ := io.ReadAll(request.Body)
|
||||||
|
if string(body) != ExpectedBody {
|
||||||
|
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
package discord
|
package discord
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,7 +15,7 @@ import (
|
|||||||
type AlertProvider struct {
|
type AlertProvider struct {
|
||||||
WebhookURL string `yaml:"webhook-url"`
|
WebhookURL string `yaml:"webhook-url"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,15 +24,34 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.WebhookURL) > 0
|
return len(provider.WebhookURL) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
|
request, err := http.NewRequest(http.MethodPost, provider.WebhookURL, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message, results string
|
var message, results string
|
||||||
var colorCode int
|
var colorCode int
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("An alert for **%s** has been resolved after passing successfully %d time(s) in a row", service.Name, alert.SuccessThreshold)
|
message = fmt.Sprintf("An alert for **%s** has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
colorCode = 3066993
|
colorCode = 3066993
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("An alert for **%s** has been triggered due to having failed %d time(s) in a row", service.Name, alert.FailureThreshold)
|
message = fmt.Sprintf("An alert for **%s** has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
colorCode = 15158332
|
colorCode = 15158332
|
||||||
}
|
}
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
@@ -46,10 +67,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
description = ":\\n> " + alertDescription
|
description = ":\\n> " + alertDescription
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return fmt.Sprintf(`{
|
||||||
URL: provider.WebhookURL,
|
|
||||||
Method: http.MethodPost,
|
|
||||||
Body: fmt.Sprintf(`{
|
|
||||||
"content": "",
|
"content": "",
|
||||||
"embeds": [
|
"embeds": [
|
||||||
{
|
{
|
||||||
@@ -65,9 +83,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}`, message, description, colorCode, results),
|
}`, message, description, colorCode, results)
|
||||||
Headers: map[string]string{"Content-Type": "application/json"},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ package discord
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -21,50 +22,137 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
defer client.InjectHTTPClient(nil)
|
||||||
alertDescription := "test"
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "resolved") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring resolved")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
if customAlertProvider.URL != "http://example.com" {
|
err := scenario.Provider.Send(
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.com", customAlertProvider.URL)
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
}
|
&scenario.Alert,
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
&core.Result{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
ConditionResults: []*core.ConditionResult{
|
||||||
}
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
},
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
scenario.Resolved,
|
||||||
}
|
)
|
||||||
if expected := "An alert for **svc** has been resolved after passing successfully 0 time(s) in a row:\n> test"; expected != body["embeds"].([]interface{})[0].(map[string]interface{})["description"] {
|
if scenario.ExpectedError && err == nil {
|
||||||
t.Errorf("expected $.embeds[0].description to be %s, got %s", expected, body["embeds"].([]interface{})[0].(map[string]interface{})["description"])
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\n \"content\": \"\",\n \"embeds\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"description\": \"An alert for **endpoint-name** has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"color\": 15158332,\n \"fields\": [\n {\n \"name\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"inline\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n \"content\": \"\",\n \"embeds\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"description\": \"An alert for **endpoint-name** has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"color\": 3066993,\n \"fields\": [\n {\n \"name\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"inline\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "triggered") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring triggered")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
body := scenario.Provider.buildRequestBody(
|
||||||
if customAlertProvider.URL != "http://example.com" {
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.com", customAlertProvider.URL)
|
&scenario.Alert,
|
||||||
}
|
&core.Result{
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
ConditionResults: []*core.ConditionResult{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
}
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
scenario.Resolved,
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
)
|
||||||
|
if body != scenario.ExpectedBody {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
|
}
|
||||||
|
out := make(map[string]interface{})
|
||||||
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package email
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
gomail "gopkg.in/mail.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AlertProvider is the configuration necessary for sending an alert using SMTP
|
||||||
|
type AlertProvider struct {
|
||||||
|
From string `yaml:"from"`
|
||||||
|
Password string `yaml:"password"`
|
||||||
|
Host string `yaml:"host"`
|
||||||
|
Port int `yaml:"port"`
|
||||||
|
To string `yaml:"to"`
|
||||||
|
|
||||||
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
|
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsValid returns whether the provider's configuration is valid
|
||||||
|
func (provider *AlertProvider) IsValid() bool {
|
||||||
|
return len(provider.From) > 0 && len(provider.Password) > 0 && len(provider.Host) > 0 && len(provider.To) > 0 && provider.Port > 0 && provider.Port < math.MaxUint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send an alert using the provider
|
||||||
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
subject, body := provider.buildMessageSubjectAndBody(endpoint, alert, result, resolved)
|
||||||
|
m := gomail.NewMessage()
|
||||||
|
m.SetHeader("From", provider.From)
|
||||||
|
m.SetHeader("To", strings.Split(provider.To, ",")...)
|
||||||
|
m.SetHeader("Subject", subject)
|
||||||
|
m.SetBody("text/plain", body)
|
||||||
|
d := gomail.NewDialer(provider.Host, provider.Port, provider.From, provider.Password)
|
||||||
|
return d.DialAndSend(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildMessageSubjectAndBody builds the message subject and body
|
||||||
|
func (provider *AlertProvider) buildMessageSubjectAndBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) (string, string) {
|
||||||
|
var subject, message, results string
|
||||||
|
if resolved {
|
||||||
|
subject = fmt.Sprintf("[%s] Alert resolved", endpoint.DisplayName())
|
||||||
|
message = fmt.Sprintf("An alert for %s has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
|
} else {
|
||||||
|
subject = fmt.Sprintf("[%s] Alert triggered", endpoint.DisplayName())
|
||||||
|
message = fmt.Sprintf("An alert for %s has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
|
}
|
||||||
|
for _, conditionResult := range result.ConditionResults {
|
||||||
|
var prefix string
|
||||||
|
if conditionResult.Success {
|
||||||
|
prefix = "✅"
|
||||||
|
} else {
|
||||||
|
prefix = "❌"
|
||||||
|
}
|
||||||
|
results += fmt.Sprintf("%s %s\n", prefix, conditionResult.Condition)
|
||||||
|
}
|
||||||
|
var description string
|
||||||
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
|
description = "\n\nAlert description: " + alertDescription
|
||||||
|
}
|
||||||
|
return subject, message + description + "\n\nCondition results:\n" + results
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
|
||||||
|
return provider.DefaultAlert
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package email
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
|
invalidProvider := AlertProvider{}
|
||||||
|
if invalidProvider.IsValid() {
|
||||||
|
t.Error("provider shouldn't have been valid")
|
||||||
|
}
|
||||||
|
validProvider := AlertProvider{From: "from@example.com", Password: "password", Host: "smtp.gmail.com", Port: 587, To: "to@example.com"}
|
||||||
|
if !validProvider.IsValid() {
|
||||||
|
t.Error("provider should've been valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
|
firstDescription := "description-1"
|
||||||
|
secondDescription := "description-2"
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedSubject string
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedSubject: "[endpoint-name] Alert triggered",
|
||||||
|
ExpectedBody: "An alert for endpoint-name has been triggered due to having failed 3 time(s) in a row\n\nAlert description: description-1\n\nCondition results:\n❌ [CONNECTED] == true\n❌ [STATUS] == 200\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedSubject: "[endpoint-name] Alert resolved",
|
||||||
|
ExpectedBody: "An alert for endpoint-name has been resolved after passing successfully 5 time(s) in a row\n\nAlert description: description-2\n\nCondition results:\n✅ [CONNECTED] == true\n✅ [STATUS] == 200\n",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
subject, body := scenario.Provider.buildMessageSubjectAndBody(
|
||||||
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
|
&scenario.Alert,
|
||||||
|
&core.Result{
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scenario.Resolved,
|
||||||
|
)
|
||||||
|
if subject != scenario.ExpectedSubject {
|
||||||
|
t.Errorf("expected subject to be %s, got %s", scenario.ExpectedSubject, subject)
|
||||||
|
}
|
||||||
|
if body != scenario.ExpectedBody {
|
||||||
|
t.Errorf("expected body to be %s, got %s", scenario.ExpectedBody, body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
package mattermost
|
package mattermost
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
|
||||||
"github.com/TwiN/gatus/v3/client"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
@@ -17,7 +18,7 @@ type AlertProvider struct {
|
|||||||
// ClientConfig is the configuration of the client used to communicate with the provider's target
|
// ClientConfig is the configuration of the client used to communicate with the provider's target
|
||||||
ClientConfig *client.Config `yaml:"client"`
|
ClientConfig *client.Config `yaml:"client"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,15 +30,33 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.WebhookURL) > 0
|
return len(provider.WebhookURL) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
var message string
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
var color string
|
request, err := http.NewRequest(http.MethodPost, provider.WebhookURL, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.GetHTTPClient(provider.ClientConfig).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
|
var message, color string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", service.Name, alert.SuccessThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
color = "#36A64F"
|
color = "#36A64F"
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", service.Name, alert.FailureThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
color = "#DD0000"
|
color = "#DD0000"
|
||||||
}
|
}
|
||||||
var results string
|
var results string
|
||||||
@@ -54,14 +73,10 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
description = ":\\n> " + alertDescription
|
description = ":\\n> " + alertDescription
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return fmt.Sprintf(`{
|
||||||
URL: provider.WebhookURL,
|
|
||||||
Method: http.MethodPost,
|
|
||||||
ClientConfig: provider.ClientConfig,
|
|
||||||
Body: fmt.Sprintf(`{
|
|
||||||
"text": "",
|
"text": "",
|
||||||
"username": "gatus",
|
"username": "gatus",
|
||||||
"icon_url": "https://raw.githubusercontent.com/TwiN/gatus/master/static/logo.png",
|
"icon_url": "https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png",
|
||||||
"attachments": [
|
"attachments": [
|
||||||
{
|
{
|
||||||
"title": ":rescue_worker_helmet: Gatus",
|
"title": ":rescue_worker_helmet: Gatus",
|
||||||
@@ -83,9 +98,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}`, message, message, description, color, service.URL, results),
|
}`, message, message, description, color, endpoint.URL, results)
|
||||||
Headers: map[string]string{"Content-Type": "application/json"},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ package mattermost
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -21,50 +22,137 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
defer client.InjectHTTPClient(nil)
|
||||||
alertDescription := "test"
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "resolved") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring resolved")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
if customAlertProvider.URL != "http://example.org" {
|
err := scenario.Provider.Send(
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.org", customAlertProvider.URL)
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
}
|
&scenario.Alert,
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
&core.Result{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
ConditionResults: []*core.ConditionResult{
|
||||||
}
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
},
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
scenario.Resolved,
|
||||||
}
|
)
|
||||||
if expected := "An alert for *svc* has been resolved after passing successfully 0 time(s) in a row:\n> test"; expected != body["attachments"].([]interface{})[0].(map[string]interface{})["text"] {
|
if scenario.ExpectedError && err == nil {
|
||||||
t.Errorf("expected $.attachments[0].description to be %s, got %s", expected, body["attachments"].([]interface{})[0].(map[string]interface{})["text"])
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\n \"text\": \"\",\n \"username\": \"gatus\",\n \"icon_url\": \"https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png\",\n \"attachments\": [\n {\n \"title\": \":rescue_worker_helmet: Gatus\",\n \"fallback\": \"Gatus - An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row\",\n \"text\": \"An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"short\": false,\n \"color\": \"#DD0000\",\n \"fields\": [\n {\n \"title\": \"URL\",\n \"value\": \"\",\n \"short\": false\n },\n {\n \"title\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n \"text\": \"\",\n \"username\": \"gatus\",\n \"icon_url\": \"https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png\",\n \"attachments\": [\n {\n \"title\": \":rescue_worker_helmet: Gatus\",\n \"fallback\": \"Gatus - An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row\",\n \"text\": \"An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"short\": false,\n \"color\": \"#36A64F\",\n \"fields\": [\n {\n \"title\": \"URL\",\n \"value\": \"\",\n \"short\": false\n },\n {\n \"title\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "triggered") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring triggered")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
body := scenario.Provider.buildRequestBody(
|
||||||
if customAlertProvider.URL != "http://example.org" {
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.org", customAlertProvider.URL)
|
&scenario.Alert,
|
||||||
}
|
&core.Result{
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
ConditionResults: []*core.ConditionResult{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
}
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
scenario.Resolved,
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
)
|
||||||
|
if body != scenario.ExpectedBody {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
|
}
|
||||||
|
out := make(map[string]interface{})
|
||||||
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
package messagebird
|
package messagebird
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -19,8 +21,8 @@ type AlertProvider struct {
|
|||||||
Originator string `yaml:"originator"`
|
Originator string `yaml:"originator"`
|
||||||
Recipients string `yaml:"recipients"`
|
Recipients string `yaml:"recipients"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsValid returns whether the provider's configuration is valid
|
// IsValid returns whether the provider's configuration is valid
|
||||||
@@ -28,28 +30,40 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.AccessKey) > 0 && len(provider.Originator) > 0 && len(provider.Recipients) > 0
|
return len(provider.AccessKey) > 0 && len(provider.Originator) > 0 && len(provider.Recipients) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
// Reference doc for messagebird https://developers.messagebird.com/api/sms-messaging/#send-outbound-sms
|
// Reference doc for messagebird: https://developers.messagebird.com/api/sms-messaging/#send-outbound-sms
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, _ *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
|
request, err := http.NewRequest(http.MethodPost, restAPIURL, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.Header.Set("Authorization", fmt.Sprintf("AccessKey %s", provider.AccessKey))
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message string
|
var message string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("RESOLVED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("TRIGGERED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("TRIGGERED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return fmt.Sprintf(`{
|
||||||
URL: restAPIURL,
|
|
||||||
Method: http.MethodPost,
|
|
||||||
Body: fmt.Sprintf(`{
|
|
||||||
"originator": "%s",
|
"originator": "%s",
|
||||||
"recipients": "%s",
|
"recipients": "%s",
|
||||||
"body": "%s"
|
"body": "%s"
|
||||||
}`, provider.Originator, provider.Recipients, message),
|
}`, provider.Originator, provider.Recipients, message)
|
||||||
Headers: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"Authorization": fmt.Sprintf("AccessKey %s", provider.AccessKey),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ package messagebird
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMessagebirdAlertProvider_IsValid(t *testing.T) {
|
func TestMessagebirdAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -25,54 +26,137 @@ func TestMessagebirdAlertProvider_IsValid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
provider := AlertProvider{
|
defer client.InjectHTTPClient(nil)
|
||||||
AccessKey: "1",
|
firstDescription := "description-1"
|
||||||
Originator: "1",
|
secondDescription := "description-2"
|
||||||
Recipients: "1",
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, true)
|
for _, scenario := range scenarios {
|
||||||
if customAlertProvider == nil {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
}
|
err := scenario.Provider.Send(
|
||||||
if !strings.Contains(customAlertProvider.Body, "RESOLVED") {
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
t.Error("customAlertProvider.Body should've contained the substring RESOLVED")
|
&scenario.Alert,
|
||||||
}
|
&core.Result{
|
||||||
if customAlertProvider.URL != "https://rest.messagebird.com/messages" {
|
ConditionResults: []*core.ConditionResult{
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://rest.messagebird.com/messages", customAlertProvider.URL)
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
}
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
},
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
},
|
||||||
}
|
scenario.Resolved,
|
||||||
body := make(map[string]interface{})
|
)
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
if scenario.ExpectedError && err == nil {
|
||||||
if err != nil {
|
t.Error("expected error, got none")
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{
|
firstDescription := "description-1"
|
||||||
AccessKey: "1",
|
secondDescription := "description-2"
|
||||||
Originator: "1",
|
scenarios := []struct {
|
||||||
Recipients: "1",
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{AccessKey: "1", Originator: "2", Recipients: "3"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\n \"originator\": \"2\",\n \"recipients\": \"3\",\n \"body\": \"TRIGGERED: endpoint-name - description-1\"\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{AccessKey: "4", Originator: "5", Recipients: "6"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n \"originator\": \"5\",\n \"recipients\": \"6\",\n \"body\": \"RESOLVED: endpoint-name - description-2\"\n}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, false)
|
for _, scenario := range scenarios {
|
||||||
if customAlertProvider == nil {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
body := scenario.Provider.buildRequestBody(
|
||||||
}
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
if !strings.Contains(customAlertProvider.Body, "TRIGGERED") {
|
&scenario.Alert,
|
||||||
t.Error("customAlertProvider.Body should've contained the substring TRIGGERED")
|
&core.Result{
|
||||||
}
|
ConditionResults: []*core.ConditionResult{
|
||||||
if customAlertProvider.URL != "https://rest.messagebird.com/messages" {
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://rest.messagebird.com/messages", customAlertProvider.URL)
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
}
|
},
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
},
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
scenario.Resolved,
|
||||||
}
|
)
|
||||||
body := make(map[string]interface{})
|
if body != scenario.ExpectedBody {
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
if err != nil {
|
}
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
out := make(map[string]interface{})
|
||||||
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
package opsgenie
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
restAPI = "https://api.opsgenie.com/v2/alerts"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AlertProvider struct {
|
||||||
|
// APIKey to use for
|
||||||
|
APIKey string `yaml:"api-key"`
|
||||||
|
|
||||||
|
// Priority to be used in Opsgenie alert payload
|
||||||
|
//
|
||||||
|
// default: P1
|
||||||
|
Priority string `yaml:"priority"`
|
||||||
|
|
||||||
|
// Source define source to be used in Opsgenie alert payload
|
||||||
|
//
|
||||||
|
// default: gatus
|
||||||
|
Source string `yaml:"source"`
|
||||||
|
|
||||||
|
// EntityPrefix is a prefix to be used in entity argument in Opsgenie alert payload
|
||||||
|
//
|
||||||
|
// default: gatus-
|
||||||
|
EntityPrefix string `yaml:"entity-prefix"`
|
||||||
|
|
||||||
|
//AliasPrefix is a prefix to be used in alias argument in Opsgenie alert payload
|
||||||
|
//
|
||||||
|
// default: gatus-healthcheck-
|
||||||
|
AliasPrefix string `yaml:"alias-prefix"`
|
||||||
|
|
||||||
|
// Tags to be used in Opsgenie alert payload
|
||||||
|
//
|
||||||
|
// default: []
|
||||||
|
Tags []string `yaml:"tags"`
|
||||||
|
|
||||||
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
|
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsValid returns whether the provider's configuration is valid
|
||||||
|
func (provider *AlertProvider) IsValid() bool {
|
||||||
|
return len(provider.APIKey) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send an alert using the provider
|
||||||
|
//
|
||||||
|
// Relevant: https://docs.opsgenie.com/docs/alert-api
|
||||||
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
err := provider.createAlert(endpoint, alert, result, resolved)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if resolved {
|
||||||
|
err = provider.closeAlert(endpoint, alert)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if alert.IsSendingOnResolved() {
|
||||||
|
if resolved {
|
||||||
|
// The alert has been resolved and there's no error, so we can clear the alert's ResolveKey
|
||||||
|
alert.ResolveKey = ""
|
||||||
|
} else {
|
||||||
|
alert.ResolveKey = provider.alias(buildKey(endpoint))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) createAlert(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
payload := provider.buildCreateRequestBody(endpoint, alert, result, resolved)
|
||||||
|
_, err := provider.sendRequest(restAPI, http.MethodPost, payload)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) closeAlert(endpoint *core.Endpoint, alert *alert.Alert) error {
|
||||||
|
payload := provider.buildCloseRequestBody(endpoint, alert)
|
||||||
|
url := restAPI + "/" + provider.alias(buildKey(endpoint)) + "/close?identifierType=alias"
|
||||||
|
_, err := provider.sendRequest(url, http.MethodPost, payload)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) sendRequest(url, method string, payload interface{}) (*http.Response, error) {
|
||||||
|
body, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fail to build alert payload: %v", payload)
|
||||||
|
}
|
||||||
|
request, err := http.NewRequest(method, url, bytes.NewBuffer(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.Header.Set("Authorization", "GenieKey "+provider.APIKey)
|
||||||
|
res, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if res.StatusCode > 399 {
|
||||||
|
rBody, _ := io.ReadAll(res.Body)
|
||||||
|
return nil, fmt.Errorf("call to provider alert returned status code %d: %s", res.StatusCode, string(rBody))
|
||||||
|
}
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) alertCreateRequest {
|
||||||
|
var message, description, results string
|
||||||
|
if resolved {
|
||||||
|
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription())
|
||||||
|
description = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
|
} else {
|
||||||
|
message = fmt.Sprintf("%s - %s", endpoint.Name, alert.GetDescription())
|
||||||
|
description = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
|
}
|
||||||
|
if endpoint.Group != "" {
|
||||||
|
message = fmt.Sprintf("[%s] %s", endpoint.Group, message)
|
||||||
|
}
|
||||||
|
for _, conditionResult := range result.ConditionResults {
|
||||||
|
var prefix string
|
||||||
|
if conditionResult.Success {
|
||||||
|
prefix = "▣"
|
||||||
|
} else {
|
||||||
|
prefix = "▢"
|
||||||
|
}
|
||||||
|
results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
|
||||||
|
}
|
||||||
|
description = description + "\n" + results
|
||||||
|
key := buildKey(endpoint)
|
||||||
|
details := map[string]string{
|
||||||
|
"endpoint:url": endpoint.URL,
|
||||||
|
"endpoint:group": endpoint.Group,
|
||||||
|
"result:hostname": result.Hostname,
|
||||||
|
"result:ip": result.IP,
|
||||||
|
"result:dns_code": result.DNSRCode,
|
||||||
|
"result:errors": strings.Join(result.Errors, ","),
|
||||||
|
}
|
||||||
|
for k, v := range details {
|
||||||
|
if v == "" {
|
||||||
|
delete(details, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if result.HTTPStatus > 0 {
|
||||||
|
details["result:http_status"] = strconv.Itoa(result.HTTPStatus)
|
||||||
|
}
|
||||||
|
return alertCreateRequest{
|
||||||
|
Message: message,
|
||||||
|
Description: description,
|
||||||
|
Source: provider.source(),
|
||||||
|
Priority: provider.priority(),
|
||||||
|
Alias: provider.alias(key),
|
||||||
|
Entity: provider.entity(key),
|
||||||
|
Tags: provider.Tags,
|
||||||
|
Details: details,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) buildCloseRequestBody(endpoint *core.Endpoint, alert *alert.Alert) alertCloseRequest {
|
||||||
|
return alertCloseRequest{
|
||||||
|
Source: buildKey(endpoint),
|
||||||
|
Note: fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) source() string {
|
||||||
|
source := provider.Source
|
||||||
|
if source == "" {
|
||||||
|
return "gatus"
|
||||||
|
}
|
||||||
|
return source
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) alias(key string) string {
|
||||||
|
alias := provider.AliasPrefix
|
||||||
|
if alias == "" {
|
||||||
|
alias = "gatus-healthcheck-"
|
||||||
|
}
|
||||||
|
return alias + key
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) entity(key string) string {
|
||||||
|
alias := provider.EntityPrefix
|
||||||
|
if alias == "" {
|
||||||
|
alias = "gatus-"
|
||||||
|
}
|
||||||
|
return alias + key
|
||||||
|
}
|
||||||
|
|
||||||
|
func (provider *AlertProvider) priority() string {
|
||||||
|
priority := provider.Priority
|
||||||
|
if priority == "" {
|
||||||
|
return "P1"
|
||||||
|
}
|
||||||
|
return priority
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
|
||||||
|
return provider.DefaultAlert
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildKey(endpoint *core.Endpoint) string {
|
||||||
|
name := toKebabCase(endpoint.Name)
|
||||||
|
if endpoint.Group == "" {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
return toKebabCase(endpoint.Group) + "-" + name
|
||||||
|
}
|
||||||
|
|
||||||
|
func toKebabCase(val string) string {
|
||||||
|
return strings.ToLower(strings.ReplaceAll(val, " ", "-"))
|
||||||
|
}
|
||||||
|
|
||||||
|
type alertCreateRequest struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Priority string `json:"priority"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
Entity string `json:"entity"`
|
||||||
|
Alias string `json:"alias"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Tags []string `json:"tags,omitempty"`
|
||||||
|
Details map[string]string `json:"details"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type alertCloseRequest struct {
|
||||||
|
Source string `json:"source"`
|
||||||
|
Note string `json:"note"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
package opsgenie
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
|
invalidProvider := AlertProvider{APIKey: ""}
|
||||||
|
if invalidProvider.IsValid() {
|
||||||
|
t.Error("provider shouldn't have been valid")
|
||||||
|
}
|
||||||
|
validProvider := AlertProvider{APIKey: "00000000-0000-0000-0000-000000000000"}
|
||||||
|
if !validProvider.IsValid() {
|
||||||
|
t.Error("provider should've been valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
|
defer client.InjectHTTPClient(nil)
|
||||||
|
description := "my bad alert description"
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &description, SuccessThreshold: 1, FailureThreshold: 1},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedError: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &description, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedError: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &description, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedError: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &description, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedError: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
|
err := scenario.Provider.Send(
|
||||||
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
|
&scenario.Alert,
|
||||||
|
&core.Result{
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scenario.Resolved,
|
||||||
|
)
|
||||||
|
if scenario.ExpectedError && err == nil {
|
||||||
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
description := "alert description"
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider *AlertProvider
|
||||||
|
Alert *alert.Alert
|
||||||
|
Endpoint *core.Endpoint
|
||||||
|
Result *core.Result
|
||||||
|
Resolved bool
|
||||||
|
want alertCreateRequest
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "missing all params (unresolved)",
|
||||||
|
Provider: &AlertProvider{},
|
||||||
|
Alert: &alert.Alert{},
|
||||||
|
Endpoint: &core.Endpoint{},
|
||||||
|
Result: &core.Result{},
|
||||||
|
Resolved: false,
|
||||||
|
want: alertCreateRequest{
|
||||||
|
Message: " - ",
|
||||||
|
Priority: "P1",
|
||||||
|
Source: "gatus",
|
||||||
|
Entity: "gatus-",
|
||||||
|
Alias: "gatus-healthcheck-",
|
||||||
|
Description: "An alert for ** has been triggered due to having failed 0 time(s) in a row\n",
|
||||||
|
Tags: nil,
|
||||||
|
Details: map[string]string{},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "missing all params (resolved)",
|
||||||
|
Provider: &AlertProvider{},
|
||||||
|
Alert: &alert.Alert{},
|
||||||
|
Endpoint: &core.Endpoint{},
|
||||||
|
Result: &core.Result{},
|
||||||
|
Resolved: true,
|
||||||
|
want: alertCreateRequest{
|
||||||
|
Message: "RESOLVED: - ",
|
||||||
|
Priority: "P1",
|
||||||
|
Source: "gatus",
|
||||||
|
Entity: "gatus-",
|
||||||
|
Alias: "gatus-healthcheck-",
|
||||||
|
Description: "An alert for ** has been resolved after passing successfully 0 time(s) in a row\n",
|
||||||
|
Tags: nil,
|
||||||
|
Details: map[string]string{},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "with default options (unresolved)",
|
||||||
|
Provider: &AlertProvider{},
|
||||||
|
Alert: &alert.Alert{
|
||||||
|
Description: &description,
|
||||||
|
FailureThreshold: 3,
|
||||||
|
},
|
||||||
|
Endpoint: &core.Endpoint{
|
||||||
|
Name: "my super app",
|
||||||
|
},
|
||||||
|
Result: &core.Result{
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{
|
||||||
|
Condition: "[STATUS] == 200",
|
||||||
|
Success: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Condition: "[BODY] == OK",
|
||||||
|
Success: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Resolved: false,
|
||||||
|
want: alertCreateRequest{
|
||||||
|
Message: "my super app - " + description,
|
||||||
|
Priority: "P1",
|
||||||
|
Source: "gatus",
|
||||||
|
Entity: "gatus-my-super-app",
|
||||||
|
Alias: "gatus-healthcheck-my-super-app",
|
||||||
|
Description: "An alert for *my super app* has been triggered due to having failed 3 time(s) in a row\n▣ - `[STATUS] == 200`\n▢ - `[BODY] == OK`\n",
|
||||||
|
Tags: nil,
|
||||||
|
Details: map[string]string{},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "with custom options (resolved)",
|
||||||
|
Provider: &AlertProvider{
|
||||||
|
Priority: "P5",
|
||||||
|
EntityPrefix: "oompa-",
|
||||||
|
AliasPrefix: "loompa-",
|
||||||
|
Source: "gatus-hc",
|
||||||
|
Tags: []string{"do-ba-dee-doo"},
|
||||||
|
},
|
||||||
|
Alert: &alert.Alert{
|
||||||
|
Description: &description,
|
||||||
|
SuccessThreshold: 4,
|
||||||
|
},
|
||||||
|
Endpoint: &core.Endpoint{
|
||||||
|
Name: "my mega app",
|
||||||
|
},
|
||||||
|
Result: &core.Result{
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{
|
||||||
|
Condition: "[STATUS] == 200",
|
||||||
|
Success: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Resolved: true,
|
||||||
|
want: alertCreateRequest{
|
||||||
|
Message: "RESOLVED: my mega app - " + description,
|
||||||
|
Priority: "P5",
|
||||||
|
Source: "gatus-hc",
|
||||||
|
Entity: "oompa-my-mega-app",
|
||||||
|
Alias: "loompa-my-mega-app",
|
||||||
|
Description: "An alert for *my mega app* has been resolved after passing successfully 4 time(s) in a row\n▣ - `[STATUS] == 200`\n",
|
||||||
|
Tags: []string{"do-ba-dee-doo"},
|
||||||
|
Details: map[string]string{},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "with default options and details (unresolved)",
|
||||||
|
Provider: &AlertProvider{
|
||||||
|
Tags: []string{"foo"},
|
||||||
|
},
|
||||||
|
Alert: &alert.Alert{
|
||||||
|
Description: &description,
|
||||||
|
FailureThreshold: 6,
|
||||||
|
},
|
||||||
|
Endpoint: &core.Endpoint{
|
||||||
|
Name: "my app",
|
||||||
|
Group: "end game",
|
||||||
|
URL: "https://my.go/app",
|
||||||
|
},
|
||||||
|
Result: &core.Result{
|
||||||
|
HTTPStatus: 400,
|
||||||
|
Hostname: "my.go",
|
||||||
|
Errors: []string{"error 01", "error 02"},
|
||||||
|
Success: false,
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{
|
||||||
|
Condition: "[STATUS] == 200",
|
||||||
|
Success: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Resolved: false,
|
||||||
|
want: alertCreateRequest{
|
||||||
|
Message: "[end game] my app - " + description,
|
||||||
|
Priority: "P1",
|
||||||
|
Source: "gatus",
|
||||||
|
Entity: "gatus-end-game-my-app",
|
||||||
|
Alias: "gatus-healthcheck-end-game-my-app",
|
||||||
|
Description: "An alert for *end game/my app* has been triggered due to having failed 6 time(s) in a row\n▢ - `[STATUS] == 200`\n",
|
||||||
|
Tags: []string{"foo"},
|
||||||
|
Details: map[string]string{
|
||||||
|
"endpoint:url": "https://my.go/app",
|
||||||
|
"endpoint:group": "end game",
|
||||||
|
"result:hostname": "my.go",
|
||||||
|
"result:errors": "error 01,error 02",
|
||||||
|
"result:http_status": "400",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
actual := scenario
|
||||||
|
t.Run(actual.Name, func(t *testing.T) {
|
||||||
|
if got := actual.Provider.buildCreateRequestBody(actual.Endpoint, actual.Alert, actual.Result, actual.Resolved); !reflect.DeepEqual(got, actual.want) {
|
||||||
|
t.Errorf("buildCreateRequestBody() = %v, want %v", got, actual.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_buildCloseRequestBody(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
description := "alert description"
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider *AlertProvider
|
||||||
|
Alert *alert.Alert
|
||||||
|
Endpoint *core.Endpoint
|
||||||
|
want alertCloseRequest
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "Missing all values",
|
||||||
|
Provider: &AlertProvider{},
|
||||||
|
Alert: &alert.Alert{},
|
||||||
|
Endpoint: &core.Endpoint{},
|
||||||
|
want: alertCloseRequest{
|
||||||
|
Source: "",
|
||||||
|
Note: "RESOLVED: - ",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "Basic values",
|
||||||
|
Provider: &AlertProvider{},
|
||||||
|
Alert: &alert.Alert{
|
||||||
|
Description: &description,
|
||||||
|
},
|
||||||
|
Endpoint: &core.Endpoint{
|
||||||
|
Name: "endpoint name",
|
||||||
|
},
|
||||||
|
want: alertCloseRequest{
|
||||||
|
Source: "endpoint-name",
|
||||||
|
Note: "RESOLVED: endpoint name - alert description",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
actual := scenario
|
||||||
|
t.Run(actual.Name, func(t *testing.T) {
|
||||||
|
if got := actual.Provider.buildCloseRequestBody(actual.Endpoint, actual.Alert); !reflect.DeepEqual(got, actual.want) {
|
||||||
|
t.Errorf("buildCloseRequestBody() = %v, want %v", got, actual.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
package pagerduty
|
package pagerduty
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,11 +21,11 @@ const (
|
|||||||
type AlertProvider struct {
|
type AlertProvider struct {
|
||||||
IntegrationKey string `yaml:"integration-key"`
|
IntegrationKey string `yaml:"integration-key"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
|
||||||
|
|
||||||
// Overrides is a list of Override that may be prioritized over the default configuration
|
// Overrides is a list of Override that may be prioritized over the default configuration
|
||||||
Overrides []Override `yaml:"overrides"`
|
Overrides []Override `yaml:"overrides,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Override is a case under which the default integration is overridden
|
// Override is a case under which the default integration is overridden
|
||||||
@@ -45,24 +49,56 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.IntegrationKey) == 32 || len(provider.Overrides) != 0
|
return len(provider.IntegrationKey) == 32 || len(provider.Overrides) != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
//
|
//
|
||||||
// relevant: https://developer.pagerduty.com/docs/events-api-v2/trigger-events/
|
// Relevant: https://developer.pagerduty.com/docs/events-api-v2/trigger-events/
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, _ *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
|
request, err := http.NewRequest(http.MethodPost, restAPIURL, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
if alert.IsSendingOnResolved() {
|
||||||
|
if resolved {
|
||||||
|
// The alert has been resolved and there's no error, so we can clear the alert's ResolveKey
|
||||||
|
alert.ResolveKey = ""
|
||||||
|
} else {
|
||||||
|
// We need to retrieve the resolve key from the response
|
||||||
|
body, err := io.ReadAll(response.Body)
|
||||||
|
var payload pagerDutyResponsePayload
|
||||||
|
if err = json.Unmarshal(body, &payload); err != nil {
|
||||||
|
// Silently fail. We don't want to create tons of alerts just because we failed to parse the body.
|
||||||
|
log.Printf("[pagerduty][Send] Ran into error unmarshaling pagerduty response: %s", err.Error())
|
||||||
|
} else {
|
||||||
|
alert.ResolveKey = payload.DedupKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message, eventAction, resolveKey string
|
var message, eventAction, resolveKey string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("RESOLVED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
|
||||||
eventAction = "resolve"
|
eventAction = "resolve"
|
||||||
resolveKey = alert.ResolveKey
|
resolveKey = alert.ResolveKey
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("TRIGGERED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("TRIGGERED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
|
||||||
eventAction = "trigger"
|
eventAction = "trigger"
|
||||||
resolveKey = ""
|
resolveKey = ""
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return fmt.Sprintf(`{
|
||||||
URL: restAPIURL,
|
|
||||||
Method: http.MethodPost,
|
|
||||||
Body: fmt.Sprintf(`{
|
|
||||||
"routing_key": "%s",
|
"routing_key": "%s",
|
||||||
"dedup_key": "%s",
|
"dedup_key": "%s",
|
||||||
"event_action": "%s",
|
"event_action": "%s",
|
||||||
@@ -71,15 +107,11 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
"source": "%s",
|
"source": "%s",
|
||||||
"severity": "critical"
|
"severity": "critical"
|
||||||
}
|
}
|
||||||
}`, provider.getPagerDutyIntegrationKeyForGroup(service.Group), resolveKey, eventAction, message, service.Name),
|
}`, provider.getIntegrationKeyForGroup(endpoint.Group), resolveKey, eventAction, message, endpoint.Name)
|
||||||
Headers: map[string]string{
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// getPagerDutyIntegrationKeyForGroup returns the appropriate pagerduty integration key for a given group
|
// getIntegrationKeyForGroup returns the appropriate pagerduty integration key for a given group
|
||||||
func (provider *AlertProvider) getPagerDutyIntegrationKeyForGroup(group string) string {
|
func (provider *AlertProvider) getIntegrationKeyForGroup(group string) string {
|
||||||
if provider.Overrides != nil {
|
if provider.Overrides != nil {
|
||||||
for _, override := range provider.Overrides {
|
for _, override := range provider.Overrides {
|
||||||
if group == override.Group {
|
if group == override.Group {
|
||||||
@@ -87,13 +119,16 @@ func (provider *AlertProvider) getPagerDutyIntegrationKeyForGroup(group string)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if provider.IntegrationKey != "" {
|
return provider.IntegrationKey
|
||||||
return provider.IntegrationKey
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
|
func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
|
||||||
return provider.DefaultAlert
|
return provider.DefaultAlert
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type pagerDutyResponsePayload struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
DedupKey string `json:"dedup_key"`
|
||||||
|
}
|
||||||
@@ -3,11 +3,12 @@ package pagerduty
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -57,111 +58,122 @@ func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
provider := AlertProvider{IntegrationKey: "00000000000000000000000000000000"}
|
defer client.InjectHTTPClient(nil)
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, true)
|
firstDescription := "description-1"
|
||||||
if customAlertProvider == nil {
|
secondDescription := "description-2"
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
scenarios := []struct {
|
||||||
}
|
Name string
|
||||||
if !strings.Contains(customAlertProvider.Body, "RESOLVED") {
|
Provider AlertProvider
|
||||||
t.Error("customAlertProvider.Body should've contained the substring RESOLVED")
|
Alert alert.Alert
|
||||||
}
|
Resolved bool
|
||||||
if customAlertProvider.URL != "https://events.pagerduty.com/v2/enqueue" {
|
MockRoundTripper test.MockRoundTripper
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://events.pagerduty.com/v2/enqueue", customAlertProvider.URL)
|
ExpectedError bool
|
||||||
}
|
}{
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
Name: "triggered",
|
||||||
}
|
Provider: AlertProvider{},
|
||||||
body := make(map[string]interface{})
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
Resolved: false,
|
||||||
if err != nil {
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
}
|
}),
|
||||||
}
|
ExpectedError: false,
|
||||||
|
},
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlertAndOverride(t *testing.T) {
|
{
|
||||||
provider := AlertProvider{
|
Name: "triggered-error",
|
||||||
IntegrationKey: "",
|
Provider: AlertProvider{},
|
||||||
Overrides: []Override{
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
{
|
Resolved: false,
|
||||||
IntegrationKey: "00000000000000000000000000000000",
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
Group: "group",
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
},
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, true)
|
for _, scenario := range scenarios {
|
||||||
if customAlertProvider == nil {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
}
|
err := scenario.Provider.Send(
|
||||||
if !strings.Contains(customAlertProvider.Body, "RESOLVED") {
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
t.Error("customAlertProvider.Body should've contained the substring RESOLVED")
|
&scenario.Alert,
|
||||||
}
|
&core.Result{
|
||||||
if customAlertProvider.URL != "https://events.pagerduty.com/v2/enqueue" {
|
ConditionResults: []*core.ConditionResult{
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://events.pagerduty.com/v2/enqueue", customAlertProvider.URL)
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
}
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
},
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
},
|
||||||
}
|
scenario.Resolved,
|
||||||
body := make(map[string]interface{})
|
)
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
if scenario.ExpectedError && err == nil {
|
||||||
if err != nil {
|
t.Error("expected error, got none")
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{IntegrationKey: "00000000000000000000000000000000"}
|
description := "test"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, false)
|
scenarios := []struct {
|
||||||
if customAlertProvider == nil {
|
Name string
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Provider AlertProvider
|
||||||
}
|
Alert alert.Alert
|
||||||
if !strings.Contains(customAlertProvider.Body, "TRIGGERED") {
|
Resolved bool
|
||||||
t.Error("customAlertProvider.Body should've contained the substring TRIGGERED")
|
ExpectedBody string
|
||||||
}
|
}{
|
||||||
if customAlertProvider.URL != "https://events.pagerduty.com/v2/enqueue" {
|
{
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://events.pagerduty.com/v2/enqueue", customAlertProvider.URL)
|
Name: "triggered",
|
||||||
}
|
Provider: AlertProvider{IntegrationKey: "00000000000000000000000000000000"},
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
Alert: alert.Alert{Description: &description},
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
Resolved: false,
|
||||||
}
|
ExpectedBody: "{\n \"routing_key\": \"00000000000000000000000000000000\",\n \"dedup_key\": \"\",\n \"event_action\": \"trigger\",\n \"payload\": {\n \"summary\": \"TRIGGERED: - test\",\n \"source\": \"\",\n \"severity\": \"critical\"\n }\n}",
|
||||||
body := make(map[string]interface{})
|
},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
{
|
||||||
if err != nil {
|
Name: "resolved",
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
Provider: AlertProvider{IntegrationKey: "00000000000000000000000000000000"},
|
||||||
}
|
Alert: alert.Alert{Description: &description, ResolveKey: "key"},
|
||||||
}
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n \"routing_key\": \"00000000000000000000000000000000\",\n \"dedup_key\": \"key\",\n \"event_action\": \"resolve\",\n \"payload\": {\n \"summary\": \"RESOLVED: - test\",\n \"source\": \"\",\n \"severity\": \"critical\"\n }\n}",
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlertAndOverride(t *testing.T) {
|
|
||||||
provider := AlertProvider{
|
|
||||||
IntegrationKey: "",
|
|
||||||
Overrides: []Override{
|
|
||||||
{
|
|
||||||
IntegrationKey: "00000000000000000000000000000000",
|
|
||||||
Group: "group",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, false)
|
for _, scenario := range scenarios {
|
||||||
if customAlertProvider == nil {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
body := scenario.Provider.buildRequestBody(&core.Endpoint{}, &scenario.Alert, &core.Result{}, scenario.Resolved)
|
||||||
}
|
if body != scenario.ExpectedBody {
|
||||||
if !strings.Contains(customAlertProvider.Body, "TRIGGERED") {
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
t.Error("customAlertProvider.Body should've contained the substring TRIGGERED")
|
}
|
||||||
}
|
out := make(map[string]interface{})
|
||||||
if customAlertProvider.URL != "https://events.pagerduty.com/v2/enqueue" {
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://events.pagerduty.com/v2/enqueue", customAlertProvider.URL)
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
}
|
}
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
})
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
|
||||||
}
|
|
||||||
body := make(map[string]interface{})
|
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
|
||||||
if err != nil {
|
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_getPagerDutyIntegrationKey(t *testing.T) {
|
func TestAlertProvider_getIntegrationKeyForGroup(t *testing.T) {
|
||||||
scenarios := []struct {
|
scenarios := []struct {
|
||||||
Name string
|
Name string
|
||||||
Provider AlertProvider
|
Provider AlertProvider
|
||||||
@@ -217,9 +229,18 @@ func TestAlertProvider_getPagerDutyIntegrationKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
if output := scenario.Provider.getPagerDutyIntegrationKeyForGroup(scenario.InputGroup); output != scenario.ExpectedOutput {
|
if output := scenario.Provider.getIntegrationKeyForGroup(scenario.InputGroup); output != scenario.ExpectedOutput {
|
||||||
t.Errorf("expected %s, got %s", scenario.ExpectedOutput, output)
|
t.Errorf("expected %s, got %s", scenario.ExpectedOutput, output)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/discord"
|
"github.com/TwiN/gatus/v3/alerting/provider/discord"
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/provider/email"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v3/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v3/alerting/provider/messagebird"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/pagerduty"
|
"github.com/TwiN/gatus/v3/alerting/provider/pagerduty"
|
||||||
@@ -19,32 +20,32 @@ type AlertProvider interface {
|
|||||||
// IsValid returns whether the provider's configuration is valid
|
// IsValid returns whether the provider's configuration is valid
|
||||||
IsValid() bool
|
IsValid() bool
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
|
||||||
ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider
|
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
GetDefaultAlert() *alert.Alert
|
GetDefaultAlert() *alert.Alert
|
||||||
|
|
||||||
|
// Send an alert using the provider
|
||||||
|
Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseWithDefaultAlert parses a service alert by using the provider's default alert as a baseline
|
// ParseWithDefaultAlert parses an Endpoint alert by using the provider's default alert as a baseline
|
||||||
func ParseWithDefaultAlert(providerDefaultAlert, serviceAlert *alert.Alert) {
|
func ParseWithDefaultAlert(providerDefaultAlert, endpointAlert *alert.Alert) {
|
||||||
if providerDefaultAlert == nil || serviceAlert == nil {
|
if providerDefaultAlert == nil || endpointAlert == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if serviceAlert.Enabled == nil {
|
if endpointAlert.Enabled == nil {
|
||||||
serviceAlert.Enabled = providerDefaultAlert.Enabled
|
endpointAlert.Enabled = providerDefaultAlert.Enabled
|
||||||
}
|
}
|
||||||
if serviceAlert.SendOnResolved == nil {
|
if endpointAlert.SendOnResolved == nil {
|
||||||
serviceAlert.SendOnResolved = providerDefaultAlert.SendOnResolved
|
endpointAlert.SendOnResolved = providerDefaultAlert.SendOnResolved
|
||||||
}
|
}
|
||||||
if serviceAlert.Description == nil {
|
if endpointAlert.Description == nil {
|
||||||
serviceAlert.Description = providerDefaultAlert.Description
|
endpointAlert.Description = providerDefaultAlert.Description
|
||||||
}
|
}
|
||||||
if serviceAlert.FailureThreshold == 0 {
|
if endpointAlert.FailureThreshold == 0 {
|
||||||
serviceAlert.FailureThreshold = providerDefaultAlert.FailureThreshold
|
endpointAlert.FailureThreshold = providerDefaultAlert.FailureThreshold
|
||||||
}
|
}
|
||||||
if serviceAlert.SuccessThreshold == 0 {
|
if endpointAlert.SuccessThreshold == 0 {
|
||||||
serviceAlert.SuccessThreshold = providerDefaultAlert.SuccessThreshold
|
endpointAlert.SuccessThreshold = providerDefaultAlert.SuccessThreshold
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,6 +53,7 @@ var (
|
|||||||
// Validate interface implementation on compile
|
// Validate interface implementation on compile
|
||||||
_ AlertProvider = (*custom.AlertProvider)(nil)
|
_ AlertProvider = (*custom.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*discord.AlertProvider)(nil)
|
_ AlertProvider = (*discord.AlertProvider)(nil)
|
||||||
|
_ AlertProvider = (*email.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*mattermost.AlertProvider)(nil)
|
_ AlertProvider = (*mattermost.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*messagebird.AlertProvider)(nil)
|
_ AlertProvider = (*messagebird.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*pagerduty.AlertProvider)(nil)
|
_ AlertProvider = (*pagerduty.AlertProvider)(nil)
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import (
|
|||||||
|
|
||||||
func TestParseWithDefaultAlert(t *testing.T) {
|
func TestParseWithDefaultAlert(t *testing.T) {
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
DefaultAlert, ServiceAlert, ExpectedOutputAlert *alert.Alert
|
DefaultAlert, EndpointAlert, ExpectedOutputAlert *alert.Alert
|
||||||
}
|
}
|
||||||
enabled := true
|
enabled := true
|
||||||
disabled := false
|
disabled := false
|
||||||
@@ -17,7 +17,7 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
secondDescription := "description-2"
|
secondDescription := "description-2"
|
||||||
scenarios := []Scenario{
|
scenarios := []Scenario{
|
||||||
{
|
{
|
||||||
Name: "service-alert-type-only",
|
Name: "endpoint-alert-type-only",
|
||||||
DefaultAlert: &alert.Alert{
|
DefaultAlert: &alert.Alert{
|
||||||
Enabled: &enabled,
|
Enabled: &enabled,
|
||||||
SendOnResolved: &enabled,
|
SendOnResolved: &enabled,
|
||||||
@@ -25,7 +25,7 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
FailureThreshold: 5,
|
FailureThreshold: 5,
|
||||||
SuccessThreshold: 10,
|
SuccessThreshold: 10,
|
||||||
},
|
},
|
||||||
ServiceAlert: &alert.Alert{
|
EndpointAlert: &alert.Alert{
|
||||||
Type: alert.TypeDiscord,
|
Type: alert.TypeDiscord,
|
||||||
},
|
},
|
||||||
ExpectedOutputAlert: &alert.Alert{
|
ExpectedOutputAlert: &alert.Alert{
|
||||||
@@ -38,7 +38,7 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "service-alert-overwrites-default-alert",
|
Name: "endpoint-alert-overwrites-default-alert",
|
||||||
DefaultAlert: &alert.Alert{
|
DefaultAlert: &alert.Alert{
|
||||||
Enabled: &disabled,
|
Enabled: &disabled,
|
||||||
SendOnResolved: &disabled,
|
SendOnResolved: &disabled,
|
||||||
@@ -46,7 +46,7 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
FailureThreshold: 5,
|
FailureThreshold: 5,
|
||||||
SuccessThreshold: 10,
|
SuccessThreshold: 10,
|
||||||
},
|
},
|
||||||
ServiceAlert: &alert.Alert{
|
EndpointAlert: &alert.Alert{
|
||||||
Type: alert.TypeTelegram,
|
Type: alert.TypeTelegram,
|
||||||
Enabled: &enabled,
|
Enabled: &enabled,
|
||||||
SendOnResolved: &enabled,
|
SendOnResolved: &enabled,
|
||||||
@@ -64,7 +64,7 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "service-alert-partially-overwrites-default-alert",
|
Name: "endpoint-alert-partially-overwrites-default-alert",
|
||||||
DefaultAlert: &alert.Alert{
|
DefaultAlert: &alert.Alert{
|
||||||
Enabled: &enabled,
|
Enabled: &enabled,
|
||||||
SendOnResolved: &enabled,
|
SendOnResolved: &enabled,
|
||||||
@@ -72,7 +72,7 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
FailureThreshold: 5,
|
FailureThreshold: 5,
|
||||||
SuccessThreshold: 10,
|
SuccessThreshold: 10,
|
||||||
},
|
},
|
||||||
ServiceAlert: &alert.Alert{
|
EndpointAlert: &alert.Alert{
|
||||||
Type: alert.TypeDiscord,
|
Type: alert.TypeDiscord,
|
||||||
Enabled: nil,
|
Enabled: nil,
|
||||||
SendOnResolved: nil,
|
SendOnResolved: nil,
|
||||||
@@ -98,7 +98,7 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
FailureThreshold: 5,
|
FailureThreshold: 5,
|
||||||
SuccessThreshold: 10,
|
SuccessThreshold: 10,
|
||||||
},
|
},
|
||||||
ServiceAlert: &alert.Alert{
|
EndpointAlert: &alert.Alert{
|
||||||
Type: alert.TypeDiscord,
|
Type: alert.TypeDiscord,
|
||||||
},
|
},
|
||||||
ExpectedOutputAlert: &alert.Alert{
|
ExpectedOutputAlert: &alert.Alert{
|
||||||
@@ -120,33 +120,33 @@ func TestParseWithDefaultAlert(t *testing.T) {
|
|||||||
FailureThreshold: 2,
|
FailureThreshold: 2,
|
||||||
SuccessThreshold: 5,
|
SuccessThreshold: 5,
|
||||||
},
|
},
|
||||||
ServiceAlert: nil,
|
EndpointAlert: nil,
|
||||||
ExpectedOutputAlert: nil,
|
ExpectedOutputAlert: nil,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
ParseWithDefaultAlert(scenario.DefaultAlert, scenario.ServiceAlert)
|
ParseWithDefaultAlert(scenario.DefaultAlert, scenario.EndpointAlert)
|
||||||
if scenario.ExpectedOutputAlert == nil {
|
if scenario.ExpectedOutputAlert == nil {
|
||||||
if scenario.ServiceAlert != nil {
|
if scenario.EndpointAlert != nil {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if scenario.ServiceAlert.IsEnabled() != scenario.ExpectedOutputAlert.IsEnabled() {
|
if scenario.EndpointAlert.IsEnabled() != scenario.ExpectedOutputAlert.IsEnabled() {
|
||||||
t.Errorf("expected ServiceAlert.IsEnabled() to be %v, got %v", scenario.ExpectedOutputAlert.IsEnabled(), scenario.ServiceAlert.IsEnabled())
|
t.Errorf("expected EndpointAlert.IsEnabled() to be %v, got %v", scenario.ExpectedOutputAlert.IsEnabled(), scenario.EndpointAlert.IsEnabled())
|
||||||
}
|
}
|
||||||
if scenario.ServiceAlert.IsSendingOnResolved() != scenario.ExpectedOutputAlert.IsSendingOnResolved() {
|
if scenario.EndpointAlert.IsSendingOnResolved() != scenario.ExpectedOutputAlert.IsSendingOnResolved() {
|
||||||
t.Errorf("expected ServiceAlert.IsSendingOnResolved() to be %v, got %v", scenario.ExpectedOutputAlert.IsSendingOnResolved(), scenario.ServiceAlert.IsSendingOnResolved())
|
t.Errorf("expected EndpointAlert.IsSendingOnResolved() to be %v, got %v", scenario.ExpectedOutputAlert.IsSendingOnResolved(), scenario.EndpointAlert.IsSendingOnResolved())
|
||||||
}
|
}
|
||||||
if scenario.ServiceAlert.GetDescription() != scenario.ExpectedOutputAlert.GetDescription() {
|
if scenario.EndpointAlert.GetDescription() != scenario.ExpectedOutputAlert.GetDescription() {
|
||||||
t.Errorf("expected ServiceAlert.GetDescription() to be %v, got %v", scenario.ExpectedOutputAlert.GetDescription(), scenario.ServiceAlert.GetDescription())
|
t.Errorf("expected EndpointAlert.GetDescription() to be %v, got %v", scenario.ExpectedOutputAlert.GetDescription(), scenario.EndpointAlert.GetDescription())
|
||||||
}
|
}
|
||||||
if scenario.ServiceAlert.FailureThreshold != scenario.ExpectedOutputAlert.FailureThreshold {
|
if scenario.EndpointAlert.FailureThreshold != scenario.ExpectedOutputAlert.FailureThreshold {
|
||||||
t.Errorf("expected ServiceAlert.FailureThreshold to be %v, got %v", scenario.ExpectedOutputAlert.FailureThreshold, scenario.ServiceAlert.FailureThreshold)
|
t.Errorf("expected EndpointAlert.FailureThreshold to be %v, got %v", scenario.ExpectedOutputAlert.FailureThreshold, scenario.EndpointAlert.FailureThreshold)
|
||||||
}
|
}
|
||||||
if scenario.ServiceAlert.SuccessThreshold != scenario.ExpectedOutputAlert.SuccessThreshold {
|
if scenario.EndpointAlert.SuccessThreshold != scenario.ExpectedOutputAlert.SuccessThreshold {
|
||||||
t.Errorf("expected ServiceAlert.SuccessThreshold to be %v, got %v", scenario.ExpectedOutputAlert.SuccessThreshold, scenario.ServiceAlert.SuccessThreshold)
|
t.Errorf("expected EndpointAlert.SuccessThreshold to be %v, got %v", scenario.ExpectedOutputAlert.SuccessThreshold, scenario.EndpointAlert.SuccessThreshold)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package slack
|
package slack
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,7 +15,7 @@ import (
|
|||||||
type AlertProvider struct {
|
type AlertProvider struct {
|
||||||
WebhookURL string `yaml:"webhook-url"` // Slack webhook URL
|
WebhookURL string `yaml:"webhook-url"` // Slack webhook URL
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,14 +24,33 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.WebhookURL) > 0
|
return len(provider.WebhookURL) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
|
request, err := http.NewRequest(http.MethodPost, provider.WebhookURL, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message, color, results string
|
var message, color, results string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", service.Name, alert.SuccessThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
color = "#36A64F"
|
color = "#36A64F"
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", service.Name, alert.FailureThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
color = "#DD0000"
|
color = "#DD0000"
|
||||||
}
|
}
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
@@ -45,10 +66,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
description = ":\\n> " + alertDescription
|
description = ":\\n> " + alertDescription
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return fmt.Sprintf(`{
|
||||||
URL: provider.WebhookURL,
|
|
||||||
Method: http.MethodPost,
|
|
||||||
Body: fmt.Sprintf(`{
|
|
||||||
"text": "",
|
"text": "",
|
||||||
"attachments": [
|
"attachments": [
|
||||||
{
|
{
|
||||||
@@ -65,9 +83,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}`, message, description, color, results),
|
}`, message, description, color, results)
|
||||||
Headers: map[string]string{"Content-Type": "application/json"},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ package slack
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -15,56 +16,162 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
if invalidProvider.IsValid() {
|
if invalidProvider.IsValid() {
|
||||||
t.Error("provider shouldn't have been valid")
|
t.Error("provider shouldn't have been valid")
|
||||||
}
|
}
|
||||||
validProvider := AlertProvider{WebhookURL: "http://example.com"}
|
validProvider := AlertProvider{WebhookURL: "https://example.com"}
|
||||||
if !validProvider.IsValid() {
|
if !validProvider.IsValid() {
|
||||||
t.Error("provider should've been valid")
|
t.Error("provider should've been valid")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
defer client.InjectHTTPClient(nil)
|
||||||
alertDescription := "test"
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "resolved") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring resolved")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
if customAlertProvider.URL != "http://example.com" {
|
err := scenario.Provider.Send(
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.com", customAlertProvider.URL)
|
&core.Endpoint{Name: "name"},
|
||||||
}
|
&scenario.Alert,
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
&core.Result{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
ConditionResults: []*core.ConditionResult{
|
||||||
}
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
},
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
scenario.Resolved,
|
||||||
}
|
)
|
||||||
if expected := "An alert for *svc* has been resolved after passing successfully 0 time(s) in a row:\n> test"; expected != body["attachments"].([]interface{})[0].(map[string]interface{})["text"] {
|
if scenario.ExpectedError && err == nil {
|
||||||
t.Errorf("expected $.attachments[0].description to be %s, got %s", expected, body["attachments"].([]interface{})[0].(map[string]interface{})["text"])
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Endpoint core.Endpoint
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"short\": false,\n \"color\": \"#DD0000\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-with-group",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name", Group: "group"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *group/name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"short\": false,\n \"color\": \"#DD0000\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"short\": false,\n \"color\": \"#36A64F\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-with-group",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name", Group: "group"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *group/name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"short\": false,\n \"color\": \"#36A64F\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "triggered") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring triggered")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
body := scenario.Provider.buildRequestBody(
|
||||||
if customAlertProvider.URL != "http://example.com" {
|
&scenario.Endpoint,
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.com", customAlertProvider.URL)
|
&scenario.Alert,
|
||||||
}
|
&core.Result{
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
ConditionResults: []*core.ConditionResult{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
}
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
scenario.Resolved,
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
)
|
||||||
|
if body != scenario.ExpectedBody {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
|
}
|
||||||
|
out := make(map[string]interface{})
|
||||||
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
package teams
|
package teams
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,7 +15,7 @@ import (
|
|||||||
type AlertProvider struct {
|
type AlertProvider struct {
|
||||||
WebhookURL string `yaml:"webhook-url"`
|
WebhookURL string `yaml:"webhook-url"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,15 +24,33 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.WebhookURL) > 0
|
return len(provider.WebhookURL) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
var message string
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
var color string
|
request, err := http.NewRequest(http.MethodPost, provider.WebhookURL, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
|
var message, color string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", service.Name, alert.SuccessThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
color = "#36A64F"
|
color = "#36A64F"
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", service.Name, alert.FailureThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
color = "#DD0000"
|
color = "#DD0000"
|
||||||
}
|
}
|
||||||
var results string
|
var results string
|
||||||
@@ -47,10 +67,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
description = ":\\n> " + alertDescription
|
description = ":\\n> " + alertDescription
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return fmt.Sprintf(`{
|
||||||
URL: provider.WebhookURL,
|
|
||||||
Method: http.MethodPost,
|
|
||||||
Body: fmt.Sprintf(`{
|
|
||||||
"@type": "MessageCard",
|
"@type": "MessageCard",
|
||||||
"@context": "http://schema.org/extensions",
|
"@context": "http://schema.org/extensions",
|
||||||
"themeColor": "%s",
|
"themeColor": "%s",
|
||||||
@@ -66,9 +83,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
"text": "%s"
|
"text": "%s"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}`, color, message, description, service.URL, results),
|
}`, color, message, description, endpoint.URL, results)
|
||||||
Headers: map[string]string{"Content-Type": "application/json"},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ package teams
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -21,50 +22,137 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
defer client.InjectHTTPClient(nil)
|
||||||
alertDescription := "test"
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "resolved") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring resolved")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
if customAlertProvider.URL != "http://example.org" {
|
err := scenario.Provider.Send(
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.org", customAlertProvider.URL)
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
}
|
&scenario.Alert,
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
&core.Result{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
ConditionResults: []*core.ConditionResult{
|
||||||
}
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
},
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
scenario.Resolved,
|
||||||
}
|
)
|
||||||
if expected := "An alert for *svc* has been resolved after passing successfully 0 time(s) in a row:\n> test"; expected != body["text"] {
|
if scenario.ExpectedError && err == nil {
|
||||||
t.Errorf("expected $.text to be %s, got %s", expected, body["text"])
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
firstDescription := "description-1"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
secondDescription := "description-2"
|
||||||
if customAlertProvider == nil {
|
scenarios := []struct {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"#DD0000\",\n \"title\": \"🚨 Gatus\",\n \"text\": \"An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"sections\": [\n {\n \"activityTitle\": \"URL\",\n \"text\": \"\"\n },\n {\n \"activityTitle\": \"Condition results\",\n \"text\": \"❌ - `[CONNECTED] == true`<br/>❌ - `[STATUS] == 200`<br/>\"\n }\n ]\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"#36A64F\",\n \"title\": \"🚨 Gatus\",\n \"text\": \"An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"sections\": [\n {\n \"activityTitle\": \"URL\",\n \"text\": \"\"\n },\n {\n \"activityTitle\": \"Condition results\",\n \"text\": \"✅ - `[CONNECTED] == true`<br/>✅ - `[STATUS] == 200`<br/>\"\n }\n ]\n}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "triggered") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring triggered")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
body := scenario.Provider.buildRequestBody(
|
||||||
if customAlertProvider.URL != "http://example.org" {
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
t.Errorf("expected URL to be %s, got %s", "http://example.org", customAlertProvider.URL)
|
&scenario.Alert,
|
||||||
}
|
&core.Result{
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
ConditionResults: []*core.ConditionResult{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
}
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
scenario.Resolved,
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
)
|
||||||
|
if body != scenario.ExpectedBody {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
|
}
|
||||||
|
out := make(map[string]interface{})
|
||||||
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
package telegram
|
package telegram
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -14,7 +16,7 @@ type AlertProvider struct {
|
|||||||
Token string `yaml:"token"`
|
Token string `yaml:"token"`
|
||||||
ID string `yaml:"id"`
|
ID string `yaml:"id"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,13 +25,32 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.Token) > 0 && len(provider.ID) > 0
|
return len(provider.Token) > 0 && len(provider.ID) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
|
request, err := http.NewRequest(http.MethodPost, fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token), buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message, results string
|
var message, results string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been resolved:\\n—\\n _healthcheck passing successfully %d time(s) in a row_\\n— ", service.Name, alert.FailureThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been resolved:\\n—\\n _healthcheck passing successfully %d time(s) in a row_\\n— ", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("An alert for *%s* has been triggered:\\n—\\n _healthcheck failed %d time(s) in a row_\\n— ", service.Name, alert.FailureThreshold)
|
message = fmt.Sprintf("An alert for *%s* has been triggered:\\n—\\n _healthcheck failed %d time(s) in a row_\\n— ", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
}
|
}
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
@@ -46,12 +67,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
} else {
|
} else {
|
||||||
text = fmt.Sprintf("⛑ *Gatus* \\n%s \\n*Condition results*\\n%s", message, results)
|
text = fmt.Sprintf("⛑ *Gatus* \\n%s \\n*Condition results*\\n%s", message, results)
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return fmt.Sprintf(`{"chat_id": "%s", "text": "%s", "parse_mode": "MARKDOWN"}`, provider.ID, text)
|
||||||
URL: fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token),
|
|
||||||
Method: http.MethodPost,
|
|
||||||
Body: fmt.Sprintf(`{"chat_id": "%s", "text": "%s", "parse_mode": "MARKDOWN"}`, provider.ID, text),
|
|
||||||
Headers: map[string]string{"Content-Type": "application/json"},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -2,13 +2,13 @@ package telegram
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/test"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -22,70 +22,137 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "12345678"}
|
defer client.InjectHTTPClient(nil)
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
firstDescription := "description-1"
|
||||||
if customAlertProvider == nil {
|
secondDescription := "description-2"
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "resolved") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring resolved")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
if customAlertProvider.URL != fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token) {
|
err := scenario.Provider.Send(
|
||||||
t.Errorf("expected URL to be %s, got %s", fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token), customAlertProvider.URL)
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
}
|
&scenario.Alert,
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
&core.Result{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
ConditionResults: []*core.ConditionResult{
|
||||||
}
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
//_, err := json.Marshal(customAlertProvider.Body)
|
},
|
||||||
if err != nil {
|
scenario.Resolved,
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
)
|
||||||
|
if scenario.ExpectedError && err == nil {
|
||||||
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "0123456789"}
|
firstDescription := "description-1"
|
||||||
description := "Healthcheck Successful"
|
secondDescription := "description-2"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{Description: &description}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
scenarios := []struct {
|
||||||
if customAlertProvider == nil {
|
Name string
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{ID: "123"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\"chat_id\": \"123\", \"text\": \"⛑ *Gatus* \\nAn alert for *endpoint-name* has been triggered:\\n—\\n _healthcheck failed 3 time(s) in a row_\\n— \\n*Description* \\n_description-1_ \\n\\n*Condition results*\\n❌ - `[CONNECTED] == true`\\n❌ - `[STATUS] == 200`\\n\", \"parse_mode\": \"MARKDOWN\"}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{ID: "123"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\"chat_id\": \"123\", \"text\": \"⛑ *Gatus* \\nAn alert for *endpoint-name* has been resolved:\\n—\\n _healthcheck passing successfully 3 time(s) in a row_\\n— \\n*Description* \\n_description-2_ \\n\\n*Condition results*\\n✅ - `[CONNECTED] == true`\\n✅ - `[STATUS] == 200`\\n\", \"parse_mode\": \"MARKDOWN\"}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "triggered") {
|
for _, scenario := range scenarios {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring triggered")
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
}
|
body := scenario.Provider.buildRequestBody(
|
||||||
if customAlertProvider.URL != fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token) {
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
t.Errorf("expected URL to be %s, got %s", fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token), customAlertProvider.URL)
|
&scenario.Alert,
|
||||||
}
|
&core.Result{
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
ConditionResults: []*core.ConditionResult{
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
}
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
body := make(map[string]interface{})
|
},
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
},
|
||||||
if err != nil {
|
scenario.Resolved,
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
)
|
||||||
|
if body != scenario.ExpectedBody {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
|
}
|
||||||
|
out := make(map[string]interface{})
|
||||||
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithDescription(t *testing.T) {
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "0123456789"}
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
t.Error("expected default alert to be not nil")
|
||||||
if customAlertProvider == nil {
|
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
|
||||||
}
|
}
|
||||||
if !strings.Contains(customAlertProvider.Body, "triggered") {
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
t.Error("customAlertProvider.Body should've contained the substring triggered")
|
t.Error("expected default alert to be nil")
|
||||||
}
|
|
||||||
if customAlertProvider.URL != fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token) {
|
|
||||||
t.Errorf("expected URL to be %s, got %s", fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", provider.Token), customAlertProvider.URL)
|
|
||||||
}
|
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
|
||||||
}
|
|
||||||
body := make(map[string]interface{})
|
|
||||||
err := json.Unmarshal([]byte(customAlertProvider.Body), &body)
|
|
||||||
if err != nil {
|
|
||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
package twilio
|
package twilio
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,7 +20,7 @@ type AlertProvider struct {
|
|||||||
From string `yaml:"from"`
|
From string `yaml:"from"`
|
||||||
To string `yaml:"to"`
|
To string `yaml:"to"`
|
||||||
|
|
||||||
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
DefaultAlert *alert.Alert `yaml:"default-alert"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,27 +29,39 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
return len(provider.Token) > 0 && len(provider.SID) > 0 && len(provider.From) > 0 && len(provider.To) > 0
|
return len(provider.Token) > 0 && len(provider.SID) > 0 && len(provider.From) > 0 && len(provider.To) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// Send an alert using the provider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, _ *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
|
request, err := http.NewRequest(http.MethodPost, fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", provider.SID), buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
request.Header.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(provider.SID+":"+provider.Token))))
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message string
|
var message string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("RESOLVED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("TRIGGERED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("TRIGGERED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
|
||||||
}
|
|
||||||
return &custom.AlertProvider{
|
|
||||||
URL: fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", provider.SID),
|
|
||||||
Method: http.MethodPost,
|
|
||||||
Body: url.Values{
|
|
||||||
"To": {provider.To},
|
|
||||||
"From": {provider.From},
|
|
||||||
"Body": {message},
|
|
||||||
}.Encode(),
|
|
||||||
Headers: map[string]string{
|
|
||||||
"Content-Type": "application/x-www-form-urlencoded",
|
|
||||||
"Authorization": fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", provider.SID, provider.Token)))),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
return url.Values{
|
||||||
|
"To": {provider.To},
|
||||||
|
"From": {provider.From},
|
||||||
|
"Body": {message},
|
||||||
|
}.Encode()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package twilio
|
package twilio
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
@@ -25,54 +23,56 @@ func TestTwilioAlertProvider_IsValid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
provider := AlertProvider{
|
firstDescription := "description-1"
|
||||||
SID: "1",
|
secondDescription := "description-2"
|
||||||
Token: "2",
|
scenarios := []struct {
|
||||||
From: "3",
|
Name string
|
||||||
To: "4",
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{SID: "1", Token: "2", From: "3", To: "4"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "Body=TRIGGERED%3A+endpoint-name+-+description-1&From=3&To=4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{SID: "1", Token: "2", From: "3", To: "4"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "Body=RESOLVED%3A+endpoint-name+-+description-2&From=3&To=4",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
description := "alert-description"
|
for _, scenario := range scenarios {
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "service-name"}, &alert.Alert{Description: &description}, &core.Result{}, true)
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
if customAlertProvider == nil {
|
body := scenario.Provider.buildRequestBody(
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
}
|
&scenario.Alert,
|
||||||
if !strings.Contains(customAlertProvider.Body, "RESOLVED") {
|
&core.Result{
|
||||||
t.Error("customAlertProvider.Body should've contained the substring RESOLVED")
|
ConditionResults: []*core.ConditionResult{
|
||||||
}
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
if customAlertProvider.URL != "https://api.twilio.com/2010-04-01/Accounts/1/Messages.json" {
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://api.twilio.com/2010-04-01/Accounts/1/Messages.json", customAlertProvider.URL)
|
},
|
||||||
}
|
},
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
scenario.Resolved,
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
)
|
||||||
}
|
if body != scenario.ExpectedBody {
|
||||||
if customAlertProvider.Body != "Body=RESOLVED%3A+service-name+-+alert-description&From=3&To=4" {
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
t.Errorf("expected body to be %s, got %s", "Body=RESOLVED%3A+service-name+-+alert-description&From=3&To=4", customAlertProvider.Body)
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
provider := AlertProvider{
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
SID: "4",
|
t.Error("expected default alert to be not nil")
|
||||||
Token: "3",
|
|
||||||
From: "2",
|
|
||||||
To: "1",
|
|
||||||
}
|
}
|
||||||
description := "alert-description"
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "service-name"}, &alert.Alert{Description: &description}, &core.Result{}, false)
|
t.Error("expected default alert to be nil")
|
||||||
if customAlertProvider == nil {
|
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
|
||||||
}
|
|
||||||
if !strings.Contains(customAlertProvider.Body, "TRIGGERED") {
|
|
||||||
t.Error("customAlertProvider.Body should've contained the substring TRIGGERED")
|
|
||||||
}
|
|
||||||
if customAlertProvider.URL != "https://api.twilio.com/2010-04-01/Accounts/4/Messages.json" {
|
|
||||||
t.Errorf("expected URL to be %s, got %s", "https://api.twilio.com/2010-04-01/Accounts/4/Messages.json", customAlertProvider.URL)
|
|
||||||
}
|
|
||||||
if customAlertProvider.Method != http.MethodPost {
|
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
|
||||||
}
|
|
||||||
if customAlertProvider.Body != "Body=TRIGGERED%3A+service-name+-+alert-description&From=2&To=1" {
|
|
||||||
t.Errorf("expected body to be %s, got %s", "Body=TRIGGERED%3A+service-name+-+alert-description&From=2&To=1", customAlertProvider.Body)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,15 +14,21 @@ import (
|
|||||||
"github.com/go-ping/ping"
|
"github.com/go-ping/ping"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// injectedHTTPClient is used for testing purposes
|
||||||
|
var injectedHTTPClient *http.Client
|
||||||
|
|
||||||
// GetHTTPClient returns the shared HTTP client
|
// GetHTTPClient returns the shared HTTP client
|
||||||
func GetHTTPClient(config *Config) *http.Client {
|
func GetHTTPClient(config *Config) *http.Client {
|
||||||
|
if injectedHTTPClient != nil {
|
||||||
|
return injectedHTTPClient
|
||||||
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
return defaultConfig.getHTTPClient()
|
return defaultConfig.getHTTPClient()
|
||||||
}
|
}
|
||||||
return config.getHTTPClient()
|
return config.getHTTPClient()
|
||||||
}
|
}
|
||||||
|
|
||||||
// CanCreateTCPConnection checks whether a connection can be established with a TCP service
|
// CanCreateTCPConnection checks whether a connection can be established with a TCP endpoint
|
||||||
func CanCreateTCPConnection(address string, config *Config) bool {
|
func CanCreateTCPConnection(address string, config *Config) bool {
|
||||||
conn, err := net.DialTimeout("tcp", address, config.Timeout)
|
conn, err := net.DialTimeout("tcp", address, config.Timeout)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -104,3 +110,8 @@ func Ping(address string, config *Config) (bool, time.Duration) {
|
|||||||
}
|
}
|
||||||
return true, 0
|
return true, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InjectHTTPClient is used to inject a custom HTTP client for testing purposes
|
||||||
|
func InjectHTTPClient(httpClient *http.Client) {
|
||||||
|
injectedHTTPClient = httpClient
|
||||||
|
}
|
||||||
@@ -46,7 +46,7 @@ func (c *Config) ValidateAndSetDefaults() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetHTTPClient return a HTTP client matching the Config's parameters.
|
// GetHTTPClient return an HTTP client matching the Config's parameters.
|
||||||
func (c *Config) getHTTPClient() *http.Client {
|
func (c *Config) getHTTPClient() *http.Client {
|
||||||
if c.httpClient == nil {
|
if c.httpClient == nil {
|
||||||
c.httpClient = &http.Client{
|
c.httpClient = &http.Client{
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
services:
|
endpoints:
|
||||||
- name: front-end
|
- name: front-end
|
||||||
group: core
|
group: core
|
||||||
url: "https://twin.sh/health"
|
url: "https://twin.sh/health"
|
||||||
interval: 1m
|
interval: 5m
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
- "[BODY].status == UP"
|
- "[BODY].status == UP"
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
@@ -30,8 +29,8 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// ErrNoServiceInConfig is an error returned when a configuration file has no services configured
|
// ErrNoEndpointInConfig is an error returned when a configuration file has no endpoints configured
|
||||||
ErrNoServiceInConfig = errors.New("configuration file should contain at least 1 service")
|
ErrNoEndpointInConfig = errors.New("configuration file should contain at least 1 endpoint")
|
||||||
|
|
||||||
// ErrConfigFileNotFound is an error returned when the configuration file could not be found
|
// ErrConfigFileNotFound is an error returned when the configuration file could not be found
|
||||||
ErrConfigFileNotFound = errors.New("configuration file not found")
|
ErrConfigFileNotFound = errors.New("configuration file not found")
|
||||||
@@ -43,40 +42,48 @@ var (
|
|||||||
// Config is the main configuration structure
|
// Config is the main configuration structure
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// Debug Whether to enable debug logs
|
// Debug Whether to enable debug logs
|
||||||
Debug bool `yaml:"debug"`
|
Debug bool `yaml:"debug,omitempty"`
|
||||||
|
|
||||||
// Metrics Whether to expose metrics at /metrics
|
// Metrics Whether to expose metrics at /metrics
|
||||||
Metrics bool `yaml:"metrics"`
|
Metrics bool `yaml:"metrics,omitempty"`
|
||||||
|
|
||||||
// SkipInvalidConfigUpdate Whether to make the application ignore invalid configuration
|
// SkipInvalidConfigUpdate Whether to make the application ignore invalid configuration
|
||||||
// if the configuration file is updated while the application is running
|
// if the configuration file is updated while the application is running
|
||||||
SkipInvalidConfigUpdate bool `yaml:"skip-invalid-config-update"`
|
SkipInvalidConfigUpdate bool `yaml:"skip-invalid-config-update,omitempty"`
|
||||||
|
|
||||||
// DisableMonitoringLock Whether to disable the monitoring lock
|
// DisableMonitoringLock Whether to disable the monitoring lock
|
||||||
// The monitoring lock is what prevents multiple services from being processed at the same time.
|
// The monitoring lock is what prevents multiple endpoints from being processed at the same time.
|
||||||
// Disabling this may lead to inaccurate response times
|
// Disabling this may lead to inaccurate response times
|
||||||
DisableMonitoringLock bool `yaml:"disable-monitoring-lock"`
|
DisableMonitoringLock bool `yaml:"disable-monitoring-lock,omitempty"`
|
||||||
|
|
||||||
// Security Configuration for securing access to Gatus
|
// Security Configuration for securing access to Gatus
|
||||||
Security *security.Config `yaml:"security"`
|
Security *security.Config `yaml:"security,omitempty"`
|
||||||
|
|
||||||
// Alerting Configuration for alerting
|
// Alerting Configuration for alerting
|
||||||
Alerting *alerting.Config `yaml:"alerting"`
|
Alerting *alerting.Config `yaml:"alerting,omitempty"`
|
||||||
|
|
||||||
// Services List of services to monitor
|
// Endpoints List of endpoints to monitor
|
||||||
Services []*core.Service `yaml:"services"`
|
Endpoints []*core.Endpoint `yaml:"endpoints,omitempty"`
|
||||||
|
|
||||||
|
// Services List of endpoints to monitor
|
||||||
|
//
|
||||||
|
// XXX: Remove this in v5.0.0
|
||||||
|
// XXX: This is not a typo -- not v4.0.0, but v5.0.0 -- I want to give enough time for people to migrate
|
||||||
|
//
|
||||||
|
// Deprecated in favor of Endpoints
|
||||||
|
Services []*core.Endpoint `yaml:"services,omitempty"`
|
||||||
|
|
||||||
// Storage is the configuration for how the data is stored
|
// Storage is the configuration for how the data is stored
|
||||||
Storage *storage.Config `yaml:"storage"`
|
Storage *storage.Config `yaml:"storage,omitempty"`
|
||||||
|
|
||||||
// Web is the configuration for the web listener
|
// Web is the web configuration for the application
|
||||||
Web *web.Config `yaml:"web"`
|
Web *web.Config `yaml:"web,omitempty"`
|
||||||
|
|
||||||
// UI is the configuration for the UI
|
// UI is the configuration for the UI
|
||||||
UI *ui.Config `yaml:"ui"`
|
UI *ui.Config `yaml:"ui,omitempty"`
|
||||||
|
|
||||||
// Maintenance is the configuration for creating a maintenance window in which no alerts are sent
|
// Maintenance is the configuration for creating a maintenance window in which no alerts are sent
|
||||||
Maintenance *maintenance.Config `yaml:"maintenance"`
|
Maintenance *maintenance.Config `yaml:"maintenance,omitempty"`
|
||||||
|
|
||||||
filePath string // path to the file from which config was loaded from
|
filePath string // path to the file from which config was loaded from
|
||||||
lastFileModTime time.Time // last modification time
|
lastFileModTime time.Time // last modification time
|
||||||
@@ -134,32 +141,36 @@ func LoadDefaultConfiguration() (*Config, error) {
|
|||||||
|
|
||||||
func readConfigurationFile(fileName string) (config *Config, err error) {
|
func readConfigurationFile(fileName string) (config *Config, err error) {
|
||||||
var bytes []byte
|
var bytes []byte
|
||||||
if bytes, err = ioutil.ReadFile(fileName); err == nil {
|
if bytes, err = os.ReadFile(fileName); err == nil {
|
||||||
// file exists, so we'll parse it and return it
|
// file exists, so we'll parse it and return it
|
||||||
return parseAndValidateConfigBytes(bytes)
|
return parseAndValidateConfigBytes(bytes)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parseAndValidateConfigBytes parses a Gatus configuration file into a Config struct and validates its parameters
|
||||||
func parseAndValidateConfigBytes(yamlBytes []byte) (config *Config, err error) {
|
func parseAndValidateConfigBytes(yamlBytes []byte) (config *Config, err error) {
|
||||||
// Expand environment variables
|
// Expand environment variables
|
||||||
yamlBytes = []byte(os.ExpandEnv(string(yamlBytes)))
|
yamlBytes = []byte(os.ExpandEnv(string(yamlBytes)))
|
||||||
// Parse configuration file
|
// Parse configuration file
|
||||||
err = yaml.Unmarshal(yamlBytes, &config)
|
if err = yaml.Unmarshal(yamlBytes, &config); err != nil {
|
||||||
if err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Check if the configuration file at least has services configured
|
if config != nil && len(config.Services) > 0 { // XXX: Remove this in v5.0.0
|
||||||
if config == nil || config.Services == nil || len(config.Services) == 0 {
|
log.Println("WARNING: Your configuration is using 'services:', which is deprecated in favor of 'endpoints:'.")
|
||||||
err = ErrNoServiceInConfig
|
log.Println("WARNING: See https://github.com/TwiN/gatus/issues/191 for more information")
|
||||||
|
config.Endpoints = append(config.Endpoints, config.Services...)
|
||||||
|
config.Services = nil
|
||||||
|
}
|
||||||
|
// Check if the configuration file at least has endpoints configured
|
||||||
|
if config == nil || config.Endpoints == nil || len(config.Endpoints) == 0 {
|
||||||
|
err = ErrNoEndpointInConfig
|
||||||
} else {
|
} else {
|
||||||
// Note that the functions below may panic, and this is on purpose to prevent Gatus from starting with
|
validateAlertingConfig(config.Alerting, config.Endpoints, config.Debug)
|
||||||
// invalid configurations
|
|
||||||
validateAlertingConfig(config.Alerting, config.Services, config.Debug)
|
|
||||||
if err := validateSecurityConfig(config); err != nil {
|
if err := validateSecurityConfig(config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err := validateServicesConfig(config); err != nil {
|
if err := validateEndpointsConfig(config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err := validateWebConfig(config); err != nil {
|
if err := validateWebConfig(config); err != nil {
|
||||||
@@ -183,19 +194,10 @@ func validateStorageConfig(config *Config) error {
|
|||||||
config.Storage = &storage.Config{
|
config.Storage = &storage.Config{
|
||||||
Type: storage.TypeMemory,
|
Type: storage.TypeMemory,
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
err := storage.Initialize(config.Storage)
|
if err := config.Storage.ValidateAndSetDefaults(); err != nil {
|
||||||
if err != nil {
|
return err
|
||||||
return err
|
}
|
||||||
}
|
|
||||||
// Remove all ServiceStatus that represent services which no longer exist in the configuration
|
|
||||||
var keys []string
|
|
||||||
for _, service := range config.Services {
|
|
||||||
keys = append(keys, service.Key())
|
|
||||||
}
|
|
||||||
numberOfServiceStatusesDeleted := storage.Get().DeleteAllServiceStatusesNotInKeys(keys)
|
|
||||||
if numberOfServiceStatusesDeleted > 0 {
|
|
||||||
log.Printf("[config][validateStorageConfig] Deleted %d service statuses because their matching services no longer existed", numberOfServiceStatusesDeleted)
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -231,16 +233,16 @@ func validateWebConfig(config *Config) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateServicesConfig(config *Config) error {
|
func validateEndpointsConfig(config *Config) error {
|
||||||
for _, service := range config.Services {
|
for _, endpoint := range config.Endpoints {
|
||||||
if config.Debug {
|
if config.Debug {
|
||||||
log.Printf("[config][validateServicesConfig] Validating service '%s'", service.Name)
|
log.Printf("[config][validateEndpointsConfig] Validating endpoint '%s'", endpoint.Name)
|
||||||
}
|
}
|
||||||
if err := service.ValidateAndSetDefaults(); err != nil {
|
if err := endpoint.ValidateAndSetDefaults(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("[config][validateServicesConfig] Validated %d services", len(config.Services))
|
log.Printf("[config][validateEndpointsConfig] Validated %d endpoints", len(config.Endpoints))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -260,10 +262,10 @@ func validateSecurityConfig(config *Config) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// validateAlertingConfig validates the alerting configuration
|
// validateAlertingConfig validates the alerting configuration
|
||||||
// Note that the alerting configuration has to be validated before the service configuration, because the default alert
|
// Note that the alerting configuration has to be validated before the endpoint configuration, because the default alert
|
||||||
// returned by provider.AlertProvider.GetDefaultAlert() must be parsed before core.Service.ValidateAndSetDefaults()
|
// returned by provider.AlertProvider.GetDefaultAlert() must be parsed before core.Endpoint.ValidateAndSetDefaults()
|
||||||
// sets the default alert values when none are set.
|
// sets the default alert values when none are set.
|
||||||
func validateAlertingConfig(alertingConfig *alerting.Config, services []*core.Service, debug bool) {
|
func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.Endpoint, debug bool) {
|
||||||
if alertingConfig == nil {
|
if alertingConfig == nil {
|
||||||
log.Printf("[config][validateAlertingConfig] Alerting is not configured")
|
log.Printf("[config][validateAlertingConfig] Alerting is not configured")
|
||||||
return
|
return
|
||||||
@@ -271,8 +273,10 @@ func validateAlertingConfig(alertingConfig *alerting.Config, services []*core.Se
|
|||||||
alertTypes := []alert.Type{
|
alertTypes := []alert.Type{
|
||||||
alert.TypeCustom,
|
alert.TypeCustom,
|
||||||
alert.TypeDiscord,
|
alert.TypeDiscord,
|
||||||
|
alert.TypeEmail,
|
||||||
alert.TypeMattermost,
|
alert.TypeMattermost,
|
||||||
alert.TypeMessagebird,
|
alert.TypeMessagebird,
|
||||||
|
alert.TypeOpsgenie,
|
||||||
alert.TypePagerDuty,
|
alert.TypePagerDuty,
|
||||||
alert.TypeSlack,
|
alert.TypeSlack,
|
||||||
alert.TypeTeams,
|
alert.TypeTeams,
|
||||||
@@ -286,13 +290,13 @@ func validateAlertingConfig(alertingConfig *alerting.Config, services []*core.Se
|
|||||||
if alertProvider.IsValid() {
|
if alertProvider.IsValid() {
|
||||||
// Parse alerts with the provider's default alert
|
// Parse alerts with the provider's default alert
|
||||||
if alertProvider.GetDefaultAlert() != nil {
|
if alertProvider.GetDefaultAlert() != nil {
|
||||||
for _, service := range services {
|
for _, endpoint := range endpoints {
|
||||||
for alertIndex, serviceAlert := range service.Alerts {
|
for alertIndex, endpointAlert := range endpoint.Alerts {
|
||||||
if alertType == serviceAlert.Type {
|
if alertType == endpointAlert.Type {
|
||||||
if debug {
|
if debug {
|
||||||
log.Printf("[config][validateAlertingConfig] Parsing alert %d with provider's default alert for provider=%s in service=%s", alertIndex, alertType, service.Name)
|
log.Printf("[config][validateAlertingConfig] Parsing alert %d with provider's default alert for provider=%s in endpoint=%s", alertIndex, alertType, endpoint.Name)
|
||||||
}
|
}
|
||||||
provider.ParseWithDefaultAlert(alertProvider.GetDefaultAlert(), serviceAlert)
|
provider.ParseWithDefaultAlert(alertProvider.GetDefaultAlert(), endpointAlert)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v3/config/ui"
|
"github.com/TwiN/gatus/v3/config/ui"
|
||||||
"github.com/TwiN/gatus/v3/config/web"
|
"github.com/TwiN/gatus/v3/config/web"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestLoadFileThatDoesNotExist(t *testing.T) {
|
func TestLoadFileThatDoesNotExist(t *testing.T) {
|
||||||
@@ -44,7 +45,8 @@ func TestParseAndValidateConfigBytes(t *testing.T) {
|
|||||||
}()
|
}()
|
||||||
config, err := parseAndValidateConfigBytes([]byte(fmt.Sprintf(`
|
config, err := parseAndValidateConfigBytes([]byte(fmt.Sprintf(`
|
||||||
storage:
|
storage:
|
||||||
file: %s
|
type: sqlite
|
||||||
|
path: %s
|
||||||
maintenance:
|
maintenance:
|
||||||
enabled: true
|
enabled: true
|
||||||
start: 00:00
|
start: 00:00
|
||||||
@@ -52,7 +54,7 @@ maintenance:
|
|||||||
every: [Monday, Thursday]
|
every: [Monday, Thursday]
|
||||||
ui:
|
ui:
|
||||||
title: Test
|
title: Test
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
interval: 15s
|
interval: 15s
|
||||||
@@ -83,86 +85,89 @@ services:
|
|||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
}
|
}
|
||||||
|
if config.Storage == nil || config.Storage.Path != file || config.Storage.Type != storage.TypeSQLite {
|
||||||
|
t.Error("expected storage to be set to sqlite, got", config.Storage)
|
||||||
|
}
|
||||||
if config.UI == nil || config.UI.Title != "Test" {
|
if config.UI == nil || config.UI.Title != "Test" {
|
||||||
t.Error("Expected Config.UI.Title to be Test")
|
t.Error("Expected Config.UI.Title to be Test")
|
||||||
}
|
}
|
||||||
if mc := config.Maintenance; mc == nil || mc.Start != "00:00" || !mc.IsEnabled() || mc.Duration != 4*time.Hour || len(mc.Every) != 2 {
|
if mc := config.Maintenance; mc == nil || mc.Start != "00:00" || !mc.IsEnabled() || mc.Duration != 4*time.Hour || len(mc.Every) != 2 {
|
||||||
t.Error("Expected Config.Maintenance to be configured properly")
|
t.Error("Expected Config.Maintenance to be configured properly")
|
||||||
}
|
}
|
||||||
if len(config.Services) != 3 {
|
if len(config.Endpoints) != 3 {
|
||||||
t.Error("Should have returned two services")
|
t.Error("Should have returned two endpoints")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Method != "GET" {
|
if config.Endpoints[0].Method != "GET" {
|
||||||
t.Errorf("Method should have been %s (default)", "GET")
|
t.Errorf("Method should have been %s (default)", "GET")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 15*time.Second {
|
if config.Endpoints[0].Interval != 15*time.Second {
|
||||||
t.Errorf("Interval should have been %s", 15*time.Second)
|
t.Errorf("Interval should have been %s", 15*time.Second)
|
||||||
}
|
}
|
||||||
if config.Services[0].ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
if config.Endpoints[0].ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
||||||
t.Errorf("ClientConfig.Insecure should have been %v, got %v", true, config.Services[0].ClientConfig.Insecure)
|
t.Errorf("ClientConfig.Insecure should have been %v, got %v", true, config.Endpoints[0].ClientConfig.Insecure)
|
||||||
}
|
}
|
||||||
if config.Services[0].ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
if config.Endpoints[0].ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
||||||
t.Errorf("ClientConfig.IgnoreRedirect should have been %v, got %v", true, config.Services[0].ClientConfig.IgnoreRedirect)
|
t.Errorf("ClientConfig.IgnoreRedirect should have been %v, got %v", true, config.Endpoints[0].ClientConfig.IgnoreRedirect)
|
||||||
}
|
}
|
||||||
if config.Services[0].ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
if config.Endpoints[0].ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
||||||
t.Errorf("ClientConfig.Timeout should have been %v, got %v", client.GetDefaultConfig().Timeout, config.Services[0].ClientConfig.Timeout)
|
t.Errorf("ClientConfig.Timeout should have been %v, got %v", client.GetDefaultConfig().Timeout, config.Endpoints[0].ClientConfig.Timeout)
|
||||||
}
|
}
|
||||||
if len(config.Services[0].Conditions) != 1 {
|
if len(config.Endpoints[0].Conditions) != 1 {
|
||||||
t.Errorf("There should have been %d conditions", 1)
|
t.Errorf("There should have been %d conditions", 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[1].URL != "https://api.github.com/healthz" {
|
if config.Endpoints[1].URL != "https://api.github.com/healthz" {
|
||||||
t.Errorf("URL should have been %s", "https://api.github.com/healthz")
|
t.Errorf("URL should have been %s", "https://api.github.com/healthz")
|
||||||
}
|
}
|
||||||
if config.Services[1].Method != "GET" {
|
if config.Endpoints[1].Method != "GET" {
|
||||||
t.Errorf("Method should have been %s (default)", "GET")
|
t.Errorf("Method should have been %s (default)", "GET")
|
||||||
}
|
}
|
||||||
if config.Services[1].Interval != 60*time.Second {
|
if config.Endpoints[1].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if !config.Services[1].ClientConfig.Insecure {
|
if !config.Endpoints[1].ClientConfig.Insecure {
|
||||||
t.Errorf("ClientConfig.Insecure should have been %v, got %v", true, config.Services[1].ClientConfig.Insecure)
|
t.Errorf("ClientConfig.Insecure should have been %v, got %v", true, config.Endpoints[1].ClientConfig.Insecure)
|
||||||
}
|
}
|
||||||
if !config.Services[1].ClientConfig.IgnoreRedirect {
|
if !config.Endpoints[1].ClientConfig.IgnoreRedirect {
|
||||||
t.Errorf("ClientConfig.IgnoreRedirect should have been %v, got %v", true, config.Services[1].ClientConfig.IgnoreRedirect)
|
t.Errorf("ClientConfig.IgnoreRedirect should have been %v, got %v", true, config.Endpoints[1].ClientConfig.IgnoreRedirect)
|
||||||
}
|
}
|
||||||
if config.Services[1].ClientConfig.Timeout != 5*time.Second {
|
if config.Endpoints[1].ClientConfig.Timeout != 5*time.Second {
|
||||||
t.Errorf("ClientConfig.Timeout should have been %v, got %v", 5*time.Second, config.Services[1].ClientConfig.Timeout)
|
t.Errorf("ClientConfig.Timeout should have been %v, got %v", 5*time.Second, config.Endpoints[1].ClientConfig.Timeout)
|
||||||
}
|
}
|
||||||
if len(config.Services[1].Conditions) != 2 {
|
if len(config.Endpoints[1].Conditions) != 2 {
|
||||||
t.Errorf("There should have been %d conditions", 2)
|
t.Errorf("There should have been %d conditions", 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[2].URL != "https://example.com/" {
|
if config.Endpoints[2].URL != "https://example.com/" {
|
||||||
t.Errorf("URL should have been %s", "https://example.com/")
|
t.Errorf("URL should have been %s", "https://example.com/")
|
||||||
}
|
}
|
||||||
if config.Services[2].Method != "GET" {
|
if config.Endpoints[2].Method != "GET" {
|
||||||
t.Errorf("Method should have been %s (default)", "GET")
|
t.Errorf("Method should have been %s (default)", "GET")
|
||||||
}
|
}
|
||||||
if config.Services[2].Interval != 30*time.Minute {
|
if config.Endpoints[2].Interval != 30*time.Minute {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 30*time.Minute)
|
t.Errorf("Interval should have been %s, because it is the default value", 30*time.Minute)
|
||||||
}
|
}
|
||||||
if !config.Services[2].ClientConfig.Insecure {
|
if !config.Endpoints[2].ClientConfig.Insecure {
|
||||||
t.Errorf("ClientConfig.Insecure should have been %v, got %v", true, config.Services[2].ClientConfig.Insecure)
|
t.Errorf("ClientConfig.Insecure should have been %v, got %v", true, config.Endpoints[2].ClientConfig.Insecure)
|
||||||
}
|
}
|
||||||
if config.Services[2].ClientConfig.IgnoreRedirect {
|
if config.Endpoints[2].ClientConfig.IgnoreRedirect {
|
||||||
t.Errorf("ClientConfig.IgnoreRedirect should have been %v by default, got %v", false, config.Services[2].ClientConfig.IgnoreRedirect)
|
t.Errorf("ClientConfig.IgnoreRedirect should have been %v by default, got %v", false, config.Endpoints[2].ClientConfig.IgnoreRedirect)
|
||||||
}
|
}
|
||||||
if config.Services[2].ClientConfig.Timeout != 10*time.Second {
|
if config.Endpoints[2].ClientConfig.Timeout != 10*time.Second {
|
||||||
t.Errorf("ClientConfig.Timeout should have been %v by default, got %v", 10*time.Second, config.Services[2].ClientConfig.Timeout)
|
t.Errorf("ClientConfig.Timeout should have been %v by default, got %v", 10*time.Second, config.Endpoints[2].ClientConfig.Timeout)
|
||||||
}
|
}
|
||||||
if len(config.Services[2].Conditions) != 1 {
|
if len(config.Endpoints[2].Conditions) != 1 {
|
||||||
t.Errorf("There should have been %d conditions", 1)
|
t.Errorf("There should have been %d conditions", 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesDefault(t *testing.T) {
|
func TestParseAndValidateConfigBytesDefault(t *testing.T) {
|
||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -183,20 +188,20 @@ services:
|
|||||||
if config.Web.Port != web.DefaultPort {
|
if config.Web.Port != web.DefaultPort {
|
||||||
t.Errorf("Port should have been %d, because it is the default value", web.DefaultPort)
|
t.Errorf("Port should have been %d, because it is the default value", web.DefaultPort)
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if config.Services[0].ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
if config.Endpoints[0].ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
||||||
t.Errorf("ClientConfig.Insecure should have been %v by default, got %v", true, config.Services[0].ClientConfig.Insecure)
|
t.Errorf("ClientConfig.Insecure should have been %v by default, got %v", true, config.Endpoints[0].ClientConfig.Insecure)
|
||||||
}
|
}
|
||||||
if config.Services[0].ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
if config.Endpoints[0].ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
||||||
t.Errorf("ClientConfig.IgnoreRedirect should have been %v by default, got %v", true, config.Services[0].ClientConfig.IgnoreRedirect)
|
t.Errorf("ClientConfig.IgnoreRedirect should have been %v by default, got %v", true, config.Endpoints[0].ClientConfig.IgnoreRedirect)
|
||||||
}
|
}
|
||||||
if config.Services[0].ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
if config.Endpoints[0].ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
||||||
t.Errorf("ClientConfig.Timeout should have been %v by default, got %v", client.GetDefaultConfig().Timeout, config.Services[0].ClientConfig.Timeout)
|
t.Errorf("ClientConfig.Timeout should have been %v by default, got %v", client.GetDefaultConfig().Timeout, config.Endpoints[0].ClientConfig.Timeout)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,7 +209,7 @@ func TestParseAndValidateConfigBytesWithAddress(t *testing.T) {
|
|||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
web:
|
web:
|
||||||
address: 127.0.0.1
|
address: 127.0.0.1
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/actuator/health
|
url: https://twin.sh/actuator/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -219,10 +224,10 @@ services:
|
|||||||
if config.Metrics {
|
if config.Metrics {
|
||||||
t.Error("Metrics should've been false by default")
|
t.Error("Metrics should've been false by default")
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/actuator/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/actuator/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/actuator/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/actuator/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if config.Web.Address != "127.0.0.1" {
|
if config.Web.Address != "127.0.0.1" {
|
||||||
@@ -237,7 +242,7 @@ func TestParseAndValidateConfigBytesWithPort(t *testing.T) {
|
|||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
web:
|
web:
|
||||||
port: 12345
|
port: 12345
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -252,10 +257,10 @@ services:
|
|||||||
if config.Metrics {
|
if config.Metrics {
|
||||||
t.Error("Metrics should've been false by default")
|
t.Error("Metrics should've been false by default")
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if config.Web.Address != web.DefaultAddress {
|
if config.Web.Address != web.DefaultAddress {
|
||||||
@@ -271,7 +276,7 @@ func TestParseAndValidateConfigBytesWithPortAndHost(t *testing.T) {
|
|||||||
web:
|
web:
|
||||||
port: 12345
|
port: 12345
|
||||||
address: 127.0.0.1
|
address: 127.0.0.1
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -286,10 +291,10 @@ services:
|
|||||||
if config.Metrics {
|
if config.Metrics {
|
||||||
t.Error("Metrics should've been false by default")
|
t.Error("Metrics should've been false by default")
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if config.Web.Address != "127.0.0.1" {
|
if config.Web.Address != "127.0.0.1" {
|
||||||
@@ -305,7 +310,7 @@ func TestParseAndValidateConfigBytesWithInvalidPort(t *testing.T) {
|
|||||||
web:
|
web:
|
||||||
port: 65536
|
port: 65536
|
||||||
address: 127.0.0.1
|
address: 127.0.0.1
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -319,7 +324,7 @@ services:
|
|||||||
func TestParseAndValidateConfigBytesWithMetricsAndCustomUserAgentHeader(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithMetricsAndCustomUserAgentHeader(t *testing.T) {
|
||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
metrics: true
|
metrics: true
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
headers:
|
headers:
|
||||||
@@ -336,10 +341,10 @@ services:
|
|||||||
if !config.Metrics {
|
if !config.Metrics {
|
||||||
t.Error("Metrics should have been true")
|
t.Error("Metrics should have been true")
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if config.Web.Address != web.DefaultAddress {
|
if config.Web.Address != web.DefaultAddress {
|
||||||
@@ -348,7 +353,7 @@ services:
|
|||||||
if config.Web.Port != web.DefaultPort {
|
if config.Web.Port != web.DefaultPort {
|
||||||
t.Errorf("Port should have been %d, because it is the default value", web.DefaultPort)
|
t.Errorf("Port should have been %d, because it is the default value", web.DefaultPort)
|
||||||
}
|
}
|
||||||
if userAgent := config.Services[0].Headers["User-Agent"]; userAgent != "Test/2.0" {
|
if userAgent := config.Endpoints[0].Headers["User-Agent"]; userAgent != "Test/2.0" {
|
||||||
t.Errorf("User-Agent should've been %s, got %s", "Test/2.0", userAgent)
|
t.Errorf("User-Agent should've been %s, got %s", "Test/2.0", userAgent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -359,7 +364,7 @@ metrics: true
|
|||||||
web:
|
web:
|
||||||
address: 192.168.0.1
|
address: 192.168.0.1
|
||||||
port: 9090
|
port: 9090
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -380,13 +385,13 @@ services:
|
|||||||
if config.Web.Port != 9090 {
|
if config.Web.Port != 9090 {
|
||||||
t.Errorf("Port should have been %d, because it is specified in config", 9090)
|
t.Errorf("Port should have been %d, because it is specified in config", 9090)
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if userAgent := config.Services[0].Headers["User-Agent"]; userAgent != core.GatusUserAgent {
|
if userAgent := config.Endpoints[0].Headers["User-Agent"]; userAgent != core.GatusUserAgent {
|
||||||
t.Errorf("User-Agent should've been %s because it's the default value, got %s", core.GatusUserAgent, userAgent)
|
t.Errorf("User-Agent should've been %s because it's the default value, got %s", core.GatusUserAgent, userAgent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -402,8 +407,8 @@ badconfig:
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("An error should've been returned")
|
t.Error("An error should've been returned")
|
||||||
}
|
}
|
||||||
if err != ErrNoServiceInConfig {
|
if err != ErrNoEndpointInConfig {
|
||||||
t.Error("The error returned should have been of type ErrNoServiceInConfig")
|
t.Error("The error returned should have been of type ErrNoEndpointInConfig")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -436,7 +441,7 @@ alerting:
|
|||||||
teams:
|
teams:
|
||||||
webhook-url: "http://example.com"
|
webhook-url: "http://example.com"
|
||||||
|
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
alerts:
|
alerts:
|
||||||
@@ -477,116 +482,116 @@ services:
|
|||||||
if config.Alerting.Slack == nil || !config.Alerting.Slack.IsValid() {
|
if config.Alerting.Slack == nil || !config.Alerting.Slack.IsValid() {
|
||||||
t.Fatal("Slack alerting config should've been valid")
|
t.Fatal("Slack alerting config should've been valid")
|
||||||
}
|
}
|
||||||
// Services
|
// Endpoints
|
||||||
if len(config.Services) != 1 {
|
if len(config.Endpoints) != 1 {
|
||||||
t.Error("There should've been 1 service")
|
t.Error("There should've been 1 endpoint")
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if len(config.Services[0].Alerts) != 8 {
|
if len(config.Endpoints[0].Alerts) != 8 {
|
||||||
t.Fatal("There should've been 8 alerts configured")
|
t.Fatal("There should've been 8 alerts configured")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[0].Type != alert.TypeSlack {
|
if config.Endpoints[0].Alerts[0].Type != alert.TypeSlack {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Services[0].Alerts[0].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Endpoints[0].Alerts[0].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[0].IsEnabled() {
|
if !config.Endpoints[0].Alerts[0].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[0].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[0].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[0].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[0].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[0].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[0].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[0].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[0].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[1].Type != alert.TypePagerDuty {
|
if config.Endpoints[0].Alerts[1].Type != alert.TypePagerDuty {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypePagerDuty, config.Services[0].Alerts[1].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypePagerDuty, config.Endpoints[0].Alerts[1].Type)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].GetDescription() != "Healthcheck failed 7 times in a row" {
|
if config.Endpoints[0].Alerts[1].GetDescription() != "Healthcheck failed 7 times in a row" {
|
||||||
t.Errorf("The description of the alert should've been %s, but it was %s", "Healthcheck failed 7 times in a row", config.Services[0].Alerts[1].GetDescription())
|
t.Errorf("The description of the alert should've been %s, but it was %s", "Healthcheck failed 7 times in a row", config.Endpoints[0].Alerts[1].GetDescription())
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].FailureThreshold != 7 {
|
if config.Endpoints[0].Alerts[1].FailureThreshold != 7 {
|
||||||
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 7, config.Services[0].Alerts[1].FailureThreshold)
|
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 7, config.Endpoints[0].Alerts[1].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].SuccessThreshold != 5 {
|
if config.Endpoints[0].Alerts[1].SuccessThreshold != 5 {
|
||||||
t.Errorf("The success threshold of the alert should've been %d, but it was %d", 5, config.Services[0].Alerts[1].SuccessThreshold)
|
t.Errorf("The success threshold of the alert should've been %d, but it was %d", 5, config.Endpoints[0].Alerts[1].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[2].Type != alert.TypeMattermost {
|
if config.Endpoints[0].Alerts[2].Type != alert.TypeMattermost {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMattermost, config.Services[0].Alerts[2].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMattermost, config.Endpoints[0].Alerts[2].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[2].IsEnabled() {
|
if !config.Endpoints[0].Alerts[2].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[2].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[2].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[2].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[2].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[2].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[2].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[3].Type != alert.TypeMessagebird {
|
if config.Endpoints[0].Alerts[3].Type != alert.TypeMessagebird {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMessagebird, config.Services[0].Alerts[3].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMessagebird, config.Endpoints[0].Alerts[3].Type)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[3].IsEnabled() {
|
if config.Endpoints[0].Alerts[3].IsEnabled() {
|
||||||
t.Error("The alert should've been disabled")
|
t.Error("The alert should've been disabled")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[4].Type != alert.TypeDiscord {
|
if config.Endpoints[0].Alerts[4].Type != alert.TypeDiscord {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeDiscord, config.Services[0].Alerts[4].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeDiscord, config.Endpoints[0].Alerts[4].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[4].IsEnabled() {
|
if !config.Endpoints[0].Alerts[4].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[4].FailureThreshold != 10 {
|
if config.Endpoints[0].Alerts[4].FailureThreshold != 10 {
|
||||||
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 10, config.Services[0].Alerts[4].FailureThreshold)
|
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 10, config.Endpoints[0].Alerts[4].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[4].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[4].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[4].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[4].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[5].Type != alert.TypeTelegram {
|
if config.Endpoints[0].Alerts[5].Type != alert.TypeTelegram {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTelegram, config.Services[0].Alerts[5].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTelegram, config.Endpoints[0].Alerts[5].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[5].IsEnabled() {
|
if !config.Endpoints[0].Alerts[5].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[5].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[5].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[5].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[5].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[5].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[5].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[5].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[5].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[6].Type != alert.TypeTwilio {
|
if config.Endpoints[0].Alerts[6].Type != alert.TypeTwilio {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTwilio, config.Services[0].Alerts[6].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTwilio, config.Endpoints[0].Alerts[6].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[6].IsEnabled() {
|
if !config.Endpoints[0].Alerts[6].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[6].FailureThreshold != 12 {
|
if config.Endpoints[0].Alerts[6].FailureThreshold != 12 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 12, config.Services[0].Alerts[6].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 12, config.Endpoints[0].Alerts[6].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[6].SuccessThreshold != 15 {
|
if config.Endpoints[0].Alerts[6].SuccessThreshold != 15 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 15, config.Services[0].Alerts[6].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 15, config.Endpoints[0].Alerts[6].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[7].Type != alert.TypeTeams {
|
if config.Endpoints[0].Alerts[7].Type != alert.TypeTeams {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTeams, config.Services[0].Alerts[7].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTeams, config.Endpoints[0].Alerts[7].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[7].IsEnabled() {
|
if !config.Endpoints[0].Alerts[7].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[7].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[7].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[7].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[7].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[7].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[7].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[7].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[7].SuccessThreshold)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -642,7 +647,7 @@ alerting:
|
|||||||
default-alert:
|
default-alert:
|
||||||
enabled: true
|
enabled: true
|
||||||
|
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
alerts:
|
alerts:
|
||||||
@@ -651,7 +656,7 @@ services:
|
|||||||
- type: mattermost
|
- type: mattermost
|
||||||
- type: messagebird
|
- type: messagebird
|
||||||
- type: discord
|
- type: discord
|
||||||
success-threshold: 2 # test service alert override
|
success-threshold: 2 # test endpoint alert override
|
||||||
- type: telegram
|
- type: telegram
|
||||||
- type: twilio
|
- type: twilio
|
||||||
- type: teams
|
- type: teams
|
||||||
@@ -754,119 +759,119 @@ services:
|
|||||||
t.Fatal("Teams.GetDefaultAlert() shouldn't have returned nil")
|
t.Fatal("Teams.GetDefaultAlert() shouldn't have returned nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Services
|
// Endpoints
|
||||||
if len(config.Services) != 1 {
|
if len(config.Endpoints) != 1 {
|
||||||
t.Error("There should've been 1 service")
|
t.Error("There should've been 1 endpoint")
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if len(config.Services[0].Alerts) != 8 {
|
if len(config.Endpoints[0].Alerts) != 8 {
|
||||||
t.Fatal("There should've been 8 alerts configured")
|
t.Fatal("There should've been 8 alerts configured")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[0].Type != alert.TypeSlack {
|
if config.Endpoints[0].Alerts[0].Type != alert.TypeSlack {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Services[0].Alerts[0].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Endpoints[0].Alerts[0].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[0].IsEnabled() {
|
if !config.Endpoints[0].Alerts[0].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[0].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[0].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[0].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[0].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[0].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[0].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[0].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[0].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[1].Type != alert.TypePagerDuty {
|
if config.Endpoints[0].Alerts[1].Type != alert.TypePagerDuty {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypePagerDuty, config.Services[0].Alerts[1].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypePagerDuty, config.Endpoints[0].Alerts[1].Type)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].GetDescription() != "default description" {
|
if config.Endpoints[0].Alerts[1].GetDescription() != "default description" {
|
||||||
t.Errorf("The description of the alert should've been %s, but it was %s", "default description", config.Services[0].Alerts[1].GetDescription())
|
t.Errorf("The description of the alert should've been %s, but it was %s", "default description", config.Endpoints[0].Alerts[1].GetDescription())
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].FailureThreshold != 7 {
|
if config.Endpoints[0].Alerts[1].FailureThreshold != 7 {
|
||||||
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 7, config.Services[0].Alerts[1].FailureThreshold)
|
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 7, config.Endpoints[0].Alerts[1].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].SuccessThreshold != 5 {
|
if config.Endpoints[0].Alerts[1].SuccessThreshold != 5 {
|
||||||
t.Errorf("The success threshold of the alert should've been %d, but it was %d", 5, config.Services[0].Alerts[1].SuccessThreshold)
|
t.Errorf("The success threshold of the alert should've been %d, but it was %d", 5, config.Endpoints[0].Alerts[1].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[2].Type != alert.TypeMattermost {
|
if config.Endpoints[0].Alerts[2].Type != alert.TypeMattermost {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMattermost, config.Services[0].Alerts[2].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMattermost, config.Endpoints[0].Alerts[2].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[2].IsEnabled() {
|
if !config.Endpoints[0].Alerts[2].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[2].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[2].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[2].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[2].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[2].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[2].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[3].Type != alert.TypeMessagebird {
|
if config.Endpoints[0].Alerts[3].Type != alert.TypeMessagebird {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMessagebird, config.Services[0].Alerts[3].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeMessagebird, config.Endpoints[0].Alerts[3].Type)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[3].IsEnabled() {
|
if config.Endpoints[0].Alerts[3].IsEnabled() {
|
||||||
t.Error("The alert should've been disabled")
|
t.Error("The alert should've been disabled")
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[3].IsSendingOnResolved() {
|
if !config.Endpoints[0].Alerts[3].IsSendingOnResolved() {
|
||||||
t.Error("The alert should be sending on resolve")
|
t.Error("The alert should be sending on resolve")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[4].Type != alert.TypeDiscord {
|
if config.Endpoints[0].Alerts[4].Type != alert.TypeDiscord {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeDiscord, config.Services[0].Alerts[4].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeDiscord, config.Endpoints[0].Alerts[4].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[4].IsEnabled() {
|
if !config.Endpoints[0].Alerts[4].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[4].FailureThreshold != 10 {
|
if config.Endpoints[0].Alerts[4].FailureThreshold != 10 {
|
||||||
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 10, config.Services[0].Alerts[4].FailureThreshold)
|
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 10, config.Endpoints[0].Alerts[4].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[4].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[4].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[4].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[4].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[5].Type != alert.TypeTelegram {
|
if config.Endpoints[0].Alerts[5].Type != alert.TypeTelegram {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTelegram, config.Services[0].Alerts[5].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTelegram, config.Endpoints[0].Alerts[5].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[5].IsEnabled() {
|
if !config.Endpoints[0].Alerts[5].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[5].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[5].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[5].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[5].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[5].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[5].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[5].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[5].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[6].Type != alert.TypeTwilio {
|
if config.Endpoints[0].Alerts[6].Type != alert.TypeTwilio {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTwilio, config.Services[0].Alerts[6].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTwilio, config.Endpoints[0].Alerts[6].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[6].IsEnabled() {
|
if !config.Endpoints[0].Alerts[6].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[6].FailureThreshold != 12 {
|
if config.Endpoints[0].Alerts[6].FailureThreshold != 12 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 12, config.Services[0].Alerts[6].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 12, config.Endpoints[0].Alerts[6].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[6].SuccessThreshold != 15 {
|
if config.Endpoints[0].Alerts[6].SuccessThreshold != 15 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 15, config.Services[0].Alerts[6].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 15, config.Endpoints[0].Alerts[6].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Services[0].Alerts[7].Type != alert.TypeTeams {
|
if config.Endpoints[0].Alerts[7].Type != alert.TypeTeams {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTeams, config.Services[0].Alerts[7].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeTeams, config.Endpoints[0].Alerts[7].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[7].IsEnabled() {
|
if !config.Endpoints[0].Alerts[7].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[7].FailureThreshold != 3 {
|
if config.Endpoints[0].Alerts[7].FailureThreshold != 3 {
|
||||||
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Services[0].Alerts[7].FailureThreshold)
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[7].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[7].SuccessThreshold != 2 {
|
if config.Endpoints[0].Alerts[7].SuccessThreshold != 2 {
|
||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Services[0].Alerts[7].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[7].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -875,12 +880,12 @@ func TestParseAndValidateConfigBytesWithAlertingAndDefaultAlertAndMultipleAlerts
|
|||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
alerting:
|
alerting:
|
||||||
slack:
|
slack:
|
||||||
webhook-url: "http://example.com"
|
webhook-url: "https://example.com"
|
||||||
default-alert:
|
default-alert:
|
||||||
enabled: true
|
enabled: true
|
||||||
description: "description"
|
description: "description"
|
||||||
|
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
alerts:
|
alerts:
|
||||||
@@ -908,45 +913,45 @@ services:
|
|||||||
if config.Alerting.Slack == nil || !config.Alerting.Slack.IsValid() {
|
if config.Alerting.Slack == nil || !config.Alerting.Slack.IsValid() {
|
||||||
t.Fatal("Slack alerting config should've been valid")
|
t.Fatal("Slack alerting config should've been valid")
|
||||||
}
|
}
|
||||||
// Services
|
// Endpoints
|
||||||
if len(config.Services) != 1 {
|
if len(config.Endpoints) != 1 {
|
||||||
t.Error("There should've been 2 services")
|
t.Error("There should've been 2 endpoints")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[0].Type != alert.TypeSlack {
|
if config.Endpoints[0].Alerts[0].Type != alert.TypeSlack {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Services[0].Alerts[0].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Endpoints[0].Alerts[0].Type)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].Type != alert.TypeSlack {
|
if config.Endpoints[0].Alerts[1].Type != alert.TypeSlack {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Services[0].Alerts[1].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Endpoints[0].Alerts[1].Type)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].Type != alert.TypeSlack {
|
if config.Endpoints[0].Alerts[2].Type != alert.TypeSlack {
|
||||||
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Services[0].Alerts[2].Type)
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeSlack, config.Endpoints[0].Alerts[2].Type)
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[0].IsEnabled() {
|
if !config.Endpoints[0].Alerts[0].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if !config.Services[0].Alerts[1].IsEnabled() {
|
if !config.Endpoints[0].Alerts[1].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].IsEnabled() {
|
if config.Endpoints[0].Alerts[2].IsEnabled() {
|
||||||
t.Error("The alert should've been disabled")
|
t.Error("The alert should've been disabled")
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[0].GetDescription() != "description" {
|
if config.Endpoints[0].Alerts[0].GetDescription() != "description" {
|
||||||
t.Errorf("The description of the alert should've been %s, but it was %s", "description", config.Services[0].Alerts[0].GetDescription())
|
t.Errorf("The description of the alert should've been %s, but it was %s", "description", config.Endpoints[0].Alerts[0].GetDescription())
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].GetDescription() != "wow" {
|
if config.Endpoints[0].Alerts[1].GetDescription() != "wow" {
|
||||||
t.Errorf("The description of the alert should've been %s, but it was %s", "description", config.Services[0].Alerts[1].GetDescription())
|
t.Errorf("The description of the alert should've been %s, but it was %s", "description", config.Endpoints[0].Alerts[1].GetDescription())
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].GetDescription() != "description" {
|
if config.Endpoints[0].Alerts[2].GetDescription() != "description" {
|
||||||
t.Errorf("The description of the alert should've been %s, but it was %s", "description", config.Services[0].Alerts[2].GetDescription())
|
t.Errorf("The description of the alert should've been %s, but it was %s", "description", config.Endpoints[0].Alerts[2].GetDescription())
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[0].FailureThreshold != 10 {
|
if config.Endpoints[0].Alerts[0].FailureThreshold != 10 {
|
||||||
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 10, config.Services[0].Alerts[0].FailureThreshold)
|
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 10, config.Endpoints[0].Alerts[0].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[1].FailureThreshold != 20 {
|
if config.Endpoints[0].Alerts[1].FailureThreshold != 20 {
|
||||||
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 20, config.Services[0].Alerts[1].FailureThreshold)
|
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 20, config.Endpoints[0].Alerts[1].FailureThreshold)
|
||||||
}
|
}
|
||||||
if config.Services[0].Alerts[2].FailureThreshold != 30 {
|
if config.Endpoints[0].Alerts[2].FailureThreshold != 30 {
|
||||||
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 30, config.Services[0].Alerts[2].FailureThreshold)
|
t.Errorf("The failure threshold of the alert should've been %d, but it was %d", 30, config.Endpoints[0].Alerts[2].FailureThreshold)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -955,7 +960,7 @@ func TestParseAndValidateConfigBytesWithInvalidPagerDutyAlertingConfig(t *testin
|
|||||||
alerting:
|
alerting:
|
||||||
pagerduty:
|
pagerduty:
|
||||||
integration-key: "INVALID_KEY"
|
integration-key: "INVALID_KEY"
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
alerts:
|
alerts:
|
||||||
@@ -987,9 +992,9 @@ alerting:
|
|||||||
url: "https://example.com"
|
url: "https://example.com"
|
||||||
body: |
|
body: |
|
||||||
{
|
{
|
||||||
"text": "[ALERT_TRIGGERED_OR_RESOLVED]: [SERVICE_NAME] - [ALERT_DESCRIPTION]"
|
"text": "[ALERT_TRIGGERED_OR_RESOLVED]: [ENDPOINT_NAME] - [ALERT_DESCRIPTION]"
|
||||||
}
|
}
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
alerts:
|
alerts:
|
||||||
@@ -1033,8 +1038,8 @@ alerting:
|
|||||||
RESOLVED: "operational"
|
RESOLVED: "operational"
|
||||||
url: "https://example.com"
|
url: "https://example.com"
|
||||||
insecure: true
|
insecure: true
|
||||||
body: "[ALERT_TRIGGERED_OR_RESOLVED]: [SERVICE_NAME] - [ALERT_DESCRIPTION]"
|
body: "[ALERT_TRIGGERED_OR_RESOLVED]: [ENDPOINT_NAME] - [ALERT_DESCRIPTION]"
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
alerts:
|
alerts:
|
||||||
@@ -1073,8 +1078,8 @@ alerting:
|
|||||||
ALERT_TRIGGERED_OR_RESOLVED:
|
ALERT_TRIGGERED_OR_RESOLVED:
|
||||||
TRIGGERED: "partial_outage"
|
TRIGGERED: "partial_outage"
|
||||||
url: "https://example.com"
|
url: "https://example.com"
|
||||||
body: "[ALERT_TRIGGERED_OR_RESOLVED]: [SERVICE_NAME] - [ALERT_DESCRIPTION]"
|
body: "[ALERT_TRIGGERED_OR_RESOLVED]: [ENDPOINT_NAME] - [ALERT_DESCRIPTION]"
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
alerts:
|
alerts:
|
||||||
@@ -1105,15 +1110,15 @@ services:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesWithInvalidServiceName(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithInvalidEndpointName(t *testing.T) {
|
||||||
_, err := parseAndValidateConfigBytes([]byte(`
|
_, err := parseAndValidateConfigBytes([]byte(`
|
||||||
services:
|
endpoints:
|
||||||
- name: ""
|
- name: ""
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != core.ErrServiceWithNoName {
|
if err != core.ErrEndpointWithNoName {
|
||||||
t.Error("should've returned an error")
|
t.Error("should've returned an error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1122,7 +1127,7 @@ func TestParseAndValidateConfigBytesWithInvalidStorageConfig(t *testing.T) {
|
|||||||
_, err := parseAndValidateConfigBytes([]byte(`
|
_, err := parseAndValidateConfigBytes([]byte(`
|
||||||
storage:
|
storage:
|
||||||
type: sqlite
|
type: sqlite
|
||||||
services:
|
endpoints:
|
||||||
- name: example
|
- name: example
|
||||||
url: https://example.org
|
url: https://example.org
|
||||||
conditions:
|
conditions:
|
||||||
@@ -1137,7 +1142,7 @@ func TestParseAndValidateConfigBytesWithInvalidYAML(t *testing.T) {
|
|||||||
_, err := parseAndValidateConfigBytes([]byte(`
|
_, err := parseAndValidateConfigBytes([]byte(`
|
||||||
storage:
|
storage:
|
||||||
invalid yaml
|
invalid yaml
|
||||||
services:
|
endpoints:
|
||||||
- name: example
|
- name: example
|
||||||
url: https://example.org
|
url: https://example.org
|
||||||
conditions:
|
conditions:
|
||||||
@@ -1154,7 +1159,7 @@ security:
|
|||||||
basic:
|
basic:
|
||||||
username: "admin"
|
username: "admin"
|
||||||
password-sha512: "invalid-sha512-hash"
|
password-sha512: "invalid-sha512-hash"
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -1173,7 +1178,7 @@ security:
|
|||||||
basic:
|
basic:
|
||||||
username: "%s"
|
username: "%s"
|
||||||
password-sha512: "%s"
|
password-sha512: "%s"
|
||||||
services:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
conditions:
|
conditions:
|
||||||
@@ -1202,10 +1207,10 @@ services:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesWithNoServicesOrAutoDiscovery(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithNoEndpointsOrAutoDiscovery(t *testing.T) {
|
||||||
_, err := parseAndValidateConfigBytes([]byte(``))
|
_, err := parseAndValidateConfigBytes([]byte(``))
|
||||||
if err != ErrNoServiceInConfig {
|
if err != ErrNoEndpointInConfig {
|
||||||
t.Error("The error returned should have been of type ErrNoServiceInConfig")
|
t.Error("The error returned should have been of type ErrNoEndpointInConfig")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1249,3 +1254,101 @@ func TestGetAlertingProviderByAlertType(t *testing.T) {
|
|||||||
t.Error("expected Teams configuration")
|
t.Error("expected Teams configuration")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// XXX: Remove this in v5.0.0
|
||||||
|
func TestParseAndValidateConfigBytes_backwardCompatibleWithServices(t *testing.T) {
|
||||||
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
|
services:
|
||||||
|
- name: website
|
||||||
|
url: https://twin.sh/actuator/health
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
`))
|
||||||
|
if err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
if config == nil {
|
||||||
|
t.Fatal("Config shouldn't have been nil")
|
||||||
|
}
|
||||||
|
if config.Endpoints[0].URL != "https://twin.sh/actuator/health" {
|
||||||
|
t.Errorf("URL should have been %s", "https://twin.sh/actuator/health")
|
||||||
|
}
|
||||||
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// XXX: Remove this in v5.0.0
|
||||||
|
func TestParseAndValidateConfigBytes_backwardCompatibleMergeServicesInEndpoints(t *testing.T) {
|
||||||
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
|
services:
|
||||||
|
- name: website1
|
||||||
|
url: https://twin.sh/actuator/health
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
endpoints:
|
||||||
|
- name: website2
|
||||||
|
url: https://twin.sh/actuator/health
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
`))
|
||||||
|
if err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
if config == nil {
|
||||||
|
t.Fatal("Config shouldn't have been nil")
|
||||||
|
}
|
||||||
|
if len(config.Endpoints) != 2 {
|
||||||
|
t.Error("services should've been merged in endpoints")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// XXX: Remove this in v4.0.0
|
||||||
|
func TestParseAndValidateConfigBytes_backwardCompatibleWithStorageFile(t *testing.T) {
|
||||||
|
file := t.TempDir() + "/test.db"
|
||||||
|
config, err := parseAndValidateConfigBytes([]byte(fmt.Sprintf(`
|
||||||
|
storage:
|
||||||
|
type: sqlite
|
||||||
|
file: %s
|
||||||
|
|
||||||
|
endpoints:
|
||||||
|
- name: website
|
||||||
|
url: https://twin.sh/actuator/health
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
`, file)))
|
||||||
|
if err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
if config == nil {
|
||||||
|
t.Fatal("Config shouldn't have been nil")
|
||||||
|
}
|
||||||
|
if config.Storage == nil || config.Storage.Path != file || config.Storage.Type != storage.TypeSQLite {
|
||||||
|
t.Error("expected storage to be set to sqlite, got", config.Storage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// XXX: Remove this in v4.0.0
|
||||||
|
func TestParseAndValidateConfigBytes_backwardCompatibleWithStorageTypeMemoryAndFile(t *testing.T) {
|
||||||
|
file := t.TempDir() + "/test.db"
|
||||||
|
config, err := parseAndValidateConfigBytes([]byte(fmt.Sprintf(`
|
||||||
|
storage:
|
||||||
|
type: memory
|
||||||
|
file: %s
|
||||||
|
|
||||||
|
endpoints:
|
||||||
|
- name: website
|
||||||
|
url: https://twin.sh/actuator/health
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
`, file)))
|
||||||
|
if err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
if config == nil {
|
||||||
|
t.Fatal("Config shouldn't have been nil")
|
||||||
|
}
|
||||||
|
if config.Storage == nil || config.Storage.Path != file || config.Storage.Type != storage.TypeMemory {
|
||||||
|
t.Error("expected storage to be set to memory, got", config.Storage)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,7 +39,6 @@ type Config struct {
|
|||||||
Every []string `yaml:"every"`
|
Every []string `yaml:"every"`
|
||||||
|
|
||||||
durationToStartFromMidnight time.Duration
|
durationToStartFromMidnight time.Duration
|
||||||
timeLocation *time.Location
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDefaultConfig() *Config {
|
func GetDefaultConfig() *Config {
|
||||||
@@ -89,7 +88,7 @@ func (c *Config) ValidateAndSetDefaults() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsUnderMaintenance checks whether the services that Gatus monitors are within the configured maintenance window
|
// IsUnderMaintenance checks whether the endpoints that Gatus monitors are within the configured maintenance window
|
||||||
func (c Config) IsUnderMaintenance() bool {
|
func (c Config) IsUnderMaintenance() bool {
|
||||||
if !c.IsEnabled() {
|
if !c.IsEnabled() {
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
defaultTitle = "Health Dashboard | Gatus"
|
defaultTitle = "Health Dashboard | Gatus"
|
||||||
defaultLogo = ""
|
defaultHeader = "Health Status"
|
||||||
|
defaultLogo = ""
|
||||||
|
defaultLink = ""
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -18,15 +20,19 @@ var (
|
|||||||
|
|
||||||
// Config is the configuration for the UI of Gatus
|
// Config is the configuration for the UI of Gatus
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Title string `yaml:"title"` // Title of the page
|
Title string `yaml:"title,omitempty"` // Title of the page
|
||||||
Logo string `yaml:"logo"` // Logo to display on the page
|
Header string `yaml:"header,omitempty"` // Header is the text at the top of the page
|
||||||
|
Logo string `yaml:"logo,omitempty"` // Logo to display on the page
|
||||||
|
Link string `yaml:"link,omitempty"` // Link to open when clicking on the logo
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultConfig returns a Config struct with the default values
|
// GetDefaultConfig returns a Config struct with the default values
|
||||||
func GetDefaultConfig() *Config {
|
func GetDefaultConfig() *Config {
|
||||||
return &Config{
|
return &Config{
|
||||||
Title: defaultTitle,
|
Title: defaultTitle,
|
||||||
Logo: defaultLogo,
|
Header: defaultHeader,
|
||||||
|
Logo: defaultLogo,
|
||||||
|
Link: defaultLink,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,6 +41,12 @@ func (cfg *Config) ValidateAndSetDefaults() error {
|
|||||||
if len(cfg.Title) == 0 {
|
if len(cfg.Title) == 0 {
|
||||||
cfg.Title = defaultTitle
|
cfg.Title = defaultTitle
|
||||||
}
|
}
|
||||||
|
if len(cfg.Header) == 0 {
|
||||||
|
cfg.Header = defaultHeader
|
||||||
|
}
|
||||||
|
if len(cfg.Header) == 0 {
|
||||||
|
cfg.Header = defaultLink
|
||||||
|
}
|
||||||
t, err := template.ParseFiles(StaticFolder + "/index.html")
|
t, err := template.ParseFiles(StaticFolder + "/index.html")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -9,10 +9,21 @@ func TestConfig_ValidateAndSetDefaults(t *testing.T) {
|
|||||||
defer func() {
|
defer func() {
|
||||||
StaticFolder = "./web/static"
|
StaticFolder = "./web/static"
|
||||||
}()
|
}()
|
||||||
cfg := &Config{Title: ""}
|
cfg := &Config{
|
||||||
|
Title: "",
|
||||||
|
Header: "",
|
||||||
|
Logo: "",
|
||||||
|
Link: "",
|
||||||
|
}
|
||||||
if err := cfg.ValidateAndSetDefaults(); err != nil {
|
if err := cfg.ValidateAndSetDefaults(); err != nil {
|
||||||
t.Error("expected no error, got", err.Error())
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
|
if cfg.Title != defaultTitle {
|
||||||
|
t.Errorf("expected title to be %s, got %s", defaultTitle, cfg.Title)
|
||||||
|
}
|
||||||
|
if cfg.Header != defaultHeader {
|
||||||
|
t.Errorf("expected header to be %s, got %s", defaultHeader, cfg.Header)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetDefaultConfig(t *testing.T) {
|
func TestGetDefaultConfig(t *testing.T) {
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// DefaultAddress is the default address the service will bind to
|
// DefaultAddress is the default address the application will bind to
|
||||||
DefaultAddress = "0.0.0.0"
|
DefaultAddress = "0.0.0.0"
|
||||||
|
|
||||||
// DefaultPort is the default port the service will listen on
|
// DefaultPort is the default port the application will listen on
|
||||||
DefaultPort = 8080
|
DefaultPort = 8080
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ func TestHandle(t *testing.T) {
|
|||||||
Address: "0.0.0.0",
|
Address: "0.0.0.0",
|
||||||
Port: rand.Intn(65534),
|
Port: rand.Intn(65534),
|
||||||
},
|
},
|
||||||
Services: []*core.Service{
|
Endpoints: []*core.Endpoint{
|
||||||
{
|
{
|
||||||
Name: "frontend",
|
Name: "frontend",
|
||||||
Group: "core",
|
Group: "core",
|
||||||
@@ -34,7 +34,7 @@ func TestHandle(t *testing.T) {
|
|||||||
defer os.Clearenv()
|
defer os.Clearenv()
|
||||||
Handle(cfg.Security, cfg.Web, cfg.UI, cfg.Metrics)
|
Handle(cfg.Security, cfg.Web, cfg.UI, cfg.Metrics)
|
||||||
defer Shutdown()
|
defer Shutdown()
|
||||||
request, _ := http.NewRequest("GET", "/health", nil)
|
request, _ := http.NewRequest("GET", "/health", http.NoBody)
|
||||||
responseRecorder := httptest.NewRecorder()
|
responseRecorder := httptest.NewRecorder()
|
||||||
server.Handler.ServeHTTP(responseRecorder, request)
|
server.Handler.ServeHTTP(responseRecorder, request)
|
||||||
if responseRecorder.Code != http.StatusOK {
|
if responseRecorder.Code != http.StatusOK {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwiN/gatus/v3/storage/store/common"
|
"github.com/TwiN/gatus/v3/storage/store/common"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
)
|
)
|
||||||
@@ -21,7 +21,7 @@ const (
|
|||||||
badgeColorHexVeryBad = "#c7130a"
|
badgeColorHexVeryBad = "#c7130a"
|
||||||
)
|
)
|
||||||
|
|
||||||
// UptimeBadge handles the automatic generation of badge based on the group name and service name passed.
|
// UptimeBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
||||||
//
|
//
|
||||||
// Valid values for {duration}: 7d, 24h, 1h
|
// Valid values for {duration}: 7d, 24h, 1h
|
||||||
func UptimeBadge(writer http.ResponseWriter, request *http.Request) {
|
func UptimeBadge(writer http.ResponseWriter, request *http.Request) {
|
||||||
@@ -40,27 +40,25 @@ func UptimeBadge(writer http.ResponseWriter, request *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
key := variables["key"]
|
key := variables["key"]
|
||||||
uptime, err := storage.Get().GetUptimeByKey(key, from, time.Now())
|
uptime, err := store.Get().GetUptimeByKey(key, from, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrServiceNotFound {
|
if err == common.ErrEndpointNotFound {
|
||||||
writer.WriteHeader(http.StatusNotFound)
|
http.Error(writer, err.Error(), http.StatusNotFound)
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if err == common.ErrInvalidTimeRange {
|
||||||
writer.WriteHeader(http.StatusBadRequest)
|
http.Error(writer, err.Error(), http.StatusBadRequest)
|
||||||
} else {
|
} else {
|
||||||
writer.WriteHeader(http.StatusInternalServerError)
|
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
_, _ = writer.Write([]byte(err.Error()))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
formattedDate := time.Now().Format(http.TimeFormat)
|
|
||||||
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
||||||
writer.Header().Set("Date", formattedDate)
|
|
||||||
writer.Header().Set("Expires", formattedDate)
|
|
||||||
writer.Header().Set("Content-Type", "image/svg+xml")
|
writer.Header().Set("Content-Type", "image/svg+xml")
|
||||||
|
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||||
|
writer.Header().Set("Expires", "0")
|
||||||
|
writer.WriteHeader(http.StatusOK)
|
||||||
_, _ = writer.Write(generateUptimeBadgeSVG(duration, uptime))
|
_, _ = writer.Write(generateUptimeBadgeSVG(duration, uptime))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResponseTimeBadge handles the automatic generation of badge based on the group name and service name passed.
|
// ResponseTimeBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
||||||
//
|
//
|
||||||
// Valid values for {duration}: 7d, 24h, 1h
|
// Valid values for {duration}: 7d, 24h, 1h
|
||||||
func ResponseTimeBadge(writer http.ResponseWriter, request *http.Request) {
|
func ResponseTimeBadge(writer http.ResponseWriter, request *http.Request) {
|
||||||
@@ -79,23 +77,21 @@ func ResponseTimeBadge(writer http.ResponseWriter, request *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
key := variables["key"]
|
key := variables["key"]
|
||||||
averageResponseTime, err := storage.Get().GetAverageResponseTimeByKey(key, from, time.Now())
|
averageResponseTime, err := store.Get().GetAverageResponseTimeByKey(key, from, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrServiceNotFound {
|
if err == common.ErrEndpointNotFound {
|
||||||
writer.WriteHeader(http.StatusNotFound)
|
http.Error(writer, err.Error(), http.StatusNotFound)
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if err == common.ErrInvalidTimeRange {
|
||||||
writer.WriteHeader(http.StatusBadRequest)
|
http.Error(writer, err.Error(), http.StatusBadRequest)
|
||||||
} else {
|
} else {
|
||||||
writer.WriteHeader(http.StatusInternalServerError)
|
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
_, _ = writer.Write([]byte(err.Error()))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
formattedDate := time.Now().Format(http.TimeFormat)
|
|
||||||
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
||||||
writer.Header().Set("Date", formattedDate)
|
|
||||||
writer.Header().Set("Expires", formattedDate)
|
|
||||||
writer.Header().Set("Content-Type", "image/svg+xml")
|
writer.Header().Set("Content-Type", "image/svg+xml")
|
||||||
|
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||||
|
writer.Header().Set("Expires", "0")
|
||||||
|
writer.WriteHeader(http.StatusOK)
|
||||||
_, _ = writer.Write(generateResponseTimeBadgeSVG(duration, averageResponseTime))
|
_, _ = writer.Write(generateResponseTimeBadgeSVG(duration, averageResponseTime))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,16 +9,16 @@ import (
|
|||||||
|
|
||||||
"github.com/TwiN/gatus/v3/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwiN/gatus/v3/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwiN/gatus/v3/watchdog"
|
"github.com/TwiN/gatus/v3/watchdog"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestUptimeBadge(t *testing.T) {
|
func TestUptimeBadge(t *testing.T) {
|
||||||
defer storage.Get().Clear()
|
defer store.Get().Clear()
|
||||||
defer cache.Clear()
|
defer cache.Clear()
|
||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Metrics: true,
|
Metrics: true,
|
||||||
Services: []*core.Service{
|
Endpoints: []*core.Endpoint{
|
||||||
{
|
{
|
||||||
Name: "frontend",
|
Name: "frontend",
|
||||||
Group: "core",
|
Group: "core",
|
||||||
@@ -29,8 +29,8 @@ func TestUptimeBadge(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
@@ -41,63 +41,73 @@ func TestUptimeBadge(t *testing.T) {
|
|||||||
scenarios := []Scenario{
|
scenarios := []Scenario{
|
||||||
{
|
{
|
||||||
Name: "badge-uptime-1h",
|
Name: "badge-uptime-1h",
|
||||||
Path: "/api/v1/services/core_frontend/uptimes/1h/badge.svg",
|
Path: "/api/v1/endpoints/core_frontend/uptimes/1h/badge.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-uptime-24h",
|
Name: "badge-uptime-24h",
|
||||||
Path: "/api/v1/services/core_backend/uptimes/24h/badge.svg",
|
Path: "/api/v1/endpoints/core_backend/uptimes/24h/badge.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-uptime-7d",
|
Name: "badge-uptime-7d",
|
||||||
Path: "/api/v1/services/core_frontend/uptimes/7d/badge.svg",
|
Path: "/api/v1/endpoints/core_frontend/uptimes/7d/badge.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-uptime-with-invalid-duration",
|
Name: "badge-uptime-with-invalid-duration",
|
||||||
Path: "/api/v1/services/core_backend/uptimes/3d/badge.svg",
|
Path: "/api/v1/endpoints/core_backend/uptimes/3d/badge.svg",
|
||||||
ExpectedCode: http.StatusBadRequest,
|
ExpectedCode: http.StatusBadRequest,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-uptime-for-invalid-key",
|
Name: "badge-uptime-for-invalid-key",
|
||||||
Path: "/api/v1/services/invalid_key/uptimes/7d/badge.svg",
|
Path: "/api/v1/endpoints/invalid_key/uptimes/7d/badge.svg",
|
||||||
ExpectedCode: http.StatusNotFound,
|
ExpectedCode: http.StatusNotFound,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-response-time-1h",
|
Name: "badge-response-time-1h",
|
||||||
Path: "/api/v1/services/core_frontend/response-times/1h/badge.svg",
|
Path: "/api/v1/endpoints/core_frontend/response-times/1h/badge.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-response-time-24h",
|
Name: "badge-response-time-24h",
|
||||||
Path: "/api/v1/services/core_backend/response-times/24h/badge.svg",
|
Path: "/api/v1/endpoints/core_backend/response-times/24h/badge.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-response-time-7d",
|
Name: "badge-response-time-7d",
|
||||||
Path: "/api/v1/services/core_frontend/response-times/7d/badge.svg",
|
Path: "/api/v1/endpoints/core_frontend/response-times/7d/badge.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-response-time-with-invalid-duration",
|
Name: "badge-response-time-with-invalid-duration",
|
||||||
Path: "/api/v1/services/core_backend/response-times/3d/badge.svg",
|
Path: "/api/v1/endpoints/core_backend/response-times/3d/badge.svg",
|
||||||
ExpectedCode: http.StatusBadRequest,
|
ExpectedCode: http.StatusBadRequest,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "badge-response-time-for-invalid-key",
|
Name: "badge-response-time-for-invalid-key",
|
||||||
Path: "/api/v1/services/invalid_key/response-times/7d/badge.svg",
|
Path: "/api/v1/endpoints/invalid_key/response-times/7d/badge.svg",
|
||||||
ExpectedCode: http.StatusNotFound,
|
ExpectedCode: http.StatusNotFound,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "chart-response-time-24h",
|
Name: "chart-response-time-24h",
|
||||||
|
Path: "/api/v1/endpoints/core_backend/response-times/24h/chart.svg",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{ // XXX: Remove this in v4.0.0
|
||||||
|
Name: "backward-compatible-services-badge-uptime-1h",
|
||||||
|
Path: "/api/v1/services/core_frontend/uptimes/1h/badge.svg",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{ // XXX: Remove this in v4.0.0
|
||||||
|
Name: "backward-compatible-services-chart-response-time-24h",
|
||||||
Path: "/api/v1/services/core_backend/response-times/24h/chart.svg",
|
Path: "/api/v1/services/core_backend/response-times/24h/chart.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
|
||||||
if scenario.Gzip {
|
if scenario.Gzip {
|
||||||
request.Header.Set("Accept-Encoding", "gzip")
|
request.Header.Set("Accept-Encoding", "gzip")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwiN/gatus/v3/storage/store/common"
|
"github.com/TwiN/gatus/v3/storage/store/common"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"github.com/wcharczuk/go-chart/v2"
|
"github.com/wcharczuk/go-chart/v2"
|
||||||
@@ -42,21 +42,19 @@ func ResponseTimeChart(writer http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(writer, "Durations supported: 7d, 24h", http.StatusBadRequest)
|
http.Error(writer, "Durations supported: 7d, 24h", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
hourlyAverageResponseTime, err := storage.Get().GetHourlyAverageResponseTimeByKey(vars["key"], from, time.Now())
|
hourlyAverageResponseTime, err := store.Get().GetHourlyAverageResponseTimeByKey(vars["key"], from, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrServiceNotFound {
|
if err == common.ErrEndpointNotFound {
|
||||||
writer.WriteHeader(http.StatusNotFound)
|
http.Error(writer, err.Error(), http.StatusNotFound)
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if err == common.ErrInvalidTimeRange {
|
||||||
writer.WriteHeader(http.StatusBadRequest)
|
http.Error(writer, err.Error(), http.StatusBadRequest)
|
||||||
} else {
|
} else {
|
||||||
writer.WriteHeader(http.StatusInternalServerError)
|
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
_, _ = writer.Write([]byte(err.Error()))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if len(hourlyAverageResponseTime) == 0 {
|
if len(hourlyAverageResponseTime) == 0 {
|
||||||
writer.WriteHeader(http.StatusNoContent)
|
http.Error(writer, "", http.StatusNoContent)
|
||||||
_, _ = writer.Write(nil)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
series := chart.TimeSeries{
|
series := chart.TimeSeries{
|
||||||
@@ -114,6 +112,9 @@ func ResponseTimeChart(writer http.ResponseWriter, r *http.Request) {
|
|||||||
Series: []chart.Series{series},
|
Series: []chart.Series{series},
|
||||||
}
|
}
|
||||||
writer.Header().Set("Content-Type", "image/svg+xml")
|
writer.Header().Set("Content-Type", "image/svg+xml")
|
||||||
|
writer.Header().Set("Cache-Control", "no-cache, no-store")
|
||||||
|
writer.Header().Set("Expires", "0")
|
||||||
|
writer.WriteHeader(http.StatusOK)
|
||||||
if err := graph.Render(chart.SVG, writer); err != nil {
|
if err := graph.Render(chart.SVG, writer); err != nil {
|
||||||
log.Println("[handler][ResponseTimeChart] Failed to render response time chart:", err.Error())
|
log.Println("[handler][ResponseTimeChart] Failed to render response time chart:", err.Error())
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -8,16 +8,16 @@ import (
|
|||||||
|
|
||||||
"github.com/TwiN/gatus/v3/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwiN/gatus/v3/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwiN/gatus/v3/watchdog"
|
"github.com/TwiN/gatus/v3/watchdog"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestResponseTimeChart(t *testing.T) {
|
func TestResponseTimeChart(t *testing.T) {
|
||||||
defer storage.Get().Clear()
|
defer store.Get().Clear()
|
||||||
defer cache.Clear()
|
defer cache.Clear()
|
||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Metrics: true,
|
Metrics: true,
|
||||||
Services: []*core.Service{
|
Endpoints: []*core.Endpoint{
|
||||||
{
|
{
|
||||||
Name: "frontend",
|
Name: "frontend",
|
||||||
Group: "core",
|
Group: "core",
|
||||||
@@ -28,8 +28,8 @@ func TestResponseTimeChart(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
@@ -40,28 +40,33 @@ func TestResponseTimeChart(t *testing.T) {
|
|||||||
scenarios := []Scenario{
|
scenarios := []Scenario{
|
||||||
{
|
{
|
||||||
Name: "chart-response-time-24h",
|
Name: "chart-response-time-24h",
|
||||||
Path: "/api/v1/services/core_backend/response-times/24h/chart.svg",
|
Path: "/api/v1/endpoints/core_backend/response-times/24h/chart.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "chart-response-time-7d",
|
Name: "chart-response-time-7d",
|
||||||
Path: "/api/v1/services/core_frontend/response-times/7d/chart.svg",
|
Path: "/api/v1/endpoints/core_frontend/response-times/7d/chart.svg",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "chart-response-time-with-invalid-duration",
|
Name: "chart-response-time-with-invalid-duration",
|
||||||
Path: "/api/v1/services/core_backend/response-times/3d/chart.svg",
|
Path: "/api/v1/endpoints/core_backend/response-times/3d/chart.svg",
|
||||||
ExpectedCode: http.StatusBadRequest,
|
ExpectedCode: http.StatusBadRequest,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "chart-response-time-for-invalid-key",
|
Name: "chart-response-time-for-invalid-key",
|
||||||
Path: "/api/v1/services/invalid_key/response-times/7d/chart.svg",
|
Path: "/api/v1/endpoints/invalid_key/response-times/7d/chart.svg",
|
||||||
ExpectedCode: http.StatusNotFound,
|
ExpectedCode: http.StatusNotFound,
|
||||||
},
|
},
|
||||||
|
{ // XXX: Remove this in v4.0.0
|
||||||
|
Name: "backward-compatible-services-chart-response-time-24h",
|
||||||
|
Path: "/api/v1/services/core_backend/response-times/24h/chart.svg",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
|
||||||
if scenario.Gzip {
|
if scenario.Gzip {
|
||||||
request.Header.Set("Accept-Encoding", "gzip")
|
request.Header.Set("Accept-Encoding", "gzip")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v3/security"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConfigHandler is a handler that returns information for the front end of the application.
|
||||||
|
type ConfigHandler struct {
|
||||||
|
securityConfig *security.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
func (handler ConfigHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hasOIDC := false
|
||||||
|
isAuthenticated := true // Default to true if no security config is set
|
||||||
|
if handler.securityConfig != nil {
|
||||||
|
hasOIDC = handler.securityConfig.OIDC != nil
|
||||||
|
isAuthenticated = handler.securityConfig.IsAuthenticated(r)
|
||||||
|
}
|
||||||
|
// Return the config
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte(fmt.Sprintf(`{"oidc":%v,"authenticated":%v}`, hasOIDC, isAuthenticated)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v3/security"
|
||||||
|
"github.com/gorilla/mux"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConfigHandler_ServeHTTP(t *testing.T) {
|
||||||
|
securityConfig := &security.Config{
|
||||||
|
OIDC: &security.OIDCConfig{
|
||||||
|
IssuerURL: "https://sso.gatus.io/",
|
||||||
|
RedirectURL: "http://localhost:80/authorization-code/callback",
|
||||||
|
Scopes: []string{"openid"},
|
||||||
|
AllowedSubjects: []string{"user1@example.com"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
handler := ConfigHandler{securityConfig: securityConfig}
|
||||||
|
// Create a fake router. We're doing this because I need the gate to be initialized.
|
||||||
|
securityConfig.ApplySecurityMiddleware(mux.NewRouter())
|
||||||
|
// Test the config handler
|
||||||
|
request, _ := http.NewRequest("GET", "/api/v1/config", http.NoBody)
|
||||||
|
responseRecorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(responseRecorder, request)
|
||||||
|
if responseRecorder.Code != http.StatusOK {
|
||||||
|
t.Error("expected code to be 200, but was", responseRecorder.Code)
|
||||||
|
}
|
||||||
|
if responseRecorder.Body.String() != `{"oidc":true,"authenticated":false}` {
|
||||||
|
t.Error("expected body to be `{\"oidc\":true,\"authenticated\":false}`, but was", responseRecorder.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,11 @@ import "net/http"
|
|||||||
|
|
||||||
func DevelopmentCORS(next http.Handler) http.Handler {
|
func DevelopmentCORS(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8081")
|
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8081")
|
||||||
|
if r.Method == "OPTIONS" {
|
||||||
|
return
|
||||||
|
}
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwiN/gatus/v3/storage/store/common"
|
"github.com/TwiN/gatus/v3/storage/store/common"
|
||||||
"github.com/TwiN/gatus/v3/storage/store/common/paging"
|
"github.com/TwiN/gatus/v3/storage/store/common/paging"
|
||||||
"github.com/TwiN/gocache"
|
"github.com/TwiN/gocache"
|
||||||
@@ -25,42 +25,42 @@ var (
|
|||||||
cache = gocache.NewCache().WithMaxSize(100).WithEvictionPolicy(gocache.FirstInFirstOut)
|
cache = gocache.NewCache().WithMaxSize(100).WithEvictionPolicy(gocache.FirstInFirstOut)
|
||||||
)
|
)
|
||||||
|
|
||||||
// ServiceStatuses handles requests to retrieve all service statuses
|
// EndpointStatuses handles requests to retrieve all EndpointStatus
|
||||||
// Due to the size of the response, this function leverages a cache.
|
// Due to the size of the response, this function leverages a cache.
|
||||||
// Must not be wrapped by GzipHandler
|
// Must not be wrapped by GzipHandler
|
||||||
func ServiceStatuses(writer http.ResponseWriter, r *http.Request) {
|
func EndpointStatuses(writer http.ResponseWriter, r *http.Request) {
|
||||||
page, pageSize := extractPageAndPageSizeFromRequest(r)
|
page, pageSize := extractPageAndPageSizeFromRequest(r)
|
||||||
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
|
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
|
||||||
var exists bool
|
var exists bool
|
||||||
var value interface{}
|
var value interface{}
|
||||||
if gzipped {
|
if gzipped {
|
||||||
writer.Header().Set("Content-Encoding", "gzip")
|
writer.Header().Set("Content-Encoding", "gzip")
|
||||||
value, exists = cache.Get(fmt.Sprintf("service-status-%d-%d-gzipped", page, pageSize))
|
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize))
|
||||||
} else {
|
} else {
|
||||||
value, exists = cache.Get(fmt.Sprintf("service-status-%d-%d", page, pageSize))
|
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize))
|
||||||
}
|
}
|
||||||
var data []byte
|
var data []byte
|
||||||
if !exists {
|
if !exists {
|
||||||
var err error
|
var err error
|
||||||
buffer := &bytes.Buffer{}
|
buffer := &bytes.Buffer{}
|
||||||
gzipWriter := gzip.NewWriter(buffer)
|
gzipWriter := gzip.NewWriter(buffer)
|
||||||
serviceStatuses, err := storage.Get().GetAllServiceStatuses(paging.NewServiceStatusParams().WithResults(page, pageSize))
|
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[handler][ServiceStatuses] Failed to retrieve service statuses: %s", err.Error())
|
log.Printf("[handler][EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
|
||||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
data, err = json.Marshal(serviceStatuses)
|
data, err = json.Marshal(endpointStatuses)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[handler][ServiceStatuses] Unable to marshal object to JSON: %s", err.Error())
|
log.Printf("[handler][EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
|
||||||
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
|
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, _ = gzipWriter.Write(data)
|
_, _ = gzipWriter.Write(data)
|
||||||
_ = gzipWriter.Close()
|
_ = gzipWriter.Close()
|
||||||
gzippedData := buffer.Bytes()
|
gzippedData := buffer.Bytes()
|
||||||
cache.SetWithTTL(fmt.Sprintf("service-status-%d-%d", page, pageSize), data, cacheTTL)
|
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
|
||||||
cache.SetWithTTL(fmt.Sprintf("service-status-%d-%d-gzipped", page, pageSize), gzippedData, cacheTTL)
|
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize), gzippedData, cacheTTL)
|
||||||
if gzipped {
|
if gzipped {
|
||||||
data = gzippedData
|
data = gzippedData
|
||||||
}
|
}
|
||||||
@@ -72,28 +72,28 @@ func ServiceStatuses(writer http.ResponseWriter, r *http.Request) {
|
|||||||
_, _ = writer.Write(data)
|
_, _ = writer.Write(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServiceStatus retrieves a single ServiceStatus by group name and service name
|
// EndpointStatus retrieves a single core.EndpointStatus by group and endpoint name
|
||||||
func ServiceStatus(writer http.ResponseWriter, r *http.Request) {
|
func EndpointStatus(writer http.ResponseWriter, r *http.Request) {
|
||||||
page, pageSize := extractPageAndPageSizeFromRequest(r)
|
page, pageSize := extractPageAndPageSizeFromRequest(r)
|
||||||
vars := mux.Vars(r)
|
vars := mux.Vars(r)
|
||||||
serviceStatus, err := storage.Get().GetServiceStatusByKey(vars["key"], paging.NewServiceStatusParams().WithResults(page, pageSize).WithEvents(1, common.MaximumNumberOfEvents))
|
endpointStatus, err := store.Get().GetEndpointStatusByKey(vars["key"], paging.NewEndpointStatusParams().WithResults(page, pageSize).WithEvents(1, common.MaximumNumberOfEvents))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrServiceNotFound {
|
if err == common.ErrEndpointNotFound {
|
||||||
http.Error(writer, err.Error(), http.StatusNotFound)
|
http.Error(writer, err.Error(), http.StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Printf("[handler][ServiceStatus] Failed to retrieve service status: %s", err.Error())
|
log.Printf("[handler][EndpointStatus] Failed to retrieve endpoint status: %s", err.Error())
|
||||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if serviceStatus == nil {
|
if endpointStatus == nil {
|
||||||
log.Printf("[handler][ServiceStatus] Service with key=%s not found", vars["key"])
|
log.Printf("[handler][EndpointStatus] Endpoint with key=%s not found", vars["key"])
|
||||||
http.Error(writer, "not found", http.StatusNotFound)
|
http.Error(writer, "not found", http.StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
output, err := json.Marshal(serviceStatus)
|
output, err := json.Marshal(endpointStatus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[handler][ServiceStatus] Unable to marshal object to JSON: %s", err.Error())
|
log.Printf("[handler][EndpointStatus] Unable to marshal object to JSON: %s", err.Error())
|
||||||
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
|
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
|
|
||||||
"github.com/TwiN/gatus/v3/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwiN/gatus/v3/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwiN/gatus/v3/watchdog"
|
"github.com/TwiN/gatus/v3/watchdog"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ var (
|
|||||||
|
|
||||||
timestamp = time.Now()
|
timestamp = time.Now()
|
||||||
|
|
||||||
testService = core.Service{
|
testEndpoint = core.Endpoint{
|
||||||
Name: "name",
|
Name: "name",
|
||||||
Group: "group",
|
Group: "group",
|
||||||
URL: "https://example.org/what/ever",
|
URL: "https://example.org/what/ever",
|
||||||
@@ -83,12 +83,12 @@ var (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestServiceStatus(t *testing.T) {
|
func TestEndpointStatus(t *testing.T) {
|
||||||
defer storage.Get().Clear()
|
defer store.Get().Clear()
|
||||||
defer cache.Clear()
|
defer cache.Clear()
|
||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Metrics: true,
|
Metrics: true,
|
||||||
Services: []*core.Service{
|
Endpoints: []*core.Endpoint{
|
||||||
{
|
{
|
||||||
Name: "frontend",
|
Name: "frontend",
|
||||||
Group: "core",
|
Group: "core",
|
||||||
@@ -99,8 +99,8 @@ func TestServiceStatus(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
||||||
|
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
@@ -111,30 +111,35 @@ func TestServiceStatus(t *testing.T) {
|
|||||||
}
|
}
|
||||||
scenarios := []Scenario{
|
scenarios := []Scenario{
|
||||||
{
|
{
|
||||||
Name: "service-status",
|
Name: "endpoint-status",
|
||||||
Path: "/api/v1/services/core_frontend/statuses",
|
Path: "/api/v1/endpoints/core_frontend/statuses",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "service-status-gzip",
|
Name: "endpoint-status-gzip",
|
||||||
Path: "/api/v1/services/core_frontend/statuses",
|
Path: "/api/v1/endpoints/core_frontend/statuses",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
Gzip: true,
|
Gzip: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "service-status-pagination",
|
Name: "endpoint-status-pagination",
|
||||||
Path: "/api/v1/services/core_frontend/statuses?page=1&pageSize=20",
|
Path: "/api/v1/endpoints/core_frontend/statuses?page=1&pageSize=20",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "service-status-for-invalid-key",
|
Name: "endpoint-status-for-invalid-key",
|
||||||
Path: "/api/v1/services/invalid_key/statuses",
|
Path: "/api/v1/endpoints/invalid_key/statuses",
|
||||||
ExpectedCode: http.StatusNotFound,
|
ExpectedCode: http.StatusNotFound,
|
||||||
},
|
},
|
||||||
|
{ // XXX: Remove this in v4.0.0
|
||||||
|
Name: "backward-compatible-service-status",
|
||||||
|
Path: "/api/v1/services/core_frontend/statuses",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
|
||||||
if scenario.Gzip {
|
if scenario.Gzip {
|
||||||
request.Header.Set("Accept-Encoding", "gzip")
|
request.Header.Set("Accept-Encoding", "gzip")
|
||||||
}
|
}
|
||||||
@@ -147,13 +152,13 @@ func TestServiceStatus(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestServiceStatuses(t *testing.T) {
|
func TestEndpointStatuses(t *testing.T) {
|
||||||
defer storage.Get().Clear()
|
defer store.Get().Clear()
|
||||||
defer cache.Clear()
|
defer cache.Clear()
|
||||||
firstResult := &testSuccessfulResult
|
firstResult := &testSuccessfulResult
|
||||||
secondResult := &testUnsuccessfulResult
|
secondResult := &testUnsuccessfulResult
|
||||||
storage.Get().Insert(&testService, firstResult)
|
store.Get().Insert(&testEndpoint, firstResult)
|
||||||
storage.Get().Insert(&testService, secondResult)
|
store.Get().Insert(&testEndpoint, secondResult)
|
||||||
// Can't be bothered dealing with timezone issues on the worker that runs the automated tests
|
// Can't be bothered dealing with timezone issues on the worker that runs the automated tests
|
||||||
firstResult.Timestamp = time.Time{}
|
firstResult.Timestamp = time.Time{}
|
||||||
secondResult.Timestamp = time.Time{}
|
secondResult.Timestamp = time.Time{}
|
||||||
@@ -168,39 +173,45 @@ func TestServiceStatuses(t *testing.T) {
|
|||||||
scenarios := []Scenario{
|
scenarios := []Scenario{
|
||||||
{
|
{
|
||||||
Name: "no-pagination",
|
Name: "no-pagination",
|
||||||
Path: "/api/v1/services/statuses",
|
Path: "/api/v1/endpoints/statuses",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"errors":null,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"},{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}],"events":[]}]`,
|
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"},{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}]}]`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "pagination-first-result",
|
Name: "pagination-first-result",
|
||||||
Path: "/api/v1/services/statuses?page=1&pageSize=1",
|
Path: "/api/v1/endpoints/statuses?page=1&pageSize=1",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}],"events":[]}]`,
|
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}]}]`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "pagination-second-result",
|
Name: "pagination-second-result",
|
||||||
Path: "/api/v1/services/statuses?page=2&pageSize=1",
|
Path: "/api/v1/endpoints/statuses?page=2&pageSize=1",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"errors":null,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"}],"events":[]}]`,
|
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"}]}]`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "pagination-no-results",
|
Name: "pagination-no-results",
|
||||||
Path: "/api/v1/services/statuses?page=5&pageSize=20",
|
Path: "/api/v1/endpoints/statuses?page=5&pageSize=20",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[],"events":[]}]`,
|
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[]}]`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "invalid-pagination-should-fall-back-to-default",
|
Name: "invalid-pagination-should-fall-back-to-default",
|
||||||
Path: "/api/v1/services/statuses?page=INVALID&pageSize=INVALID",
|
Path: "/api/v1/endpoints/statuses?page=INVALID&pageSize=INVALID",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"errors":null,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"},{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}],"events":[]}]`,
|
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"},{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}]}]`,
|
||||||
|
},
|
||||||
|
{ // XXX: Remove this in v4.0.0
|
||||||
|
Name: "backward-compatible-service-status",
|
||||||
|
Path: "/api/v1/services/statuses",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
ExpectedBody: `[{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"},{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}]}]`,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
|
||||||
responseRecorder := httptest.NewRecorder()
|
responseRecorder := httptest.NewRecorder()
|
||||||
router.ServeHTTP(responseRecorder, request)
|
router.ServeHTTP(responseRecorder, request)
|
||||||
if responseRecorder.Code != scenario.ExpectedCode {
|
if responseRecorder.Code != scenario.ExpectedCode {
|
||||||
@@ -22,7 +22,7 @@ func TestFavIcon(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
|
||||||
responseRecorder := httptest.NewRecorder()
|
responseRecorder := httptest.NewRecorder()
|
||||||
router.ServeHTTP(responseRecorder, request)
|
router.ServeHTTP(responseRecorder, request)
|
||||||
if responseRecorder.Code != scenario.ExpectedCode {
|
if responseRecorder.Code != scenario.ExpectedCode {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package handler
|
|||||||
import (
|
import (
|
||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -11,7 +10,7 @@ import (
|
|||||||
|
|
||||||
var gzPool = sync.Pool{
|
var gzPool = sync.Pool{
|
||||||
New: func() interface{} {
|
New: func() interface{} {
|
||||||
return gzip.NewWriter(ioutil.Discard)
|
return gzip.NewWriter(io.Discard)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,27 +15,39 @@ func CreateRouter(staticFolder string, securityConfig *security.Config, uiConfig
|
|||||||
if enabledMetrics {
|
if enabledMetrics {
|
||||||
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
||||||
}
|
}
|
||||||
|
api := router.PathPrefix("/api").Subrouter()
|
||||||
|
protected := api.PathPrefix("/").Subrouter()
|
||||||
|
unprotected := api.PathPrefix("/").Subrouter()
|
||||||
|
if securityConfig != nil {
|
||||||
|
if err := securityConfig.RegisterHandlers(router); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
if err := securityConfig.ApplySecurityMiddleware(protected); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Endpoints
|
||||||
|
unprotected.Handle("/v1/config", ConfigHandler{securityConfig: securityConfig}).Methods("GET")
|
||||||
|
protected.HandleFunc("/v1/endpoints/statuses", EndpointStatuses).Methods("GET") // No GzipHandler for this one, because we cache the content as Gzipped already
|
||||||
|
protected.HandleFunc("/v1/endpoints/{key}/statuses", GzipHandlerFunc(EndpointStatus)).Methods("GET")
|
||||||
|
unprotected.HandleFunc("/v1/endpoints/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET")
|
||||||
|
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge).Methods("GET")
|
||||||
|
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET")
|
||||||
|
// XXX: Remove the lines between this and the next XXX comment in v4.0.0
|
||||||
|
protected.HandleFunc("/v1/services/statuses", EndpointStatuses).Methods("GET") // No GzipHandler for this one, because we cache the content as Gzipped already
|
||||||
|
protected.HandleFunc("/v1/services/{key}/statuses", GzipHandlerFunc(EndpointStatus)).Methods("GET")
|
||||||
|
unprotected.HandleFunc("/v1/services/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET")
|
||||||
|
unprotected.HandleFunc("/v1/services/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge).Methods("GET")
|
||||||
|
unprotected.HandleFunc("/v1/services/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET")
|
||||||
|
// XXX: Remove the lines between this and the previous XXX comment in v4.0.0
|
||||||
|
// Misc
|
||||||
router.Handle("/health", health.Handler().WithJSON(true)).Methods("GET")
|
router.Handle("/health", health.Handler().WithJSON(true)).Methods("GET")
|
||||||
router.HandleFunc("/favicon.ico", FavIcon(staticFolder)).Methods("GET")
|
router.HandleFunc("/favicon.ico", FavIcon(staticFolder)).Methods("GET")
|
||||||
// Endpoints
|
|
||||||
router.HandleFunc("/api/v1/services/statuses", secureIfNecessary(securityConfig, ServiceStatuses)).Methods("GET") // No GzipHandler for this one, because we cache the content as Gzipped already
|
|
||||||
router.HandleFunc("/api/v1/services/{key}/statuses", secureIfNecessary(securityConfig, GzipHandlerFunc(ServiceStatus))).Methods("GET")
|
|
||||||
// TODO: router.HandleFunc("/api/v1/services/{key}/uptimes", secureIfNecessary(securityConfig, GzipHandlerFunc(serviceUptimesHandler))).Methods("GET")
|
|
||||||
// TODO: router.HandleFunc("/api/v1/services/{key}/events", secureIfNecessary(securityConfig, GzipHandlerFunc(serviceEventsHandler))).Methods("GET")
|
|
||||||
router.HandleFunc("/api/v1/services/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET")
|
|
||||||
router.HandleFunc("/api/v1/services/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge).Methods("GET")
|
|
||||||
router.HandleFunc("/api/v1/services/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET")
|
|
||||||
// SPA
|
// SPA
|
||||||
router.HandleFunc("/services/{service}", SinglePageApplication(staticFolder, uiConfig)).Methods("GET")
|
router.HandleFunc("/services/{name}", SinglePageApplication(staticFolder, uiConfig)).Methods("GET") // XXX: Remove this in v4.0.0
|
||||||
|
router.HandleFunc("/endpoints/{name}", SinglePageApplication(staticFolder, uiConfig)).Methods("GET")
|
||||||
router.HandleFunc("/", SinglePageApplication(staticFolder, uiConfig)).Methods("GET")
|
router.HandleFunc("/", SinglePageApplication(staticFolder, uiConfig)).Methods("GET")
|
||||||
// Everything else falls back on static content
|
// Everything else falls back on static content
|
||||||
router.PathPrefix("/").Handler(GzipHandler(http.FileServer(http.Dir(staticFolder))))
|
router.PathPrefix("/").Handler(GzipHandler(http.FileServer(http.Dir(staticFolder))))
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
func secureIfNecessary(securityConfig *security.Config, handler http.HandlerFunc) http.HandlerFunc {
|
|
||||||
if securityConfig != nil && securityConfig.IsValid() {
|
|
||||||
return security.Handler(handler, securityConfig)
|
|
||||||
}
|
|
||||||
return handler
|
|
||||||
}
|
|
||||||
@@ -44,7 +44,7 @@ func TestCreateRouter(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
|
||||||
if scenario.Gzip {
|
if scenario.Gzip {
|
||||||
request.Header.Set("Accept-Encoding", "gzip")
|
request.Header.Set("Accept-Encoding", "gzip")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,16 +8,16 @@ import (
|
|||||||
|
|
||||||
"github.com/TwiN/gatus/v3/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwiN/gatus/v3/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwiN/gatus/v3/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwiN/gatus/v3/watchdog"
|
"github.com/TwiN/gatus/v3/watchdog"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSinglePageApplication(t *testing.T) {
|
func TestSinglePageApplication(t *testing.T) {
|
||||||
defer storage.Get().Clear()
|
defer store.Get().Clear()
|
||||||
defer cache.Clear()
|
defer cache.Clear()
|
||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Metrics: true,
|
Metrics: true,
|
||||||
Services: []*core.Service{
|
Endpoints: []*core.Endpoint{
|
||||||
{
|
{
|
||||||
Name: "frontend",
|
Name: "frontend",
|
||||||
Group: "core",
|
Group: "core",
|
||||||
@@ -28,8 +28,8 @@ func TestSinglePageApplication(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateServiceStatuses(cfg.Services[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
@@ -44,6 +44,11 @@ func TestSinglePageApplication(t *testing.T) {
|
|||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Name: "frontend-endpoint",
|
||||||
|
Path: "/endpoints/core_frontend",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{ // XXX: Remove this in v4.0.0
|
||||||
Name: "frontend-service",
|
Name: "frontend-service",
|
||||||
Path: "/services/core_frontend",
|
Path: "/services/core_frontend",
|
||||||
ExpectedCode: http.StatusOK,
|
ExpectedCode: http.StatusOK,
|
||||||
@@ -51,7 +56,7 @@ func TestSinglePageApplication(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
|
||||||
if scenario.Gzip {
|
if scenario.Gzip {
|
||||||
request.Header.Set("Accept-Encoding", "gzip")
|
request.Header.Set("Accept-Encoding", "gzip")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ func TestExtractPageAndPageSizeFromRequest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run("page-"+scenario.Page+"-pageSize-"+scenario.PageSize, func(t *testing.T) {
|
t.Run("page-"+scenario.Page+"-pageSize-"+scenario.PageSize, func(t *testing.T) {
|
||||||
request, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/statuses?page=%s&pageSize=%s", scenario.Page, scenario.PageSize), nil)
|
request, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/statuses?page=%s&pageSize=%s", scenario.Page, scenario.PageSize), http.NoBody)
|
||||||
actualPage, actualPageSize := extractPageAndPageSizeFromRequest(request)
|
actualPage, actualPageSize := extractPageAndPageSizeFromRequest(request)
|
||||||
if actualPage != scenario.ExpectedPage {
|
if actualPage != scenario.ExpectedPage {
|
||||||
t.Errorf("expected %d, got %d", scenario.ExpectedPage, actualPage)
|
t.Errorf("expected %d, got %d", scenario.ExpectedPage, actualPage)
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ const (
|
|||||||
maximumLengthBeforeTruncatingWhenComparedWithPattern = 25
|
maximumLengthBeforeTruncatingWhenComparedWithPattern = 25
|
||||||
)
|
)
|
||||||
|
|
||||||
// Condition is a condition that needs to be met in order for a Service to be considered healthy.
|
// Condition is a condition that needs to be met in order for an Endpoint to be considered healthy.
|
||||||
type Condition string
|
type Condition string
|
||||||
|
|
||||||
// evaluate the Condition with the Result of the health check
|
// evaluate the Condition with the Result of the health check
|
||||||
@@ -283,7 +283,7 @@ func prettifyNumericalParameters(parameters []string, resolvedParameters []int64
|
|||||||
return prettify(parameters, []string{strconv.Itoa(int(resolvedParameters[0])), strconv.Itoa(int(resolvedParameters[1]))}, operator)
|
return prettify(parameters, []string{strconv.Itoa(int(resolvedParameters[0])), strconv.Itoa(int(resolvedParameters[1]))}, operator)
|
||||||
}
|
}
|
||||||
|
|
||||||
// XXX: make this configurable? i.e. show-resolved-conditions-on-failure
|
// prettify returns a string representation of a condition with its parameters resolved between parentheses
|
||||||
func prettify(parameters []string, resolvedParameters []string, operator string) string {
|
func prettify(parameters []string, resolvedParameters []string, operator string) string {
|
||||||
// Since, in the event of an invalid path, the resolvedParameters also contain the condition itself,
|
// Since, in the event of an invalid path, the resolvedParameters also contain the condition itself,
|
||||||
// we'll return the resolvedParameters as-is.
|
// we'll return the resolvedParameters as-is.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const (
|
|||||||
dnsPort = 53
|
dnsPort = 53
|
||||||
)
|
)
|
||||||
|
|
||||||
// DNS is the configuration for a Service of type DNS
|
// DNS is the configuration for a Endpoint of type DNS
|
||||||
type DNS struct {
|
type DNS struct {
|
||||||
// QueryType is the type for the DNS records like A, AAAA, CNAME...
|
// QueryType is the type for the DNS records like A, AAAA, CNAME...
|
||||||
QueryType string `yaml:"query-type"`
|
QueryType string `yaml:"query-type"`
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ func TestIntegrationQuery(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithNoDNSQueryName(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithNoDNSQueryName(t *testing.T) {
|
||||||
defer func() { recover() }()
|
defer func() { recover() }()
|
||||||
dns := &DNS{
|
dns := &DNS{
|
||||||
QueryType: "A",
|
QueryType: "A",
|
||||||
@@ -111,11 +111,11 @@ func TestService_ValidateAndSetDefaultsWithNoDNSQueryName(t *testing.T) {
|
|||||||
}
|
}
|
||||||
err := dns.validateAndSetDefault()
|
err := dns.validateAndSetDefault()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Should've returned an error because service`s dns didn't have a query name, which is a mandatory field for dns")
|
t.Fatal("Should've returned an error because endpoint's dns didn't have a query name, which is a mandatory field for dns")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithInvalidDNSQueryType(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithInvalidDNSQueryType(t *testing.T) {
|
||||||
defer func() { recover() }()
|
defer func() { recover() }()
|
||||||
dns := &DNS{
|
dns := &DNS{
|
||||||
QueryType: "B",
|
QueryType: "B",
|
||||||
@@ -123,6 +123,6 @@ func TestService_ValidateAndSetDefaultsWithInvalidDNSQueryType(t *testing.T) {
|
|||||||
}
|
}
|
||||||
err := dns.validateAndSetDefault()
|
err := dns.validateAndSetDefault()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Should've returned an error because service`s dns query type is invalid, it needs to be a valid query name like A, AAAA, CNAME...")
|
t.Fatal("Should've returned an error because endpoint's dns query type is invalid, it needs to be a valid query name like A, AAAA, CNAME...")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v3/client"
|
||||||
|
"github.com/TwiN/gatus/v3/core/ui"
|
||||||
|
"github.com/TwiN/gatus/v3/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// HostHeader is the name of the header used to specify the host
|
||||||
|
HostHeader = "Host"
|
||||||
|
|
||||||
|
// ContentTypeHeader is the name of the header used to specify the content type
|
||||||
|
ContentTypeHeader = "Content-Type"
|
||||||
|
|
||||||
|
// UserAgentHeader is the name of the header used to specify the request's user agent
|
||||||
|
UserAgentHeader = "User-Agent"
|
||||||
|
|
||||||
|
// GatusUserAgent is the default user agent that Gatus uses to send requests.
|
||||||
|
GatusUserAgent = "Gatus/1.0"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrEndpointWithNoCondition is the error with which Gatus will panic if an endpoint is configured with no conditions
|
||||||
|
ErrEndpointWithNoCondition = errors.New("you must specify at least one condition per endpoint")
|
||||||
|
|
||||||
|
// ErrEndpointWithNoURL is the error with which Gatus will panic if an endpoint is configured with no url
|
||||||
|
ErrEndpointWithNoURL = errors.New("you must specify an url for each endpoint")
|
||||||
|
|
||||||
|
// ErrEndpointWithNoName is the error with which Gatus will panic if an endpoint is configured with no name
|
||||||
|
ErrEndpointWithNoName = errors.New("you must specify a name for each endpoint")
|
||||||
|
|
||||||
|
// ErrEndpointWithInvalidNameOrGroup is the error with which Gatus will panic if an endpoint has an invalid character where it shouldn't
|
||||||
|
ErrEndpointWithInvalidNameOrGroup = errors.New("endpoint name and group must not have \" or \\")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Endpoint is the configuration of a monitored
|
||||||
|
type Endpoint struct {
|
||||||
|
// Enabled defines whether to enable the monitoring of the endpoint
|
||||||
|
Enabled *bool `yaml:"enabled,omitempty"`
|
||||||
|
|
||||||
|
// Name of the endpoint. Can be anything.
|
||||||
|
Name string `yaml:"name"`
|
||||||
|
|
||||||
|
// Group the endpoint is a part of. Used for grouping multiple endpoints together on the front end.
|
||||||
|
Group string `yaml:"group,omitempty"`
|
||||||
|
|
||||||
|
// URL to send the request to
|
||||||
|
URL string `yaml:"url"`
|
||||||
|
|
||||||
|
// DNS is the configuration of DNS monitoring
|
||||||
|
DNS *DNS `yaml:"dns,omitempty"`
|
||||||
|
|
||||||
|
// Method of the request made to the url of the endpoint
|
||||||
|
Method string `yaml:"method,omitempty"`
|
||||||
|
|
||||||
|
// Body of the request
|
||||||
|
Body string `yaml:"body,omitempty"`
|
||||||
|
|
||||||
|
// GraphQL is whether to wrap the body in a query param ({"query":"$body"})
|
||||||
|
GraphQL bool `yaml:"graphql,omitempty"`
|
||||||
|
|
||||||
|
// Headers of the request
|
||||||
|
Headers map[string]string `yaml:"headers,omitempty"`
|
||||||
|
|
||||||
|
// Interval is the duration to wait between every status check
|
||||||
|
Interval time.Duration `yaml:"interval,omitempty"`
|
||||||
|
|
||||||
|
// Conditions used to determine the health of the endpoint
|
||||||
|
Conditions []*Condition `yaml:"conditions"`
|
||||||
|
|
||||||
|
// Alerts is the alerting configuration for the endpoint in case of failure
|
||||||
|
Alerts []*alert.Alert `yaml:"alerts,omitempty"`
|
||||||
|
|
||||||
|
// ClientConfig is the configuration of the client used to communicate with the endpoint's target
|
||||||
|
ClientConfig *client.Config `yaml:"client,omitempty"`
|
||||||
|
|
||||||
|
// UIConfig is the configuration for the UI
|
||||||
|
UIConfig *ui.Config `yaml:"ui,omitempty"`
|
||||||
|
|
||||||
|
// NumberOfFailuresInARow is the number of unsuccessful evaluations in a row
|
||||||
|
NumberOfFailuresInARow int `yaml:"-"`
|
||||||
|
|
||||||
|
// NumberOfSuccessesInARow is the number of successful evaluations in a row
|
||||||
|
NumberOfSuccessesInARow int `yaml:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsEnabled returns whether the endpoint is enabled or not
|
||||||
|
func (endpoint Endpoint) IsEnabled() bool {
|
||||||
|
if endpoint.Enabled == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return *endpoint.Enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAndSetDefaults validates the endpoint's configuration and sets the default value of fields that have one
|
||||||
|
func (endpoint *Endpoint) ValidateAndSetDefaults() error {
|
||||||
|
// Set default values
|
||||||
|
if endpoint.ClientConfig == nil {
|
||||||
|
endpoint.ClientConfig = client.GetDefaultConfig()
|
||||||
|
} else {
|
||||||
|
endpoint.ClientConfig.ValidateAndSetDefaults()
|
||||||
|
}
|
||||||
|
if endpoint.UIConfig == nil {
|
||||||
|
endpoint.UIConfig = ui.GetDefaultConfig()
|
||||||
|
}
|
||||||
|
if endpoint.Interval == 0 {
|
||||||
|
endpoint.Interval = 1 * time.Minute
|
||||||
|
}
|
||||||
|
if len(endpoint.Method) == 0 {
|
||||||
|
endpoint.Method = http.MethodGet
|
||||||
|
}
|
||||||
|
if len(endpoint.Headers) == 0 {
|
||||||
|
endpoint.Headers = make(map[string]string)
|
||||||
|
}
|
||||||
|
// Automatically add user agent header if there isn't one specified in the endpoint configuration
|
||||||
|
if _, userAgentHeaderExists := endpoint.Headers[UserAgentHeader]; !userAgentHeaderExists {
|
||||||
|
endpoint.Headers[UserAgentHeader] = GatusUserAgent
|
||||||
|
}
|
||||||
|
// Automatically add "Content-Type: application/json" header if there's no Content-Type set
|
||||||
|
// and endpoint.GraphQL is set to true
|
||||||
|
if _, contentTypeHeaderExists := endpoint.Headers[ContentTypeHeader]; !contentTypeHeaderExists && endpoint.GraphQL {
|
||||||
|
endpoint.Headers[ContentTypeHeader] = "application/json"
|
||||||
|
}
|
||||||
|
for _, endpointAlert := range endpoint.Alerts {
|
||||||
|
if err := endpointAlert.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(endpoint.Name) == 0 {
|
||||||
|
return ErrEndpointWithNoName
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(endpoint.Name, "\"\\") || strings.ContainsAny(endpoint.Group, "\"\\") {
|
||||||
|
return ErrEndpointWithInvalidNameOrGroup
|
||||||
|
}
|
||||||
|
if len(endpoint.URL) == 0 {
|
||||||
|
return ErrEndpointWithNoURL
|
||||||
|
}
|
||||||
|
if len(endpoint.Conditions) == 0 {
|
||||||
|
return ErrEndpointWithNoCondition
|
||||||
|
}
|
||||||
|
if endpoint.DNS != nil {
|
||||||
|
return endpoint.DNS.validateAndSetDefault()
|
||||||
|
}
|
||||||
|
// Make sure that the request can be created
|
||||||
|
_, err := http.NewRequest(endpoint.Method, endpoint.URL, bytes.NewBuffer([]byte(endpoint.Body)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DisplayName returns an identifier made up of the Name and, if not empty, the Group.
|
||||||
|
func (endpoint Endpoint) DisplayName() string {
|
||||||
|
if len(endpoint.Group) > 0 {
|
||||||
|
return endpoint.Group + "/" + endpoint.Name
|
||||||
|
}
|
||||||
|
return endpoint.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key returns the unique key for the Endpoint
|
||||||
|
func (endpoint Endpoint) Key() string {
|
||||||
|
return util.ConvertGroupAndEndpointNameToKey(endpoint.Group, endpoint.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EvaluateHealth sends a request to the endpoint's URL and evaluates the conditions of the endpoint.
|
||||||
|
func (endpoint *Endpoint) EvaluateHealth() *Result {
|
||||||
|
result := &Result{Success: true, Errors: []string{}}
|
||||||
|
endpoint.getIP(result)
|
||||||
|
if len(result.Errors) == 0 {
|
||||||
|
endpoint.call(result)
|
||||||
|
} else {
|
||||||
|
result.Success = false
|
||||||
|
}
|
||||||
|
for _, condition := range endpoint.Conditions {
|
||||||
|
success := condition.evaluate(result, endpoint.UIConfig.DontResolveFailedConditions)
|
||||||
|
if !success {
|
||||||
|
result.Success = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.Timestamp = time.Now()
|
||||||
|
// No need to keep the body after the endpoint has been evaluated
|
||||||
|
result.body = nil
|
||||||
|
// Clean up parameters that we don't need to keep in the results
|
||||||
|
if endpoint.UIConfig.HideHostname {
|
||||||
|
result.Hostname = ""
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (endpoint *Endpoint) getIP(result *Result) {
|
||||||
|
if endpoint.DNS != nil {
|
||||||
|
result.Hostname = strings.TrimSuffix(endpoint.URL, ":53")
|
||||||
|
} else {
|
||||||
|
urlObject, err := url.Parse(endpoint.URL)
|
||||||
|
if err != nil {
|
||||||
|
result.AddError(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result.Hostname = urlObject.Hostname()
|
||||||
|
}
|
||||||
|
ips, err := net.LookupIP(result.Hostname)
|
||||||
|
if err != nil {
|
||||||
|
result.AddError(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result.IP = ips[0].String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (endpoint *Endpoint) call(result *Result) {
|
||||||
|
var request *http.Request
|
||||||
|
var response *http.Response
|
||||||
|
var err error
|
||||||
|
var certificate *x509.Certificate
|
||||||
|
isTypeDNS := endpoint.DNS != nil
|
||||||
|
isTypeTCP := strings.HasPrefix(endpoint.URL, "tcp://")
|
||||||
|
isTypeICMP := strings.HasPrefix(endpoint.URL, "icmp://")
|
||||||
|
isTypeSTARTTLS := strings.HasPrefix(endpoint.URL, "starttls://")
|
||||||
|
isTypeTLS := strings.HasPrefix(endpoint.URL, "tls://")
|
||||||
|
isTypeHTTP := !isTypeDNS && !isTypeTCP && !isTypeICMP && !isTypeSTARTTLS && !isTypeTLS
|
||||||
|
if isTypeHTTP {
|
||||||
|
request = endpoint.buildHTTPRequest()
|
||||||
|
}
|
||||||
|
startTime := time.Now()
|
||||||
|
if isTypeDNS {
|
||||||
|
endpoint.DNS.query(endpoint.URL, result)
|
||||||
|
result.Duration = time.Since(startTime)
|
||||||
|
} else if isTypeSTARTTLS || isTypeTLS {
|
||||||
|
if isTypeSTARTTLS {
|
||||||
|
result.Connected, certificate, err = client.CanPerformStartTLS(strings.TrimPrefix(endpoint.URL, "starttls://"), endpoint.ClientConfig)
|
||||||
|
} else {
|
||||||
|
result.Connected, certificate, err = client.CanPerformTLS(strings.TrimPrefix(endpoint.URL, "tls://"), endpoint.ClientConfig)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
result.AddError(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result.Duration = time.Since(startTime)
|
||||||
|
result.CertificateExpiration = time.Until(certificate.NotAfter)
|
||||||
|
} else if isTypeTCP {
|
||||||
|
result.Connected = client.CanCreateTCPConnection(strings.TrimPrefix(endpoint.URL, "tcp://"), endpoint.ClientConfig)
|
||||||
|
result.Duration = time.Since(startTime)
|
||||||
|
} else if isTypeICMP {
|
||||||
|
result.Connected, result.Duration = client.Ping(strings.TrimPrefix(endpoint.URL, "icmp://"), endpoint.ClientConfig)
|
||||||
|
} else {
|
||||||
|
response, err = client.GetHTTPClient(endpoint.ClientConfig).Do(request)
|
||||||
|
result.Duration = time.Since(startTime)
|
||||||
|
if err != nil {
|
||||||
|
result.AddError(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.TLS != nil && len(response.TLS.PeerCertificates) > 0 {
|
||||||
|
certificate = response.TLS.PeerCertificates[0]
|
||||||
|
result.CertificateExpiration = time.Until(certificate.NotAfter)
|
||||||
|
}
|
||||||
|
result.HTTPStatus = response.StatusCode
|
||||||
|
result.Connected = response.StatusCode > 0
|
||||||
|
// Only read the body if there's a condition that uses the BodyPlaceholder
|
||||||
|
if endpoint.needsToReadBody() {
|
||||||
|
result.body, err = io.ReadAll(response.Body)
|
||||||
|
if err != nil {
|
||||||
|
result.AddError(err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (endpoint *Endpoint) buildHTTPRequest() *http.Request {
|
||||||
|
var bodyBuffer *bytes.Buffer
|
||||||
|
if endpoint.GraphQL {
|
||||||
|
graphQlBody := map[string]string{
|
||||||
|
"query": endpoint.Body,
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(graphQlBody)
|
||||||
|
bodyBuffer = bytes.NewBuffer(body)
|
||||||
|
} else {
|
||||||
|
bodyBuffer = bytes.NewBuffer([]byte(endpoint.Body))
|
||||||
|
}
|
||||||
|
request, _ := http.NewRequest(endpoint.Method, endpoint.URL, bodyBuffer)
|
||||||
|
for k, v := range endpoint.Headers {
|
||||||
|
request.Header.Set(k, v)
|
||||||
|
if k == HostHeader {
|
||||||
|
request.Host = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
|
||||||
|
// needsToReadBody checks if there's any conditions that requires the response body to be read
|
||||||
|
func (endpoint *Endpoint) needsToReadBody() bool {
|
||||||
|
for _, condition := range endpoint.Conditions {
|
||||||
|
if condition.hasBodyPlaceholder() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import "github.com/TwiN/gatus/v3/util"
|
||||||
|
|
||||||
|
// EndpointStatus contains the evaluation Results of an Endpoint
|
||||||
|
type EndpointStatus struct {
|
||||||
|
// Name of the endpoint
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
|
||||||
|
// Group the endpoint is a part of. Used for grouping multiple endpoints together on the front end.
|
||||||
|
Group string `json:"group,omitempty"`
|
||||||
|
|
||||||
|
// Key is the key representing the EndpointStatus
|
||||||
|
Key string `json:"key"`
|
||||||
|
|
||||||
|
// Results is the list of endpoint evaluation results
|
||||||
|
Results []*Result `json:"results"`
|
||||||
|
|
||||||
|
// Events is a list of events
|
||||||
|
Events []*Event `json:"events,omitempty"`
|
||||||
|
|
||||||
|
// Uptime information on the endpoint's uptime
|
||||||
|
//
|
||||||
|
// Used by the memory store.
|
||||||
|
//
|
||||||
|
// To retrieve the uptime between two time, use store.GetUptimeByKey.
|
||||||
|
Uptime *Uptime `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewEndpointStatus creates a new EndpointStatus
|
||||||
|
func NewEndpointStatus(group, name string) *EndpointStatus {
|
||||||
|
return &EndpointStatus{
|
||||||
|
Name: name,
|
||||||
|
Group: group,
|
||||||
|
Key: util.ConvertGroupAndEndpointNameToKey(group, name),
|
||||||
|
Results: make([]*Result, 0),
|
||||||
|
Events: make([]*Event, 0),
|
||||||
|
Uptime: NewUptime(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNewEndpointStatus(t *testing.T) {
|
||||||
|
endpoint := &Endpoint{Name: "name", Group: "group"}
|
||||||
|
status := NewEndpointStatus(endpoint.Group, endpoint.Name)
|
||||||
|
if status.Name != endpoint.Name {
|
||||||
|
t.Errorf("expected %s, got %s", endpoint.Name, status.Name)
|
||||||
|
}
|
||||||
|
if status.Group != endpoint.Group {
|
||||||
|
t.Errorf("expected %s, got %s", endpoint.Group, status.Group)
|
||||||
|
}
|
||||||
|
if status.Key != "group_name" {
|
||||||
|
t.Errorf("expected %s, got %s", "group_name", status.Key)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package core
|
package core
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
"io"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -10,66 +10,66 @@ import (
|
|||||||
"github.com/TwiN/gatus/v3/client"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestService_IsEnabled(t *testing.T) {
|
func TestEndpoint_IsEnabled(t *testing.T) {
|
||||||
if !(Service{Enabled: nil}).IsEnabled() {
|
if !(Endpoint{Enabled: nil}).IsEnabled() {
|
||||||
t.Error("service.IsEnabled() should've returned true, because Enabled was set to nil")
|
t.Error("endpoint.IsEnabled() should've returned true, because Enabled was set to nil")
|
||||||
}
|
}
|
||||||
if value := false; (Service{Enabled: &value}).IsEnabled() {
|
if value := false; (Endpoint{Enabled: &value}).IsEnabled() {
|
||||||
t.Error("service.IsEnabled() should've returned false, because Enabled was set to false")
|
t.Error("endpoint.IsEnabled() should've returned false, because Enabled was set to false")
|
||||||
}
|
}
|
||||||
if value := true; !(Service{Enabled: &value}).IsEnabled() {
|
if value := true; !(Endpoint{Enabled: &value}).IsEnabled() {
|
||||||
t.Error("Service.IsEnabled() should've returned true, because Enabled was set to true")
|
t.Error("Endpoint.IsEnabled() should've returned true, because Enabled was set to true")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaults(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaults(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
Alerts: []*alert.Alert{{Type: alert.TypePagerDuty}},
|
Alerts: []*alert.Alert{{Type: alert.TypePagerDuty}},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
if service.ClientConfig == nil {
|
if endpoint.ClientConfig == nil {
|
||||||
t.Error("client configuration should've been set to the default configuration")
|
t.Error("client configuration should've been set to the default configuration")
|
||||||
} else {
|
} else {
|
||||||
if service.ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
if endpoint.ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
||||||
t.Errorf("Default client configuration should've set Insecure to %v, got %v", client.GetDefaultConfig().Insecure, service.ClientConfig.Insecure)
|
t.Errorf("Default client configuration should've set Insecure to %v, got %v", client.GetDefaultConfig().Insecure, endpoint.ClientConfig.Insecure)
|
||||||
}
|
}
|
||||||
if service.ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
if endpoint.ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
||||||
t.Errorf("Default client configuration should've set IgnoreRedirect to %v, got %v", client.GetDefaultConfig().IgnoreRedirect, service.ClientConfig.IgnoreRedirect)
|
t.Errorf("Default client configuration should've set IgnoreRedirect to %v, got %v", client.GetDefaultConfig().IgnoreRedirect, endpoint.ClientConfig.IgnoreRedirect)
|
||||||
}
|
}
|
||||||
if service.ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
if endpoint.ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
||||||
t.Errorf("Default client configuration should've set Timeout to %v, got %v", client.GetDefaultConfig().Timeout, service.ClientConfig.Timeout)
|
t.Errorf("Default client configuration should've set Timeout to %v, got %v", client.GetDefaultConfig().Timeout, endpoint.ClientConfig.Timeout)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if service.Method != "GET" {
|
if endpoint.Method != "GET" {
|
||||||
t.Error("Service method should've defaulted to GET")
|
t.Error("Endpoint method should've defaulted to GET")
|
||||||
}
|
}
|
||||||
if service.Interval != time.Minute {
|
if endpoint.Interval != time.Minute {
|
||||||
t.Error("Service interval should've defaulted to 1 minute")
|
t.Error("Endpoint interval should've defaulted to 1 minute")
|
||||||
}
|
}
|
||||||
if service.Headers == nil {
|
if endpoint.Headers == nil {
|
||||||
t.Error("Service headers should've defaulted to an empty map")
|
t.Error("Endpoint headers should've defaulted to an empty map")
|
||||||
}
|
}
|
||||||
if len(service.Alerts) != 1 {
|
if len(endpoint.Alerts) != 1 {
|
||||||
t.Error("Service should've had 1 alert")
|
t.Error("Endpoint should've had 1 alert")
|
||||||
}
|
}
|
||||||
if service.Alerts[0].IsEnabled() {
|
if endpoint.Alerts[0].IsEnabled() {
|
||||||
t.Error("Service alert should've defaulted to disabled")
|
t.Error("Endpoint alert should've defaulted to disabled")
|
||||||
}
|
}
|
||||||
if service.Alerts[0].SuccessThreshold != 2 {
|
if endpoint.Alerts[0].SuccessThreshold != 2 {
|
||||||
t.Error("Service alert should've defaulted to a success threshold of 2")
|
t.Error("Endpoint alert should've defaulted to a success threshold of 2")
|
||||||
}
|
}
|
||||||
if service.Alerts[0].FailureThreshold != 3 {
|
if endpoint.Alerts[0].FailureThreshold != 3 {
|
||||||
t.Error("Service alert should've defaulted to a failure threshold of 3")
|
t.Error("Endpoint alert should've defaulted to a failure threshold of 3")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
@@ -79,66 +79,66 @@ func TestService_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
|
|||||||
Timeout: 0,
|
Timeout: 0,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
if service.ClientConfig == nil {
|
if endpoint.ClientConfig == nil {
|
||||||
t.Error("client configuration should've been set to the default configuration")
|
t.Error("client configuration should've been set to the default configuration")
|
||||||
} else {
|
} else {
|
||||||
if !service.ClientConfig.Insecure {
|
if !endpoint.ClientConfig.Insecure {
|
||||||
t.Error("service.ClientConfig.Insecure should've been set to true")
|
t.Error("endpoint.ClientConfig.Insecure should've been set to true")
|
||||||
}
|
}
|
||||||
if !service.ClientConfig.IgnoreRedirect {
|
if !endpoint.ClientConfig.IgnoreRedirect {
|
||||||
t.Error("service.ClientConfig.IgnoreRedirect should've been set to true")
|
t.Error("endpoint.ClientConfig.IgnoreRedirect should've been set to true")
|
||||||
}
|
}
|
||||||
if service.ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
if endpoint.ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
||||||
t.Error("service.ClientConfig.Timeout should've been set to 10s, because the timeout value entered is not set or invalid")
|
t.Error("endpoint.ClientConfig.Timeout should've been set to 10s, because the timeout value entered is not set or invalid")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithNoName(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithNoName(t *testing.T) {
|
||||||
defer func() { recover() }()
|
defer func() { recover() }()
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := &Service{
|
endpoint := &Endpoint{
|
||||||
Name: "",
|
Name: "",
|
||||||
URL: "http://example.com",
|
URL: "http://example.com",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
}
|
}
|
||||||
err := service.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Should've returned an error because service didn't have a name, which is a mandatory field")
|
t.Fatal("Should've returned an error because endpoint didn't have a name, which is a mandatory field")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithNoUrl(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithNoUrl(t *testing.T) {
|
||||||
defer func() { recover() }()
|
defer func() { recover() }()
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := &Service{
|
endpoint := &Endpoint{
|
||||||
Name: "example",
|
Name: "example",
|
||||||
URL: "",
|
URL: "",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
}
|
}
|
||||||
err := service.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Should've returned an error because service didn't have an url, which is a mandatory field")
|
t.Fatal("Should've returned an error because endpoint didn't have an url, which is a mandatory field")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithNoConditions(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithNoConditions(t *testing.T) {
|
||||||
defer func() { recover() }()
|
defer func() { recover() }()
|
||||||
service := &Service{
|
endpoint := &Endpoint{
|
||||||
Name: "example",
|
Name: "example",
|
||||||
URL: "http://example.com",
|
URL: "http://example.com",
|
||||||
Conditions: nil,
|
Conditions: nil,
|
||||||
}
|
}
|
||||||
err := service.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Should've returned an error because service didn't have at least 1 condition")
|
t.Fatal("Should've returned an error because endpoint didn't have at least 1 condition")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithDNS(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithDNS(t *testing.T) {
|
||||||
conditionSuccess := Condition("[DNS_RCODE] == NOERROR")
|
conditionSuccess := Condition("[DNS_RCODE] == NOERROR")
|
||||||
service := &Service{
|
endpoint := &Endpoint{
|
||||||
Name: "dns-test",
|
Name: "dns-test",
|
||||||
URL: "http://example.com",
|
URL: "http://example.com",
|
||||||
DNS: &DNS{
|
DNS: &DNS{
|
||||||
@@ -147,24 +147,24 @@ func TestService_ValidateAndSetDefaultsWithDNS(t *testing.T) {
|
|||||||
},
|
},
|
||||||
Conditions: []*Condition{&conditionSuccess},
|
Conditions: []*Condition{&conditionSuccess},
|
||||||
}
|
}
|
||||||
err := service.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
||||||
}
|
}
|
||||||
if service.DNS.QueryName != "example.com." {
|
if endpoint.DNS.QueryName != "example.com." {
|
||||||
t.Error("Service.dns.query-name should be formatted with . suffix")
|
t.Error("Endpoint.dns.query-name should be formatted with . suffix")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_buildHTTPRequest(t *testing.T) {
|
func TestEndpoint_buildHTTPRequest(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
request := service.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "GET" {
|
if request.Method != "GET" {
|
||||||
t.Error("request.Method should've been GET, but was", request.Method)
|
t.Error("request.Method should've been GET, but was", request.Method)
|
||||||
}
|
}
|
||||||
@@ -176,9 +176,9 @@ func TestService_buildHTTPRequest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_buildHTTPRequestWithCustomUserAgent(t *testing.T) {
|
func TestEndpoint_buildHTTPRequestWithCustomUserAgent(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
@@ -186,8 +186,8 @@ func TestService_buildHTTPRequestWithCustomUserAgent(t *testing.T) {
|
|||||||
"User-Agent": "Test/2.0",
|
"User-Agent": "Test/2.0",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
request := service.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "GET" {
|
if request.Method != "GET" {
|
||||||
t.Error("request.Method should've been GET, but was", request.Method)
|
t.Error("request.Method should've been GET, but was", request.Method)
|
||||||
}
|
}
|
||||||
@@ -199,9 +199,9 @@ func TestService_buildHTTPRequestWithCustomUserAgent(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_buildHTTPRequestWithHostHeader(t *testing.T) {
|
func TestEndpoint_buildHTTPRequestWithHostHeader(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
@@ -210,8 +210,8 @@ func TestService_buildHTTPRequestWithHostHeader(t *testing.T) {
|
|||||||
"Host": "example.com",
|
"Host": "example.com",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
request := service.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "POST" {
|
if request.Method != "POST" {
|
||||||
t.Error("request.Method should've been POST, but was", request.Method)
|
t.Error("request.Method should've been POST, but was", request.Method)
|
||||||
}
|
}
|
||||||
@@ -220,9 +220,9 @@ func TestService_buildHTTPRequestWithHostHeader(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_buildHTTPRequestWithGraphQLEnabled(t *testing.T) {
|
func TestEndpoint_buildHTTPRequestWithGraphQLEnabled(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-graphql",
|
Name: "website-graphql",
|
||||||
URL: "https://twin.sh/graphql",
|
URL: "https://twin.sh/graphql",
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
@@ -237,15 +237,15 @@ func TestService_buildHTTPRequestWithGraphQLEnabled(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
request := service.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "POST" {
|
if request.Method != "POST" {
|
||||||
t.Error("request.Method should've been POST, but was", request.Method)
|
t.Error("request.Method should've been POST, but was", request.Method)
|
||||||
}
|
}
|
||||||
if contentType := request.Header.Get(ContentTypeHeader); contentType != "application/json" {
|
if contentType := request.Header.Get(ContentTypeHeader); contentType != "application/json" {
|
||||||
t.Error("request.Header.Content-Type should've been application/json, but was", contentType)
|
t.Error("request.Header.Content-Type should've been application/json, but was", contentType)
|
||||||
}
|
}
|
||||||
body, _ := ioutil.ReadAll(request.Body)
|
body, _ := io.ReadAll(request.Body)
|
||||||
if !strings.HasPrefix(string(body), "{\"query\":") {
|
if !strings.HasPrefix(string(body), "{\"query\":") {
|
||||||
t.Error("request.body should've started with '{\"query\":', but it didn't:", string(body))
|
t.Error("request.body should've started with '{\"query\":', but it didn't:", string(body))
|
||||||
}
|
}
|
||||||
@@ -254,13 +254,13 @@ func TestService_buildHTTPRequestWithGraphQLEnabled(t *testing.T) {
|
|||||||
func TestIntegrationEvaluateHealth(t *testing.T) {
|
func TestIntegrationEvaluateHealth(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
bodyCondition := Condition("[BODY].status == UP")
|
bodyCondition := Condition("[BODY].status == UP")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition, &bodyCondition},
|
Conditions: []*Condition{&condition, &bodyCondition},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
result := service.EvaluateHealth()
|
result := endpoint.EvaluateHealth()
|
||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
@@ -274,13 +274,13 @@ func TestIntegrationEvaluateHealth(t *testing.T) {
|
|||||||
|
|
||||||
func TestIntegrationEvaluateHealthWithFailure(t *testing.T) {
|
func TestIntegrationEvaluateHealthWithFailure(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 500")
|
condition := Condition("[STATUS] == 500")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
result := service.EvaluateHealth()
|
result := endpoint.EvaluateHealth()
|
||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
@@ -295,7 +295,7 @@ func TestIntegrationEvaluateHealthWithFailure(t *testing.T) {
|
|||||||
func TestIntegrationEvaluateHealthForDNS(t *testing.T) {
|
func TestIntegrationEvaluateHealthForDNS(t *testing.T) {
|
||||||
conditionSuccess := Condition("[DNS_RCODE] == NOERROR")
|
conditionSuccess := Condition("[DNS_RCODE] == NOERROR")
|
||||||
conditionBody := Condition("[BODY] == 93.184.216.34")
|
conditionBody := Condition("[BODY] == 93.184.216.34")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "example",
|
Name: "example",
|
||||||
URL: "8.8.8.8",
|
URL: "8.8.8.8",
|
||||||
DNS: &DNS{
|
DNS: &DNS{
|
||||||
@@ -304,8 +304,8 @@ func TestIntegrationEvaluateHealthForDNS(t *testing.T) {
|
|||||||
},
|
},
|
||||||
Conditions: []*Condition{&conditionSuccess, &conditionBody},
|
Conditions: []*Condition{&conditionSuccess, &conditionBody},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
result := service.EvaluateHealth()
|
result := endpoint.EvaluateHealth()
|
||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Conditions '%s' and %s should have been a success", conditionSuccess, conditionBody)
|
t.Errorf("Conditions '%s' and %s should have been a success", conditionSuccess, conditionBody)
|
||||||
}
|
}
|
||||||
@@ -319,13 +319,13 @@ func TestIntegrationEvaluateHealthForDNS(t *testing.T) {
|
|||||||
|
|
||||||
func TestIntegrationEvaluateHealthForICMP(t *testing.T) {
|
func TestIntegrationEvaluateHealthForICMP(t *testing.T) {
|
||||||
conditionSuccess := Condition("[CONNECTED] == true")
|
conditionSuccess := Condition("[CONNECTED] == true")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "icmp-test",
|
Name: "icmp-test",
|
||||||
URL: "icmp://127.0.0.1",
|
URL: "icmp://127.0.0.1",
|
||||||
Conditions: []*Condition{&conditionSuccess},
|
Conditions: []*Condition{&conditionSuccess},
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
endpoint.ValidateAndSetDefaults()
|
||||||
result := service.EvaluateHealth()
|
result := endpoint.EvaluateHealth()
|
||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Conditions '%s' should have been a success", conditionSuccess)
|
t.Errorf("Conditions '%s' should have been a success", conditionSuccess)
|
||||||
}
|
}
|
||||||
@@ -337,40 +337,40 @@ func TestIntegrationEvaluateHealthForICMP(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_getIP(t *testing.T) {
|
func TestEndpoint_getIP(t *testing.T) {
|
||||||
conditionSuccess := Condition("[CONNECTED] == true")
|
conditionSuccess := Condition("[CONNECTED] == true")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "invalid-url-test",
|
Name: "invalid-url-test",
|
||||||
URL: "",
|
URL: "",
|
||||||
Conditions: []*Condition{&conditionSuccess},
|
Conditions: []*Condition{&conditionSuccess},
|
||||||
}
|
}
|
||||||
result := &Result{}
|
result := &Result{}
|
||||||
service.getIP(result)
|
endpoint.getIP(result)
|
||||||
if len(result.Errors) == 0 {
|
if len(result.Errors) == 0 {
|
||||||
t.Error("service.getIP(result) should've thrown an error because the URL is invalid, thus cannot be parsed")
|
t.Error("endpoint.getIP(result) should've thrown an error because the URL is invalid, thus cannot be parsed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_NeedsToReadBody(t *testing.T) {
|
func TestEndpoint_NeedsToReadBody(t *testing.T) {
|
||||||
statusCondition := Condition("[STATUS] == 200")
|
statusCondition := Condition("[STATUS] == 200")
|
||||||
bodyCondition := Condition("[BODY].status == UP")
|
bodyCondition := Condition("[BODY].status == UP")
|
||||||
bodyConditionWithLength := Condition("len([BODY].tags) > 0")
|
bodyConditionWithLength := Condition("len([BODY].tags) > 0")
|
||||||
if (&Service{Conditions: []*Condition{&statusCondition}}).needsToReadBody() {
|
if (&Endpoint{Conditions: []*Condition{&statusCondition}}).needsToReadBody() {
|
||||||
t.Error("expected false, got true")
|
t.Error("expected false, got true")
|
||||||
}
|
}
|
||||||
if !(&Service{Conditions: []*Condition{&bodyCondition}}).needsToReadBody() {
|
if !(&Endpoint{Conditions: []*Condition{&bodyCondition}}).needsToReadBody() {
|
||||||
t.Error("expected true, got false")
|
t.Error("expected true, got false")
|
||||||
}
|
}
|
||||||
if !(&Service{Conditions: []*Condition{&bodyConditionWithLength}}).needsToReadBody() {
|
if !(&Endpoint{Conditions: []*Condition{&bodyConditionWithLength}}).needsToReadBody() {
|
||||||
t.Error("expected true, got false")
|
t.Error("expected true, got false")
|
||||||
}
|
}
|
||||||
if !(&Service{Conditions: []*Condition{&statusCondition, &bodyCondition}}).needsToReadBody() {
|
if !(&Endpoint{Conditions: []*Condition{&statusCondition, &bodyCondition}}).needsToReadBody() {
|
||||||
t.Error("expected true, got false")
|
t.Error("expected true, got false")
|
||||||
}
|
}
|
||||||
if !(&Service{Conditions: []*Condition{&bodyCondition, &statusCondition}}).needsToReadBody() {
|
if !(&Endpoint{Conditions: []*Condition{&bodyCondition, &statusCondition}}).needsToReadBody() {
|
||||||
t.Error("expected true, got false")
|
t.Error("expected true, got false")
|
||||||
}
|
}
|
||||||
if !(&Service{Conditions: []*Condition{&bodyConditionWithLength, &statusCondition}}).needsToReadBody() {
|
if !(&Endpoint{Conditions: []*Condition{&bodyConditionWithLength, &statusCondition}}).needsToReadBody() {
|
||||||
t.Error("expected true, got false")
|
t.Error("expected true, got false")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,13 +15,13 @@ type Event struct {
|
|||||||
type EventType string
|
type EventType string
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// EventStart is a type of event that represents when a service starts being monitored
|
// EventStart is a type of event that represents when an endpoint starts being monitored
|
||||||
EventStart EventType = "START"
|
EventStart EventType = "START"
|
||||||
|
|
||||||
// EventHealthy is a type of event that represents a service passing all of its conditions
|
// EventHealthy is a type of event that represents an endpoint passing all of its conditions
|
||||||
EventHealthy EventType = "HEALTHY"
|
EventHealthy EventType = "HEALTHY"
|
||||||
|
|
||||||
// EventUnhealthy is a type of event that represents a service failing one or more of its conditions
|
// EventUnhealthy is a type of event that represents an endpoint failing one or more of its conditions
|
||||||
EventUnhealthy EventType = "UNHEALTHY"
|
EventUnhealthy EventType = "UNHEALTHY"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -4,18 +4,18 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Result of the evaluation of a Service
|
// Result of the evaluation of a Endpoint
|
||||||
type Result struct {
|
type Result struct {
|
||||||
// HTTPStatus is the HTTP response status code
|
// HTTPStatus is the HTTP response status code
|
||||||
HTTPStatus int `json:"status"`
|
HTTPStatus int `json:"status"`
|
||||||
|
|
||||||
// DNSRCode is the response code of a DNS query in a human readable format
|
// DNSRCode is the response code of a DNS query in a human-readable format
|
||||||
DNSRCode string `json:"-"`
|
DNSRCode string `json:"-"`
|
||||||
|
|
||||||
// Hostname extracted from Service.URL
|
// Hostname extracted from Endpoint.URL
|
||||||
Hostname string `json:"hostname"`
|
Hostname string `json:"hostname,omitempty"`
|
||||||
|
|
||||||
// IP resolved from the Service URL
|
// IP resolved from the Endpoint URL
|
||||||
IP string `json:"-"`
|
IP string `json:"-"`
|
||||||
|
|
||||||
// Connected whether a connection to the host was established successfully
|
// Connected whether a connection to the host was established successfully
|
||||||
@@ -24,10 +24,10 @@ type Result struct {
|
|||||||
// Duration time that the request took
|
// Duration time that the request took
|
||||||
Duration time.Duration `json:"duration"`
|
Duration time.Duration `json:"duration"`
|
||||||
|
|
||||||
// Errors encountered during the evaluation of the service's health
|
// Errors encountered during the evaluation of the Endpoint's health
|
||||||
Errors []string `json:"errors"`
|
Errors []string `json:"errors,omitempty"`
|
||||||
|
|
||||||
// ConditionResults results of the service's conditions
|
// ConditionResults results of the Endpoint's conditions
|
||||||
ConditionResults []*ConditionResult `json:"conditionResults"`
|
ConditionResults []*ConditionResult `json:"conditionResults"`
|
||||||
|
|
||||||
// Success whether the result signifies a success or not
|
// Success whether the result signifies a success or not
|
||||||
@@ -41,8 +41,8 @@ type Result struct {
|
|||||||
|
|
||||||
// body is the response body
|
// body is the response body
|
||||||
//
|
//
|
||||||
// Note that this variable is only used during the evaluation of a service's health.
|
// Note that this variable is only used during the evaluation of an Endpoint's health.
|
||||||
// This means that the call Service.EvaluateHealth both populates the body (if necessary)
|
// This means that the call Endpoint.EvaluateHealth both populates the body (if necessary)
|
||||||
// and sets it to nil after the evaluation has been completed.
|
// and sets it to nil after the evaluation has been completed.
|
||||||
body []byte
|
body []byte
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,300 +0,0 @@
|
|||||||
package core
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io/ioutil"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v3/alerting/alert"
|
|
||||||
"github.com/TwiN/gatus/v3/client"
|
|
||||||
"github.com/TwiN/gatus/v3/core/ui"
|
|
||||||
"github.com/TwiN/gatus/v3/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// HostHeader is the name of the header used to specify the host
|
|
||||||
HostHeader = "Host"
|
|
||||||
|
|
||||||
// ContentTypeHeader is the name of the header used to specify the content type
|
|
||||||
ContentTypeHeader = "Content-Type"
|
|
||||||
|
|
||||||
// UserAgentHeader is the name of the header used to specify the request's user agent
|
|
||||||
UserAgentHeader = "User-Agent"
|
|
||||||
|
|
||||||
// GatusUserAgent is the default user agent that Gatus uses to send requests.
|
|
||||||
GatusUserAgent = "Gatus/1.0"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ErrServiceWithNoCondition is the error with which Gatus will panic if a service is configured with no conditions
|
|
||||||
ErrServiceWithNoCondition = errors.New("you must specify at least one condition per service")
|
|
||||||
|
|
||||||
// ErrServiceWithNoURL is the error with which Gatus will panic if a service is configured with no url
|
|
||||||
ErrServiceWithNoURL = errors.New("you must specify an url for each service")
|
|
||||||
|
|
||||||
// ErrServiceWithNoName is the error with which Gatus will panic if a service is configured with no name
|
|
||||||
ErrServiceWithNoName = errors.New("you must specify a name for each service")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Service is the configuration of a monitored endpoint
|
|
||||||
// XXX: Rename this to Endpoint in v4.0.0?
|
|
||||||
type Service struct {
|
|
||||||
// Enabled defines whether to enable the service
|
|
||||||
Enabled *bool `yaml:"enabled,omitempty"`
|
|
||||||
|
|
||||||
// Name of the service. Can be anything.
|
|
||||||
Name string `yaml:"name"`
|
|
||||||
|
|
||||||
// Group the service is a part of. Used for grouping multiple services together on the front end.
|
|
||||||
Group string `yaml:"group,omitempty"`
|
|
||||||
|
|
||||||
// URL to send the request to
|
|
||||||
URL string `yaml:"url"`
|
|
||||||
|
|
||||||
// DNS is the configuration of DNS monitoring
|
|
||||||
DNS *DNS `yaml:"dns,omitempty"`
|
|
||||||
|
|
||||||
// Method of the request made to the url of the service
|
|
||||||
Method string `yaml:"method,omitempty"`
|
|
||||||
|
|
||||||
// Body of the request
|
|
||||||
Body string `yaml:"body,omitempty"`
|
|
||||||
|
|
||||||
// GraphQL is whether to wrap the body in a query param ({"query":"$body"})
|
|
||||||
GraphQL bool `yaml:"graphql,omitempty"`
|
|
||||||
|
|
||||||
// Headers of the request
|
|
||||||
Headers map[string]string `yaml:"headers,omitempty"`
|
|
||||||
|
|
||||||
// Interval is the duration to wait between every status check
|
|
||||||
Interval time.Duration `yaml:"interval,omitempty"`
|
|
||||||
|
|
||||||
// Conditions used to determine the health of the service
|
|
||||||
Conditions []*Condition `yaml:"conditions"`
|
|
||||||
|
|
||||||
// Alerts is the alerting configuration for the service in case of failure
|
|
||||||
Alerts []*alert.Alert `yaml:"alerts"`
|
|
||||||
|
|
||||||
// ClientConfig is the configuration of the client used to communicate with the service's target
|
|
||||||
ClientConfig *client.Config `yaml:"client"`
|
|
||||||
|
|
||||||
// UIConfig is the configuration for the UI
|
|
||||||
UIConfig *ui.Config `yaml:"ui"`
|
|
||||||
|
|
||||||
// NumberOfFailuresInARow is the number of unsuccessful evaluations in a row
|
|
||||||
NumberOfFailuresInARow int
|
|
||||||
|
|
||||||
// NumberOfSuccessesInARow is the number of successful evaluations in a row
|
|
||||||
NumberOfSuccessesInARow int
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsEnabled returns whether the service is enabled or not
|
|
||||||
func (service Service) IsEnabled() bool {
|
|
||||||
if service.Enabled == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return *service.Enabled
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidateAndSetDefaults validates the service's configuration and sets the default value of fields that have one
|
|
||||||
func (service *Service) ValidateAndSetDefaults() error {
|
|
||||||
// Set default values
|
|
||||||
if service.ClientConfig == nil {
|
|
||||||
service.ClientConfig = client.GetDefaultConfig()
|
|
||||||
} else {
|
|
||||||
service.ClientConfig.ValidateAndSetDefaults()
|
|
||||||
}
|
|
||||||
if service.UIConfig == nil {
|
|
||||||
service.UIConfig = ui.GetDefaultConfig()
|
|
||||||
}
|
|
||||||
if service.Interval == 0 {
|
|
||||||
service.Interval = 1 * time.Minute
|
|
||||||
}
|
|
||||||
if len(service.Method) == 0 {
|
|
||||||
service.Method = http.MethodGet
|
|
||||||
}
|
|
||||||
if len(service.Headers) == 0 {
|
|
||||||
service.Headers = make(map[string]string)
|
|
||||||
}
|
|
||||||
// Automatically add user agent header if there isn't one specified in the service configuration
|
|
||||||
if _, userAgentHeaderExists := service.Headers[UserAgentHeader]; !userAgentHeaderExists {
|
|
||||||
service.Headers[UserAgentHeader] = GatusUserAgent
|
|
||||||
}
|
|
||||||
// Automatically add "Content-Type: application/json" header if there's no Content-Type set
|
|
||||||
// and service.GraphQL is set to true
|
|
||||||
if _, contentTypeHeaderExists := service.Headers[ContentTypeHeader]; !contentTypeHeaderExists && service.GraphQL {
|
|
||||||
service.Headers[ContentTypeHeader] = "application/json"
|
|
||||||
}
|
|
||||||
for _, serviceAlert := range service.Alerts {
|
|
||||||
if serviceAlert.FailureThreshold <= 0 {
|
|
||||||
serviceAlert.FailureThreshold = 3
|
|
||||||
}
|
|
||||||
if serviceAlert.SuccessThreshold <= 0 {
|
|
||||||
serviceAlert.SuccessThreshold = 2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(service.Name) == 0 {
|
|
||||||
return ErrServiceWithNoName
|
|
||||||
}
|
|
||||||
if len(service.URL) == 0 {
|
|
||||||
return ErrServiceWithNoURL
|
|
||||||
}
|
|
||||||
if len(service.Conditions) == 0 {
|
|
||||||
return ErrServiceWithNoCondition
|
|
||||||
}
|
|
||||||
if service.DNS != nil {
|
|
||||||
return service.DNS.validateAndSetDefault()
|
|
||||||
}
|
|
||||||
// Make sure that the request can be created
|
|
||||||
_, err := http.NewRequest(service.Method, service.URL, bytes.NewBuffer([]byte(service.Body)))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key returns the unique key for the Service
|
|
||||||
func (service Service) Key() string {
|
|
||||||
return util.ConvertGroupAndServiceToKey(service.Group, service.Name)
|
|
||||||
}
|
|
||||||
|
|
||||||
// EvaluateHealth sends a request to the service's URL and evaluates the conditions of the service.
|
|
||||||
func (service *Service) EvaluateHealth() *Result {
|
|
||||||
result := &Result{Success: true, Errors: []string{}}
|
|
||||||
service.getIP(result)
|
|
||||||
if len(result.Errors) == 0 {
|
|
||||||
service.call(result)
|
|
||||||
} else {
|
|
||||||
result.Success = false
|
|
||||||
}
|
|
||||||
for _, condition := range service.Conditions {
|
|
||||||
success := condition.evaluate(result, service.UIConfig.DontResolveFailedConditions)
|
|
||||||
if !success {
|
|
||||||
result.Success = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
result.Timestamp = time.Now()
|
|
||||||
// No need to keep the body after the service has been evaluated
|
|
||||||
result.body = nil
|
|
||||||
// Clean up parameters that we don't need to keep in the results
|
|
||||||
if service.UIConfig.HideHostname {
|
|
||||||
result.Hostname = ""
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func (service *Service) getIP(result *Result) {
|
|
||||||
if service.DNS != nil {
|
|
||||||
result.Hostname = strings.TrimSuffix(service.URL, ":53")
|
|
||||||
} else {
|
|
||||||
urlObject, err := url.Parse(service.URL)
|
|
||||||
if err != nil {
|
|
||||||
result.AddError(err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
result.Hostname = urlObject.Hostname()
|
|
||||||
}
|
|
||||||
ips, err := net.LookupIP(result.Hostname)
|
|
||||||
if err != nil {
|
|
||||||
result.AddError(err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
result.IP = ips[0].String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (service *Service) call(result *Result) {
|
|
||||||
var request *http.Request
|
|
||||||
var response *http.Response
|
|
||||||
var err error
|
|
||||||
var certificate *x509.Certificate
|
|
||||||
isServiceDNS := service.DNS != nil
|
|
||||||
isServiceTCP := strings.HasPrefix(service.URL, "tcp://")
|
|
||||||
isServiceICMP := strings.HasPrefix(service.URL, "icmp://")
|
|
||||||
isServiceStartTLS := strings.HasPrefix(service.URL, "starttls://")
|
|
||||||
isServiceTLS := strings.HasPrefix(service.URL, "tls://")
|
|
||||||
isServiceHTTP := !isServiceDNS && !isServiceTCP && !isServiceICMP && !isServiceStartTLS && !isServiceTLS
|
|
||||||
if isServiceHTTP {
|
|
||||||
request = service.buildHTTPRequest()
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
|
||||||
if isServiceDNS {
|
|
||||||
service.DNS.query(service.URL, result)
|
|
||||||
result.Duration = time.Since(startTime)
|
|
||||||
} else if isServiceStartTLS || isServiceTLS {
|
|
||||||
if isServiceStartTLS {
|
|
||||||
result.Connected, certificate, err = client.CanPerformStartTLS(strings.TrimPrefix(service.URL, "starttls://"), service.ClientConfig)
|
|
||||||
} else {
|
|
||||||
result.Connected, certificate, err = client.CanPerformTLS(strings.TrimPrefix(service.URL, "tls://"), service.ClientConfig)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
result.AddError(err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
result.Duration = time.Since(startTime)
|
|
||||||
result.CertificateExpiration = time.Until(certificate.NotAfter)
|
|
||||||
} else if isServiceTCP {
|
|
||||||
result.Connected = client.CanCreateTCPConnection(strings.TrimPrefix(service.URL, "tcp://"), service.ClientConfig)
|
|
||||||
result.Duration = time.Since(startTime)
|
|
||||||
} else if isServiceICMP {
|
|
||||||
result.Connected, result.Duration = client.Ping(strings.TrimPrefix(service.URL, "icmp://"), service.ClientConfig)
|
|
||||||
} else {
|
|
||||||
response, err = client.GetHTTPClient(service.ClientConfig).Do(request)
|
|
||||||
result.Duration = time.Since(startTime)
|
|
||||||
if err != nil {
|
|
||||||
result.AddError(err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer response.Body.Close()
|
|
||||||
if response.TLS != nil && len(response.TLS.PeerCertificates) > 0 {
|
|
||||||
certificate = response.TLS.PeerCertificates[0]
|
|
||||||
result.CertificateExpiration = time.Until(certificate.NotAfter)
|
|
||||||
}
|
|
||||||
result.HTTPStatus = response.StatusCode
|
|
||||||
result.Connected = response.StatusCode > 0
|
|
||||||
// Only read the body if there's a condition that uses the BodyPlaceholder
|
|
||||||
if service.needsToReadBody() {
|
|
||||||
result.body, err = ioutil.ReadAll(response.Body)
|
|
||||||
if err != nil {
|
|
||||||
result.AddError(err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (service *Service) buildHTTPRequest() *http.Request {
|
|
||||||
var bodyBuffer *bytes.Buffer
|
|
||||||
if service.GraphQL {
|
|
||||||
graphQlBody := map[string]string{
|
|
||||||
"query": service.Body,
|
|
||||||
}
|
|
||||||
body, _ := json.Marshal(graphQlBody)
|
|
||||||
bodyBuffer = bytes.NewBuffer(body)
|
|
||||||
} else {
|
|
||||||
bodyBuffer = bytes.NewBuffer([]byte(service.Body))
|
|
||||||
}
|
|
||||||
request, _ := http.NewRequest(service.Method, service.URL, bodyBuffer)
|
|
||||||
for k, v := range service.Headers {
|
|
||||||
request.Header.Set(k, v)
|
|
||||||
if k == HostHeader {
|
|
||||||
request.Host = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return request
|
|
||||||
}
|
|
||||||
|
|
||||||
// needsToReadBody checks if there's any conditions that requires the response body to be read
|
|
||||||
func (service *Service) needsToReadBody() bool {
|
|
||||||
for _, condition := range service.Conditions {
|
|
||||||
if condition.hasBodyPlaceholder() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
package core
|
|
||||||
|
|
||||||
// ServiceStatus contains the evaluation Results of a Service
|
|
||||||
type ServiceStatus struct {
|
|
||||||
// Name of the service
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
|
|
||||||
// Group the service is a part of. Used for grouping multiple services together on the front end.
|
|
||||||
Group string `json:"group,omitempty"`
|
|
||||||
|
|
||||||
// Key is the key representing the ServiceStatus
|
|
||||||
Key string `json:"key"`
|
|
||||||
|
|
||||||
// Results is the list of service evaluation results
|
|
||||||
Results []*Result `json:"results"`
|
|
||||||
|
|
||||||
// Events is a list of events
|
|
||||||
Events []*Event `json:"events"`
|
|
||||||
|
|
||||||
// Uptime information on the service's uptime
|
|
||||||
//
|
|
||||||
// Used by the memory store.
|
|
||||||
//
|
|
||||||
// To retrieve the uptime between two time, use store.GetUptimeByKey.
|
|
||||||
Uptime *Uptime `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewServiceStatus creates a new ServiceStatus
|
|
||||||
func NewServiceStatus(serviceKey, serviceGroup, serviceName string) *ServiceStatus {
|
|
||||||
return &ServiceStatus{
|
|
||||||
Name: serviceName,
|
|
||||||
Group: serviceGroup,
|
|
||||||
Key: serviceKey,
|
|
||||||
Results: make([]*Result, 0),
|
|
||||||
Events: make([]*Event, 0),
|
|
||||||
Uptime: NewUptime(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package core
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewServiceStatus(t *testing.T) {
|
|
||||||
service := &Service{Name: "name", Group: "group"}
|
|
||||||
serviceStatus := NewServiceStatus(service.Key(), service.Group, service.Name)
|
|
||||||
if serviceStatus.Name != service.Name {
|
|
||||||
t.Errorf("expected %s, got %s", service.Name, serviceStatus.Name)
|
|
||||||
}
|
|
||||||
if serviceStatus.Group != service.Group {
|
|
||||||
t.Errorf("expected %s, got %s", service.Group, serviceStatus.Group)
|
|
||||||
}
|
|
||||||
if serviceStatus.Key != "group_name" {
|
|
||||||
t.Errorf("expected %s, got %s", "group_name", serviceStatus.Key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||