Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
8088736d6e | ||
|
|
6c45f5b99c | ||
|
|
422eaa6d37 | ||
|
|
c423afb0bf | ||
|
|
835f768337 | ||
|
|
b3d0e54af2 | ||
|
|
1451cdfa64 | ||
|
|
53cc9d88e5 | ||
|
|
a6bc0039e9 | ||
|
|
adbc2c5ad7 | ||
|
|
154bc7dbc6 | ||
|
|
2d3fe9795f | ||
|
|
d19f564e4e | ||
|
|
babe7b0be9 | ||
|
|
dee04945d0 | ||
|
|
bf455fb7cc | ||
|
|
dfd2f7943f | ||
|
|
fece11540b | ||
|
|
ac43ef4ab7 | ||
|
|
bc25fea1c0 | ||
|
|
30cb7b6ec8 | ||
|
|
289d834587 | ||
|
|
428e415616 | ||
|
|
0d284c2494 | ||
|
|
4a46a5ae9e | ||
|
|
df3a2016ff | ||
|
|
dda83761b5 | ||
|
|
882444e0d5 | ||
|
|
fa4736c672 | ||
|
|
dc173b29bc | ||
|
|
c3a4ce1eb4 | ||
|
|
044f0454f8 | ||
|
|
9bd5c38a96 | ||
|
|
d6b4c2394a | ||
|
|
9fe4678193 |
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
examples
|
.examples
|
||||||
Dockerfile
|
Dockerfile
|
||||||
.github
|
.github
|
||||||
.idea
|
.idea
|
||||||
|
|||||||
+5
-5
@@ -1,16 +1,16 @@
|
|||||||
metrics: true
|
metrics: true
|
||||||
services:
|
endpoints:
|
||||||
- name: TwiNNatioN
|
- name: website
|
||||||
url: https://twinnation.org/health
|
url: https://twin.sh/health
|
||||||
interval: 30s
|
interval: 30s
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
- 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: Example
|
- name: example
|
||||||
url: https://example.com/
|
url: https://example.com/
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+6
-6
@@ -58,9 +58,9 @@
|
|||||||
"steppedLine": false,
|
"steppedLine": false,
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"expr": "sum(rate(gatus_tasks[30s])) by (service)",
|
"expr": "sum(rate(gatus_tasks[30s])) by (endpoint)",
|
||||||
"interval": "30s",
|
"interval": "30s",
|
||||||
"legendFormat": "{{service}}",
|
"legendFormat": "{{endpoint}}",
|
||||||
"refId": "A"
|
"refId": "A"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -145,9 +145,9 @@
|
|||||||
"steppedLine": false,
|
"steppedLine": false,
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"expr": "sum(rate(gatus_tasks{success=\"false\"}[30s])) by (service)",
|
"expr": "sum(rate(gatus_tasks{success=\"false\"}[30s])) by (endpoint)",
|
||||||
"interval": "30s",
|
"interval": "30s",
|
||||||
"legendFormat": "{{service}}",
|
"legendFormat": "{{endpoint}}",
|
||||||
"refId": "A"
|
"refId": "A"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -232,10 +232,10 @@
|
|||||||
"steppedLine": false,
|
"steppedLine": false,
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"expr": "sum(rate(gatus_tasks{success=\"true\"}[30s])) by (service)",
|
"expr": "sum(rate(gatus_tasks{success=\"true\"}[30s])) by (endpoint)",
|
||||||
"instant": false,
|
"instant": false,
|
||||||
"interval": "30s",
|
"interval": "30s",
|
||||||
"legendFormat": "{{service}}",
|
"legendFormat": "{{endpoint}}",
|
||||||
"refId": "A"
|
"refId": "A"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
File renamed without changes.
File renamed without changes.
+3
-3
@@ -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"
|
||||||
File renamed without changes.
+2
-2
@@ -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/"
|
||||||
File renamed without changes.
+2
-2
@@ -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/"
|
||||||
File renamed without changes.
File renamed without changes.
@@ -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"
|
||||||
File renamed without changes.
File renamed without changes.
@@ -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: TwiNNatioN
|
- name: website
|
||||||
url: https://twinnation.org/health
|
url: https://twin.sh/health
|
||||||
interval: 1m
|
interval: 5m
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
- name: GitHub
|
- "[BODY].status == UP"
|
||||||
|
|
||||||
|
- 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
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
* text=lf
|
* text=auto eol=lf
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
github: [TwinProduction]
|
github: [TwiN]
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 38 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 43 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
File renamed without changes.
Binary file not shown.
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 43 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
@@ -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
|
||||||
@@ -14,7 +14,7 @@ jobs:
|
|||||||
- name: Check out code
|
- name: Check out code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
- name: Get image repository
|
- name: Get image repository
|
||||||
run: echo IMAGE_REPOSITORY=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV
|
run: echo IMAGE_REPOSITORY=$(echo ${{ secrets.DOCKER_USERNAME }}/${{ github.event.repository.name }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v1
|
uses: docker/setup-qemu-action@v1
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ jobs:
|
|||||||
- name: Check out code
|
- name: Check out code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
- name: Get image repository
|
- name: Get image repository
|
||||||
run: echo IMAGE_REPOSITORY=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV
|
run: echo IMAGE_REPOSITORY=$(echo ${{ secrets.DOCKER_USERNAME }}/${{ github.event.repository.name }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV
|
||||||
- name: Get the release
|
- name: Get the release
|
||||||
run: echo RELEASE=${GITHUB_REF/refs\/tags\//} >> $GITHUB_ENV
|
run: echo RELEASE=${GITHUB_REF/refs\/tags\//} >> $GITHUB_ENV
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
@@ -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: |
|
||||||
|
|||||||
@@ -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,11 +1,11 @@
|
|||||||
package alert
|
package alert
|
||||||
|
|
||||||
// Alert is the service's alert configuration
|
// 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.
|
||||||
|
|||||||
+11
-11
@@ -1,17 +1,17 @@
|
|||||||
package alerting
|
package alerting
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider"
|
"github.com/TwiN/gatus/v3/alerting/provider"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/discord"
|
"github.com/TwiN/gatus/v3/alerting/provider/discord"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v3/alerting/provider/mattermost"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v3/alerting/provider/messagebird"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/pagerduty"
|
"github.com/TwiN/gatus/v3/alerting/provider/pagerduty"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/slack"
|
"github.com/TwiN/gatus/v3/alerting/provider/slack"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/teams"
|
"github.com/TwiN/gatus/v3/alerting/provider/teams"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/telegram"
|
"github.com/TwiN/gatus/v3/alerting/provider/telegram"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/twilio"
|
"github.com/TwiN/gatus/v3/alerting/provider/twilio"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config is the configuration for alerting providers
|
// Config is the configuration for alerting providers
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/client"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using a custom HTTP request
|
// AlertProvider is the configuration necessary for sending an alert using a custom HTTP request
|
||||||
@@ -26,7 +26,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *AlertProvider {
|
func (provider *AlertProvider) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) *AlertProvider {
|
||||||
return provider
|
return provider
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +57,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 +65,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 +81,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 {
|
||||||
@@ -100,14 +106,14 @@ func (provider *AlertProvider) buildHTTPRequest(serviceName, alertDescription st
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Send a request to the alert provider and return the body
|
// Send a request to the alert provider and return the body
|
||||||
func (provider *AlertProvider) Send(serviceName, alertDescription string, resolved bool) ([]byte, error) {
|
func (provider *AlertProvider) Send(endpointName, alertDescription string, resolved bool) ([]byte, error) {
|
||||||
if os.Getenv("MOCK_ALERT_PROVIDER") == "true" {
|
if os.Getenv("MOCK_ALERT_PROVIDER") == "true" {
|
||||||
if os.Getenv("MOCK_ALERT_PROVIDER_ERROR") == "true" {
|
if os.Getenv("MOCK_ALERT_PROVIDER_ERROR") == "true" {
|
||||||
return nil, errors.New("error")
|
return nil, errors.New("error")
|
||||||
}
|
}
|
||||||
return []byte("{}"), nil
|
return []byte("{}"), nil
|
||||||
}
|
}
|
||||||
request := provider.buildHTTPRequest(serviceName, alertDescription, resolved)
|
request := provider.buildHTTPRequest(endpointName, 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 nil, err
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -13,7 +13,7 @@ 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")
|
||||||
}
|
}
|
||||||
@@ -21,15 +21,15 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
|
|
||||||
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())
|
||||||
}
|
}
|
||||||
@@ -41,15 +41,15 @@ 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())
|
||||||
}
|
}
|
||||||
@@ -60,24 +60,24 @@ func TestAlertProvider_buildHTTPRequestWhenTriggered(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProvider(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProvider(t *testing.T) {
|
||||||
provider := AlertProvider{URL: "http://example.com"}
|
provider := AlertProvider{URL: "https://example.com"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
if customAlertProvider.URL != "http://example.com" {
|
if customAlertProvider.URL != "https://example.com" {
|
||||||
t.Error("expected URL to be http://example.com, got", customAlertProvider.URL)
|
t.Error("expected URL to be https://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,7 +85,7 @@ 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())
|
||||||
}
|
}
|
||||||
@@ -97,8 +97,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 +109,26 @@ func TestAlertProvider_GetAlertStatePlaceholderValueDefaults(t *testing.T) {
|
|||||||
t.Error("expected TRIGGERED, got", customAlertProvider.GetAlertStatePlaceholderValue(false))
|
t.Error("expected TRIGGERED, got", customAlertProvider.GetAlertStatePlaceholderValue(false))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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, _ := ioutil.ReadAll(request.Body)
|
||||||
|
if string(body) != ExpectedBody {
|
||||||
|
t.Error("expected body to be", ExpectedBody, "was", string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,16 +4,16 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using Discord
|
// AlertProvider is the configuration necessary for sending an alert using Discord
|
||||||
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,14 +23,14 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
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.Name, 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.Name, alert.FailureThreshold)
|
||||||
colorCode = 15158332
|
colorCode = 15158332
|
||||||
}
|
}
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -24,7 +24,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
provider := AlertProvider{WebhookURL: "http://example.com"}
|
||||||
alertDescription := "test"
|
alertDescription := "test"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
provider := AlertProvider{WebhookURL: "http://example.com"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/client"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using Mattermost
|
// AlertProvider is the configuration necessary for sending an alert using Mattermost
|
||||||
@@ -17,7 +17,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,14 +30,14 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
var message string
|
var message string
|
||||||
var color string
|
var 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.Name, 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.Name, alert.FailureThreshold)
|
||||||
color = "#DD0000"
|
color = "#DD0000"
|
||||||
}
|
}
|
||||||
var results string
|
var results string
|
||||||
@@ -61,7 +61,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
Body: fmt.Sprintf(`{
|
Body: fmt.Sprintf(`{
|
||||||
"text": "",
|
"text": "",
|
||||||
"username": "gatus",
|
"username": "gatus",
|
||||||
"icon_url": "https://raw.githubusercontent.com/TwinProduction/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,7 +83,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"},
|
Headers: map[string]string{"Content-Type": "application/json"},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -24,7 +24,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
provider := AlertProvider{WebhookURL: "http://example.org"}
|
||||||
alertDescription := "test"
|
alertDescription := "test"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
provider := AlertProvider{WebhookURL: "http://example.org"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -19,7 +19,7 @@ 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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,14 +30,13 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
// 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) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, _ *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
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.Name, alert.GetDescription())
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("TRIGGERED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("TRIGGERED: %s - %s", endpoint.Name, alert.GetDescription())
|
||||||
}
|
}
|
||||||
|
|
||||||
return &custom.AlertProvider{
|
return &custom.AlertProvider{
|
||||||
URL: restAPIURL,
|
URL: restAPIURL,
|
||||||
Method: http.MethodPost,
|
Method: http.MethodPost,
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMessagebirdAlertProvider_IsValid(t *testing.T) {
|
func TestMessagebirdAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -31,7 +31,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
Originator: "1",
|
Originator: "1",
|
||||||
Recipients: "1",
|
Recipients: "1",
|
||||||
}
|
}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
|||||||
Originator: "1",
|
Originator: "1",
|
||||||
Recipients: "1",
|
Recipients: "1",
|
||||||
}
|
}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -17,26 +17,45 @@ 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"`
|
||||||
|
|
||||||
|
// Overrides is a list of Override that may be prioritized over the default configuration
|
||||||
|
Overrides []Override `yaml:"overrides"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Override is a case under which the default integration is overridden
|
||||||
|
type Override struct {
|
||||||
|
Group string `yaml:"group"`
|
||||||
|
IntegrationKey string `yaml:"integration-key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsValid returns whether the provider's configuration is valid
|
// IsValid returns whether the provider's configuration is valid
|
||||||
func (provider *AlertProvider) IsValid() bool {
|
func (provider *AlertProvider) IsValid() bool {
|
||||||
return len(provider.IntegrationKey) == 32
|
registeredGroups := make(map[string]bool)
|
||||||
|
if provider.Overrides != nil {
|
||||||
|
for _, override := range provider.Overrides {
|
||||||
|
if isAlreadyRegistered := registeredGroups[override.Group]; isAlreadyRegistered || override.Group == "" || len(override.IntegrationKey) != 32 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
registeredGroups[override.Group] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Either the default integration key has the right length, or there are overrides who are properly configured.
|
||||||
|
return len(provider.IntegrationKey) == 32 || len(provider.Overrides) != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
//
|
//
|
||||||
// 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) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, _ *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
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.Name, 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.Name, alert.GetDescription())
|
||||||
eventAction = "trigger"
|
eventAction = "trigger"
|
||||||
resolveKey = ""
|
resolveKey = ""
|
||||||
}
|
}
|
||||||
@@ -52,13 +71,25 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
"source": "%s",
|
"source": "%s",
|
||||||
"severity": "critical"
|
"severity": "critical"
|
||||||
}
|
}
|
||||||
}`, provider.IntegrationKey, resolveKey, eventAction, message, service.Name),
|
}`, provider.getIntegrationKeyForGroup(endpoint.Group), resolveKey, eventAction, message, endpoint.Name),
|
||||||
Headers: map[string]string{
|
Headers: map[string]string{
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getIntegrationKeyForGroup returns the appropriate pagerduty integration key for a given group
|
||||||
|
func (provider *AlertProvider) getIntegrationKeyForGroup(group string) string {
|
||||||
|
if provider.Overrides != nil {
|
||||||
|
for _, override := range provider.Overrides {
|
||||||
|
if group == override.Group {
|
||||||
|
return override.IntegrationKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return provider.IntegrationKey
|
||||||
|
}
|
||||||
|
|
||||||
// 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
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -21,9 +21,75 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
||||||
|
providerWithInvalidOverrideGroup := AlertProvider{
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
IntegrationKey: "00000000000000000000000000000000",
|
||||||
|
Group: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if providerWithInvalidOverrideGroup.IsValid() {
|
||||||
|
t.Error("provider Group shouldn't have been valid")
|
||||||
|
}
|
||||||
|
providerWithInvalidOverrideIntegrationKey := AlertProvider{
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
IntegrationKey: "",
|
||||||
|
Group: "group",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if providerWithInvalidOverrideIntegrationKey.IsValid() {
|
||||||
|
t.Error("provider integration key shouldn't have been valid")
|
||||||
|
}
|
||||||
|
providerWithValidOverride := AlertProvider{
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
IntegrationKey: "00000000000000000000000000000000",
|
||||||
|
Group: "group",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if !providerWithValidOverride.IsValid() {
|
||||||
|
t.Error("provider should've been valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
||||||
provider := AlertProvider{IntegrationKey: "00000000000000000000000000000000"}
|
provider := AlertProvider{IntegrationKey: "00000000000000000000000000000000"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{}, true)
|
||||||
|
if customAlertProvider == nil {
|
||||||
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
|
}
|
||||||
|
if !strings.Contains(customAlertProvider.Body, "RESOLVED") {
|
||||||
|
t.Error("customAlertProvider.Body should've contained the substring RESOLVED")
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
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_ToCustomAlertProviderWithResolvedAlertAndOverride(t *testing.T) {
|
||||||
|
provider := AlertProvider{
|
||||||
|
IntegrationKey: "",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
IntegrationKey: "00000000000000000000000000000000",
|
||||||
|
Group: "group",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -45,7 +111,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
||||||
provider := AlertProvider{IntegrationKey: "00000000000000000000000000000000"}
|
provider := AlertProvider{IntegrationKey: "00000000000000000000000000000000"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -64,3 +130,96 @@ func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
|||||||
t.Error("expected body to be valid JSON, got error:", err.Error())
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlertAndOverride(t *testing.T) {
|
||||||
|
provider := AlertProvider{
|
||||||
|
IntegrationKey: "",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
IntegrationKey: "00000000000000000000000000000000",
|
||||||
|
Group: "group",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{}, false)
|
||||||
|
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://events.pagerduty.com/v2/enqueue" {
|
||||||
|
t.Errorf("expected URL to be %s, got %s", "https://events.pagerduty.com/v2/enqueue", 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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_getIntegrationKeyForGroup(t *testing.T) {
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
InputGroup string
|
||||||
|
ExpectedOutput string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "provider-no-override-specify-no-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
IntegrationKey: "00000000000000000000000000000001",
|
||||||
|
Overrides: nil,
|
||||||
|
},
|
||||||
|
InputGroup: "",
|
||||||
|
ExpectedOutput: "00000000000000000000000000000001",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-no-override-specify-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
IntegrationKey: "00000000000000000000000000000001",
|
||||||
|
Overrides: nil,
|
||||||
|
},
|
||||||
|
InputGroup: "group",
|
||||||
|
ExpectedOutput: "00000000000000000000000000000001",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-with-override-specify-no-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
IntegrationKey: "00000000000000000000000000000001",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
IntegrationKey: "00000000000000000000000000000002",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
InputGroup: "",
|
||||||
|
ExpectedOutput: "00000000000000000000000000000001",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-with-override-specify-group-should-override",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
IntegrationKey: "00000000000000000000000000000001",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
IntegrationKey: "00000000000000000000000000000002",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
InputGroup: "group",
|
||||||
|
ExpectedOutput: "00000000000000000000000000000002",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
if output := scenario.Provider.getIntegrationKeyForGroup(scenario.InputGroup); output != scenario.ExpectedOutput {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.ExpectedOutput, output)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/discord"
|
"github.com/TwiN/gatus/v3/alerting/provider/discord"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v3/alerting/provider/mattermost"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v3/alerting/provider/messagebird"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/pagerduty"
|
"github.com/TwiN/gatus/v3/alerting/provider/pagerduty"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/slack"
|
"github.com/TwiN/gatus/v3/alerting/provider/slack"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/teams"
|
"github.com/TwiN/gatus/v3/alerting/provider/teams"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/telegram"
|
"github.com/TwiN/gatus/v3/alerting/provider/telegram"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/twilio"
|
"github.com/TwiN/gatus/v3/alerting/provider/twilio"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the interface that each providers should implement
|
// AlertProvider is the interface that each providers should implement
|
||||||
@@ -20,31 +20,31 @@ type AlertProvider interface {
|
|||||||
IsValid() bool
|
IsValid() bool
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider
|
ToCustomAlertProvider(endpoint *core.Endpoint, 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
)
|
)
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,16 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using Slack
|
// AlertProvider is the configuration necessary for sending an alert using Slack
|
||||||
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,13 +23,13 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
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.Name, 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.Name, alert.FailureThreshold)
|
||||||
color = "#DD0000"
|
color = "#DD0000"
|
||||||
}
|
}
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -24,7 +24,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
provider := AlertProvider{WebhookURL: "http://example.com"}
|
||||||
alertDescription := "test"
|
alertDescription := "test"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.com"}
|
provider := AlertProvider{WebhookURL: "http://example.com"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,16 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using Teams
|
// AlertProvider is the configuration necessary for sending an alert using Teams
|
||||||
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,14 +23,14 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
var message string
|
var message string
|
||||||
var color string
|
var 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.Name, 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.Name, alert.FailureThreshold)
|
||||||
color = "#DD0000"
|
color = "#DD0000"
|
||||||
}
|
}
|
||||||
var results string
|
var results string
|
||||||
@@ -66,7 +66,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"},
|
Headers: map[string]string{"Content-Type": "application/json"},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -24,7 +24,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
provider := AlertProvider{WebhookURL: "http://example.org"}
|
||||||
alertDescription := "test"
|
alertDescription := "test"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{Name: "svc"}, &alert.Alert{Description: &alertDescription}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
||||||
provider := AlertProvider{WebhookURL: "http://example.org"}
|
provider := AlertProvider{WebhookURL: "http://example.org"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using Telegram
|
// AlertProvider is the configuration necessary for sending an alert using Telegram
|
||||||
@@ -14,7 +14,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,12 +24,12 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
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.Name, 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.Name, alert.FailureThreshold)
|
||||||
}
|
}
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -24,7 +24,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
||||||
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "12345678"}
|
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "12345678"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "SUCCESSFUL_CONDITION", Success: true}}}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
||||||
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "0123456789"}
|
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "0123456789"}
|
||||||
description := "Healthcheck Successful"
|
description := "Healthcheck Successful"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{Description: &description}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{Description: &description}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
|||||||
|
|
||||||
func TestAlertProvider_ToCustomAlertProviderWithDescription(t *testing.T) {
|
func TestAlertProvider_ToCustomAlertProviderWithDescription(t *testing.T) {
|
||||||
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "0123456789"}
|
provider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "0123456789"}
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{}, &alert.Alert{}, &core.Result{ConditionResults: []*core.ConditionResult{{Condition: "UNSUCCESSFUL_CONDITION", Success: false}}}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider/custom"
|
"github.com/TwiN/gatus/v3/alerting/provider/custom"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using Twilio
|
// AlertProvider is the configuration necessary for sending an alert using Twilio
|
||||||
@@ -18,7 +18,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,12 +28,12 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
|
||||||
func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, alert *alert.Alert, _ *core.Result, resolved bool) *custom.AlertProvider {
|
func (provider *AlertProvider) ToCustomAlertProvider(endpoint *core.Endpoint, alert *alert.Alert, _ *core.Result, resolved bool) *custom.AlertProvider {
|
||||||
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.Name, alert.GetDescription())
|
||||||
} else {
|
} else {
|
||||||
message = fmt.Sprintf("TRIGGERED: %s - %s", service.Name, alert.GetDescription())
|
message = fmt.Sprintf("TRIGGERED: %s - %s", endpoint.Name, alert.GetDescription())
|
||||||
}
|
}
|
||||||
return &custom.AlertProvider{
|
return &custom.AlertProvider{
|
||||||
URL: fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", provider.SID),
|
URL: fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", provider.SID),
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestTwilioAlertProvider_IsValid(t *testing.T) {
|
func TestTwilioAlertProvider_IsValid(t *testing.T) {
|
||||||
@@ -33,7 +33,7 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
To: "4",
|
To: "4",
|
||||||
}
|
}
|
||||||
description := "alert-description"
|
description := "alert-description"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "service-name"}, &alert.Alert{Description: &description}, &core.Result{}, true)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{Name: "endpoint-name"}, &alert.Alert{Description: &description}, &core.Result{}, true)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -46,8 +46,8 @@ func TestAlertProvider_ToCustomAlertProviderWithResolvedAlert(t *testing.T) {
|
|||||||
if customAlertProvider.Method != http.MethodPost {
|
if customAlertProvider.Method != http.MethodPost {
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
||||||
}
|
}
|
||||||
if customAlertProvider.Body != "Body=RESOLVED%3A+service-name+-+alert-description&From=3&To=4" {
|
if customAlertProvider.Body != "Body=RESOLVED%3A+endpoint-name+-+alert-description&From=3&To=4" {
|
||||||
t.Errorf("expected body to be %s, got %s", "Body=RESOLVED%3A+service-name+-+alert-description&From=3&To=4", customAlertProvider.Body)
|
t.Errorf("expected body to be %s, got %s", "Body=RESOLVED%3A+endpoint-name+-+alert-description&From=3&To=4", customAlertProvider.Body)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,7 +59,7 @@ func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
|||||||
To: "1",
|
To: "1",
|
||||||
}
|
}
|
||||||
description := "alert-description"
|
description := "alert-description"
|
||||||
customAlertProvider := provider.ToCustomAlertProvider(&core.Service{Name: "service-name"}, &alert.Alert{Description: &description}, &core.Result{}, false)
|
customAlertProvider := provider.ToCustomAlertProvider(&core.Endpoint{Name: "endpoint-name"}, &alert.Alert{Description: &description}, &core.Result{}, false)
|
||||||
if customAlertProvider == nil {
|
if customAlertProvider == nil {
|
||||||
t.Fatal("customAlertProvider shouldn't have been nil")
|
t.Fatal("customAlertProvider shouldn't have been nil")
|
||||||
}
|
}
|
||||||
@@ -72,7 +72,7 @@ func TestAlertProvider_ToCustomAlertProviderWithTriggeredAlert(t *testing.T) {
|
|||||||
if customAlertProvider.Method != http.MethodPost {
|
if customAlertProvider.Method != http.MethodPost {
|
||||||
t.Errorf("expected method to be %s, got %s", http.MethodPost, customAlertProvider.Method)
|
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" {
|
if customAlertProvider.Body != "Body=TRIGGERED%3A+endpoint-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)
|
t.Errorf("expected body to be %s, got %s", "Body=TRIGGERED%3A+endpoint-name+-+alert-description&From=2&To=1", customAlertProvider.Body)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+25
-4
@@ -22,7 +22,7 @@ func GetHTTPClient(config *Config) *http.Client {
|
|||||||
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 {
|
||||||
@@ -38,7 +38,11 @@ func CanPerformStartTLS(address string, config *Config) (connected bool, certifi
|
|||||||
if len(hostAndPort) != 2 {
|
if len(hostAndPort) != 2 {
|
||||||
return false, nil, errors.New("invalid address for starttls, format must be host:port")
|
return false, nil, errors.New("invalid address for starttls, format must be host:port")
|
||||||
}
|
}
|
||||||
smtpClient, err := smtp.Dial(address)
|
connection, err := net.DialTimeout("tcp", address, config.Timeout)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
smtpClient, err := smtp.NewClient(connection, hostAndPort[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -57,6 +61,20 @@ func CanPerformStartTLS(address string, config *Config) (connected bool, certifi
|
|||||||
return true, certificate, nil
|
return true, certificate, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CanPerformTLS checks whether a connection can be established to an address using the TLS protocol
|
||||||
|
func CanPerformTLS(address string, config *Config) (connected bool, certificate *x509.Certificate, err error) {
|
||||||
|
connection, err := tls.DialWithDialer(&net.Dialer{Timeout: config.Timeout}, "tcp", address, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer connection.Close()
|
||||||
|
verifiedChains := connection.ConnectionState().VerifiedChains
|
||||||
|
if len(verifiedChains) == 0 || len(verifiedChains[0]) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return true, verifiedChains[0][0], nil
|
||||||
|
}
|
||||||
|
|
||||||
// Ping checks if an address can be pinged and returns the round-trip time if the address can be pinged
|
// Ping checks if an address can be pinged and returns the round-trip time if the address can be pinged
|
||||||
//
|
//
|
||||||
// Note that this function takes at least 100ms, even if the address is 127.0.0.1
|
// Note that this function takes at least 100ms, even if the address is 127.0.0.1
|
||||||
@@ -67,8 +85,11 @@ func Ping(address string, config *Config) (bool, time.Duration) {
|
|||||||
}
|
}
|
||||||
pinger.Count = 1
|
pinger.Count = 1
|
||||||
pinger.Timeout = config.Timeout
|
pinger.Timeout = config.Timeout
|
||||||
// Set the pinger's privileged mode to true for every operating system except darwin
|
// Set the pinger's privileged mode to true for every GOOS except darwin
|
||||||
// https://github.com/TwinProduction/gatus/issues/132
|
// See https://github.com/TwiN/gatus/issues/132
|
||||||
|
//
|
||||||
|
// Note that for this to work on Linux, Gatus must run with sudo privileges.
|
||||||
|
// See https://github.com/go-ping/ping#linux
|
||||||
pinger.SetPrivileged(runtime.GOOS != "darwin")
|
pinger.SetPrivileged(runtime.GOOS != "darwin")
|
||||||
err = pinger.Run()
|
err = pinger.Run()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -91,6 +91,56 @@ func TestCanPerformStartTLS(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCanPerformTLS(t *testing.T) {
|
||||||
|
type args struct {
|
||||||
|
address string
|
||||||
|
insecure bool
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args args
|
||||||
|
wantConnected bool
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "invalid address",
|
||||||
|
args: args{
|
||||||
|
address: "test",
|
||||||
|
},
|
||||||
|
wantConnected: false,
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "error dial",
|
||||||
|
args: args{
|
||||||
|
address: "test:1234",
|
||||||
|
},
|
||||||
|
wantConnected: false,
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid tls",
|
||||||
|
args: args{
|
||||||
|
address: "smtp.gmail.com:465",
|
||||||
|
},
|
||||||
|
wantConnected: true,
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
connected, _, err := CanPerformTLS(tt.args.address, &Config{Insecure: tt.args.insecure, Timeout: 5 * time.Second})
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Errorf("CanPerformTLS() err=%v, wantErr=%v", err, tt.wantErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if connected != tt.wantConnected {
|
||||||
|
t.Errorf("CanPerformTLS() connected=%v, wantConnected=%v", connected, tt.wantConnected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCanCreateTCPConnection(t *testing.T) {
|
func TestCanCreateTCPConnection(t *testing.T) {
|
||||||
if CanCreateTCPConnection("127.0.0.1", &Config{Timeout: 5 * time.Second}) {
|
if CanCreateTCPConnection("127.0.0.1", &Config{Timeout: 5 * time.Second}) {
|
||||||
t.Error("should've failed, because there's no port in the address")
|
t.Error("should've failed, because there's no port in the address")
|
||||||
|
|||||||
+1
-1
@@ -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{
|
||||||
|
|||||||
+3
-3
@@ -1,8 +1,8 @@
|
|||||||
services:
|
endpoints:
|
||||||
- name: front-end
|
- name: front-end
|
||||||
group: core
|
group: core
|
||||||
url: "https://twinnation.org/health"
|
url: "https://twin.sh/health"
|
||||||
interval: 1m
|
interval: 5m
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
- "[BODY].status == UP"
|
- "[BODY].status == UP"
|
||||||
|
|||||||
+82
-69
@@ -7,12 +7,15 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting"
|
"github.com/TwiN/gatus/v3/alerting"
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/alerting/provider"
|
"github.com/TwiN/gatus/v3/alerting/provider"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/config/maintenance"
|
||||||
"github.com/TwinProduction/gatus/security"
|
"github.com/TwiN/gatus/v3/config/ui"
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/config/web"
|
||||||
|
"github.com/TwiN/gatus/v3/core"
|
||||||
|
"github.com/TwiN/gatus/v3/security"
|
||||||
|
"github.com/TwiN/gatus/v3/storage"
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -24,63 +27,64 @@ const (
|
|||||||
// DefaultFallbackConfigurationFilePath is the default fallback path that will be used to search for the
|
// DefaultFallbackConfigurationFilePath is the default fallback path that will be used to search for the
|
||||||
// configuration file if DefaultConfigurationFilePath didn't work
|
// configuration file if DefaultConfigurationFilePath didn't work
|
||||||
DefaultFallbackConfigurationFilePath = "config/config.yml"
|
DefaultFallbackConfigurationFilePath = "config/config.yml"
|
||||||
|
|
||||||
// DefaultAddress is the default address the service will bind to
|
|
||||||
DefaultAddress = "0.0.0.0"
|
|
||||||
|
|
||||||
// DefaultPort is the default port the service will listen on
|
|
||||||
DefaultPort = 8080
|
|
||||||
)
|
)
|
||||||
|
|
||||||
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")
|
||||||
|
|
||||||
// ErrInvalidSecurityConfig is an error returned when the security configuration is invalid
|
// ErrInvalidSecurityConfig is an error returned when the security configuration is invalid
|
||||||
ErrInvalidSecurityConfig = errors.New("invalid security configuration")
|
ErrInvalidSecurityConfig = errors.New("invalid security configuration")
|
||||||
|
|
||||||
// StaticFolder is the path to the location of the static folder from the root path of the project
|
|
||||||
// The only reason this is exposed is to allow running tests from a different path than the root path of the project
|
|
||||||
StaticFolder = "./web/static"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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 *WebConfig `yaml:"web"`
|
Web *web.Config `yaml:"web,omitempty"`
|
||||||
|
|
||||||
// UI is the configuration for the UI
|
// UI is the configuration for the UI
|
||||||
UI *UIConfig `yaml:"ui"`
|
UI *ui.Config `yaml:"ui,omitempty"`
|
||||||
|
|
||||||
|
// Maintenance is the configuration for creating a maintenance window in which no alerts are sent
|
||||||
|
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
|
||||||
@@ -145,25 +149,29 @@ func readConfigurationFile(fileName string) (config *Config, err error) {
|
|||||||
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 {
|
||||||
@@ -172,6 +180,9 @@ func parseAndValidateConfigBytes(yamlBytes []byte) (config *Config, err error) {
|
|||||||
if err := validateUIConfig(config); err != nil {
|
if err := validateUIConfig(config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := validateMaintenanceConfig(config); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if err := validateStorageConfig(config); err != nil {
|
if err := validateStorageConfig(config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -184,28 +195,30 @@ func validateStorageConfig(config *Config) error {
|
|||||||
config.Storage = &storage.Config{
|
config.Storage = &storage.Config{
|
||||||
Type: storage.TypeMemory,
|
Type: storage.TypeMemory,
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if err := config.Storage.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
err := storage.Initialize(config.Storage)
|
return nil
|
||||||
if err != nil {
|
}
|
||||||
return err
|
|
||||||
}
|
func validateMaintenanceConfig(config *Config) error {
|
||||||
// Remove all ServiceStatus that represent services which no longer exist in the configuration
|
if config.Maintenance == nil {
|
||||||
var keys []string
|
config.Maintenance = maintenance.GetDefaultConfig()
|
||||||
for _, service := range config.Services {
|
} else {
|
||||||
keys = append(keys, service.Key())
|
if err := config.Maintenance.ValidateAndSetDefaults(); err != nil {
|
||||||
}
|
return err
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateUIConfig(config *Config) error {
|
func validateUIConfig(config *Config) error {
|
||||||
if config.UI == nil {
|
if config.UI == nil {
|
||||||
config.UI = GetDefaultUIConfig()
|
config.UI = ui.GetDefaultConfig()
|
||||||
} else {
|
} else {
|
||||||
if err := config.UI.validateAndSetDefaults(); err != nil {
|
if err := config.UI.ValidateAndSetDefaults(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -214,23 +227,23 @@ func validateUIConfig(config *Config) error {
|
|||||||
|
|
||||||
func validateWebConfig(config *Config) error {
|
func validateWebConfig(config *Config) error {
|
||||||
if config.Web == nil {
|
if config.Web == nil {
|
||||||
config.Web = GetDefaultWebConfig()
|
config.Web = web.GetDefaultConfig()
|
||||||
} else {
|
} else {
|
||||||
return config.Web.validateAndSetDefaults()
|
return config.Web.ValidateAndSetDefaults()
|
||||||
}
|
}
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,10 +263,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
|
||||||
@@ -276,13 +289,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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+412
-299
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,146 @@
|
|||||||
|
package maintenance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errInvalidMaintenanceStartFormat = errors.New("invalid maintenance start format: must be hh:mm, between 00:00 and 23:59 inclusively (e.g. 23:00)")
|
||||||
|
errInvalidMaintenanceDuration = errors.New("invalid maintenance duration: must be bigger than 0 (e.g. 30m)")
|
||||||
|
errInvalidDayName = fmt.Errorf("invalid value specified for 'on'. supported values are %s", longDayNames)
|
||||||
|
|
||||||
|
longDayNames = []string{
|
||||||
|
"Sunday",
|
||||||
|
"Monday",
|
||||||
|
"Tuesday",
|
||||||
|
"Wednesday",
|
||||||
|
"Thursday",
|
||||||
|
"Friday",
|
||||||
|
"Saturday",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config allows for the configuration of a maintenance period.
|
||||||
|
// During this maintenance period, no alerts will be sent.
|
||||||
|
//
|
||||||
|
// Uses UTC.
|
||||||
|
type Config struct {
|
||||||
|
Enabled *bool `yaml:"enabled"` // Whether the maintenance period is enabled. Enabled by default if nil.
|
||||||
|
Start string `yaml:"start"` // Time at which the maintenance period starts (e.g. 23:00)
|
||||||
|
Duration time.Duration `yaml:"duration"` // Duration of the maintenance period (e.g. 4h)
|
||||||
|
|
||||||
|
// Every is a list of days of the week during which maintenance period applies.
|
||||||
|
// See longDayNames for list of valid values.
|
||||||
|
// Every day if empty.
|
||||||
|
Every []string `yaml:"every"`
|
||||||
|
|
||||||
|
durationToStartFromMidnight time.Duration
|
||||||
|
timeLocation *time.Location
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetDefaultConfig() *Config {
|
||||||
|
defaultValue := false
|
||||||
|
return &Config{
|
||||||
|
Enabled: &defaultValue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsEnabled returns whether maintenance is enabled or not
|
||||||
|
func (c Config) IsEnabled() bool {
|
||||||
|
if c.Enabled == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return *c.Enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAndSetDefaults validates the maintenance configuration and sets the default values if necessary.
|
||||||
|
//
|
||||||
|
// Must be called once in the application's lifecycle before IsUnderMaintenance is called, since it
|
||||||
|
// also sets durationToStartFromMidnight.
|
||||||
|
func (c *Config) ValidateAndSetDefaults() error {
|
||||||
|
if c == nil || !c.IsEnabled() {
|
||||||
|
// Don't waste time validating if maintenance is not enabled.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, day := range c.Every {
|
||||||
|
isDayValid := false
|
||||||
|
for _, longDayName := range longDayNames {
|
||||||
|
if day == longDayName {
|
||||||
|
isDayValid = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isDayValid {
|
||||||
|
return errInvalidDayName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
c.durationToStartFromMidnight, err = hhmmToDuration(c.Start)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if c.Duration <= 0 || c.Duration >= 24*time.Hour {
|
||||||
|
return errInvalidMaintenanceDuration
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsUnderMaintenance checks whether the endpoints that Gatus monitors are within the configured maintenance window
|
||||||
|
func (c Config) IsUnderMaintenance() bool {
|
||||||
|
if !c.IsEnabled() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
var dayWhereMaintenancePeriodWouldStart time.Time
|
||||||
|
if now.Hour() >= int(c.durationToStartFromMidnight.Hours()) {
|
||||||
|
dayWhereMaintenancePeriodWouldStart = now.Truncate(24 * time.Hour)
|
||||||
|
} else {
|
||||||
|
dayWhereMaintenancePeriodWouldStart = now.Add(-c.Duration).Truncate(24 * time.Hour)
|
||||||
|
}
|
||||||
|
hasMaintenanceEveryDay := len(c.Every) == 0
|
||||||
|
hasMaintenancePeriodScheduledToStartOnThatWeekday := c.hasDay(dayWhereMaintenancePeriodWouldStart.Weekday().String())
|
||||||
|
if !hasMaintenanceEveryDay && !hasMaintenancePeriodScheduledToStartOnThatWeekday {
|
||||||
|
// The day when the maintenance period would start is not scheduled
|
||||||
|
// to have any maintenance, so we can just return false.
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
startOfMaintenancePeriod := dayWhereMaintenancePeriodWouldStart.Add(c.durationToStartFromMidnight)
|
||||||
|
endOfMaintenancePeriod := startOfMaintenancePeriod.Add(c.Duration)
|
||||||
|
return now.After(startOfMaintenancePeriod) && now.Before(endOfMaintenancePeriod)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) hasDay(day string) bool {
|
||||||
|
for _, d := range c.Every {
|
||||||
|
if d == day {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func hhmmToDuration(s string) (time.Duration, error) {
|
||||||
|
if len(s) != 5 {
|
||||||
|
return 0, errInvalidMaintenanceStartFormat
|
||||||
|
}
|
||||||
|
var hours, minutes int
|
||||||
|
var err error
|
||||||
|
if hours, err = extractNumericalValueFromPotentiallyZeroPaddedString(s[:2]); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if minutes, err = extractNumericalValueFromPotentiallyZeroPaddedString(s[3:5]); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
duration := (time.Duration(hours) * time.Hour) + (time.Duration(minutes) * time.Minute)
|
||||||
|
if hours < 0 || hours > 23 || minutes < 0 || minutes > 59 || duration < 0 || duration >= 24*time.Hour {
|
||||||
|
return 0, errInvalidMaintenanceStartFormat
|
||||||
|
}
|
||||||
|
return duration, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractNumericalValueFromPotentiallyZeroPaddedString(s string) (int, error) {
|
||||||
|
return strconv.Atoi(strings.TrimPrefix(s, "0"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
package maintenance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetDefaultConfig(t *testing.T) {
|
||||||
|
if *GetDefaultConfig().Enabled {
|
||||||
|
t.Fatal("expected default config to be disabled by default")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfig_ValidateAndSetDefaults(t *testing.T) {
|
||||||
|
yes, no := true, false
|
||||||
|
scenarios := []struct {
|
||||||
|
name string
|
||||||
|
cfg *Config
|
||||||
|
expectedError error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "nil",
|
||||||
|
cfg: nil,
|
||||||
|
expectedError: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "disabled",
|
||||||
|
cfg: &Config{
|
||||||
|
Enabled: &no,
|
||||||
|
},
|
||||||
|
expectedError: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-day",
|
||||||
|
cfg: &Config{
|
||||||
|
Every: []string{"invalid-day"},
|
||||||
|
},
|
||||||
|
expectedError: errInvalidDayName,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-day",
|
||||||
|
cfg: &Config{
|
||||||
|
Every: []string{"invalid-day"},
|
||||||
|
},
|
||||||
|
expectedError: errInvalidDayName,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-start-format",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "0000",
|
||||||
|
},
|
||||||
|
expectedError: errInvalidMaintenanceStartFormat,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-start-hours",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "25:00",
|
||||||
|
},
|
||||||
|
expectedError: errInvalidMaintenanceStartFormat,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-start-minutes",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "0:61",
|
||||||
|
},
|
||||||
|
expectedError: errInvalidMaintenanceStartFormat,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-start-minutes-non-numerical",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "00:zz",
|
||||||
|
},
|
||||||
|
expectedError: strconv.ErrSyntax,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-start-hours-non-numerical",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "zz:00",
|
||||||
|
},
|
||||||
|
expectedError: strconv.ErrSyntax,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-duration",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "23:00",
|
||||||
|
Duration: 0,
|
||||||
|
},
|
||||||
|
expectedError: errInvalidMaintenanceDuration,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "every-day-at-2300",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "23:00",
|
||||||
|
Duration: time.Hour,
|
||||||
|
},
|
||||||
|
expectedError: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "every-monday-at-0000",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: "00:00",
|
||||||
|
Duration: 30 * time.Minute,
|
||||||
|
Every: []string{"Monday"},
|
||||||
|
},
|
||||||
|
expectedError: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "every-friday-and-sunday-at-0000-explicitly-enabled",
|
||||||
|
cfg: &Config{
|
||||||
|
Enabled: &yes,
|
||||||
|
Start: "08:00",
|
||||||
|
Duration: 8 * time.Hour,
|
||||||
|
Every: []string{"Friday", "Sunday"},
|
||||||
|
},
|
||||||
|
expectedError: nil,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.name, func(t *testing.T) {
|
||||||
|
err := scenario.cfg.ValidateAndSetDefaults()
|
||||||
|
if !errors.Is(err, scenario.expectedError) {
|
||||||
|
t.Errorf("expected %v, got %v", scenario.expectedError, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfig_IsUnderMaintenance(t *testing.T) {
|
||||||
|
yes, no := true, false
|
||||||
|
now := time.Now().UTC()
|
||||||
|
scenarios := []struct {
|
||||||
|
name string
|
||||||
|
cfg *Config
|
||||||
|
expected bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "disabled",
|
||||||
|
cfg: &Config{
|
||||||
|
Enabled: &no,
|
||||||
|
},
|
||||||
|
expected: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "under-maintenance-explicitly-enabled",
|
||||||
|
cfg: &Config{
|
||||||
|
Enabled: &yes,
|
||||||
|
Start: fmt.Sprintf("%02d:00", now.Hour()),
|
||||||
|
Duration: 2 * time.Hour,
|
||||||
|
},
|
||||||
|
expected: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "under-maintenance-starting-now-for-2h",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: fmt.Sprintf("%02d:00", now.Hour()),
|
||||||
|
Duration: 2 * time.Hour,
|
||||||
|
},
|
||||||
|
expected: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "under-maintenance-starting-now-for-8h",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: fmt.Sprintf("%02d:00", now.Hour()),
|
||||||
|
Duration: 8 * time.Hour,
|
||||||
|
},
|
||||||
|
expected: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "under-maintenance-starting-4h-ago-for-8h",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: fmt.Sprintf("%02d:00", normalizeHour(now.Hour()-4)),
|
||||||
|
Duration: 8 * time.Hour,
|
||||||
|
},
|
||||||
|
expected: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "under-maintenance-starting-4h-ago-for-3h",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: fmt.Sprintf("%02d:00", normalizeHour(now.Hour()-4)),
|
||||||
|
Duration: 3 * time.Hour,
|
||||||
|
},
|
||||||
|
expected: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "under-maintenance-starting-5h-ago-for-1h",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: fmt.Sprintf("%02d:00", normalizeHour(now.Hour()-5)),
|
||||||
|
Duration: time.Hour,
|
||||||
|
},
|
||||||
|
expected: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "not-under-maintenance-today",
|
||||||
|
cfg: &Config{
|
||||||
|
Start: fmt.Sprintf("%02d:00", now.Hour()),
|
||||||
|
Duration: time.Hour,
|
||||||
|
Every: []string{now.Add(48 * time.Hour).Weekday().String()},
|
||||||
|
},
|
||||||
|
expected: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.name, func(t *testing.T) {
|
||||||
|
t.Log(scenario.cfg.Start)
|
||||||
|
t.Log(now)
|
||||||
|
if err := scenario.cfg.ValidateAndSetDefaults(); err != nil {
|
||||||
|
t.Fatal("validation shouldn't have returned an error, got", err)
|
||||||
|
}
|
||||||
|
isUnderMaintenance := scenario.cfg.IsUnderMaintenance()
|
||||||
|
if isUnderMaintenance != scenario.expected {
|
||||||
|
t.Errorf("expected %v, got %v", scenario.expected, isUnderMaintenance)
|
||||||
|
t.Logf("start=%v; duration=%v; now=%v", scenario.cfg.Start, scenario.cfg.Duration, time.Now().UTC())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeHour(hour int) int {
|
||||||
|
if hour < 0 {
|
||||||
|
return hour + 24
|
||||||
|
}
|
||||||
|
return hour
|
||||||
|
}
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"html/template"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultTitle = "Health Dashboard | Gatus"
|
|
||||||
defaultLogo = ""
|
|
||||||
)
|
|
||||||
|
|
||||||
// UIConfig is the configuration for the UI of Gatus
|
|
||||||
type UIConfig struct {
|
|
||||||
Title string `yaml:"title"` // Title of the page
|
|
||||||
Logo string `yaml:"logo"` // Logo to display on the page
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetDefaultUIConfig returns a UIConfig struct with the default values
|
|
||||||
func GetDefaultUIConfig() *UIConfig {
|
|
||||||
return &UIConfig{
|
|
||||||
Title: defaultTitle,
|
|
||||||
Logo: defaultLogo,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfg *UIConfig) validateAndSetDefaults() error {
|
|
||||||
if len(cfg.Title) == 0 {
|
|
||||||
cfg.Title = defaultTitle
|
|
||||||
}
|
|
||||||
t, err := template.ParseFiles(StaticFolder + "/index.html")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var buffer bytes.Buffer
|
|
||||||
err = t.Execute(&buffer, cfg)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"html/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultTitle = "Health Dashboard | Gatus"
|
||||||
|
defaultLogo = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// StaticFolder is the path to the location of the static folder from the root path of the project
|
||||||
|
// The only reason this is exposed is to allow running tests from a different path than the root path of the project
|
||||||
|
StaticFolder = "./web/static"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config is the configuration for the UI of Gatus
|
||||||
|
type Config struct {
|
||||||
|
Title string `yaml:"title"` // Title of the page
|
||||||
|
Logo string `yaml:"logo"` // Logo to display on the page
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultConfig returns a Config struct with the default values
|
||||||
|
func GetDefaultConfig() *Config {
|
||||||
|
return &Config{
|
||||||
|
Title: defaultTitle,
|
||||||
|
Logo: defaultLogo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAndSetDefaults validates the UI configuration and sets the default values if necessary.
|
||||||
|
func (cfg *Config) ValidateAndSetDefaults() error {
|
||||||
|
if len(cfg.Title) == 0 {
|
||||||
|
cfg.Title = defaultTitle
|
||||||
|
}
|
||||||
|
t, err := template.ParseFiles(StaticFolder + "/index.html")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var buffer bytes.Buffer
|
||||||
|
err = t.Execute(&buffer, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConfig_ValidateAndSetDefaults(t *testing.T) {
|
||||||
|
StaticFolder = "../../web/static"
|
||||||
|
defer func() {
|
||||||
|
StaticFolder = "./web/static"
|
||||||
|
}()
|
||||||
|
cfg := &Config{Title: ""}
|
||||||
|
if err := cfg.ValidateAndSetDefaults(); err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetDefaultConfig(t *testing.T) {
|
||||||
|
defaultConfig := GetDefaultConfig()
|
||||||
|
if defaultConfig.Title != defaultTitle {
|
||||||
|
t.Error("expected GetDefaultConfig() to return defaultTitle, got", defaultConfig.Title)
|
||||||
|
}
|
||||||
|
if defaultConfig.Logo != defaultLogo {
|
||||||
|
t.Error("expected GetDefaultConfig() to return defaultLogo, got", defaultConfig.Logo)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestUIConfig_validateAndSetDefaults(t *testing.T) {
|
|
||||||
StaticFolder = "../web/static"
|
|
||||||
defer func() {
|
|
||||||
StaticFolder = "./web/static"
|
|
||||||
}()
|
|
||||||
uiConfig := &UIConfig{Title: ""}
|
|
||||||
if err := uiConfig.validateAndSetDefaults(); err != nil {
|
|
||||||
t.Error("expected no error, got", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGetDefaultUIConfig(t *testing.T) {
|
|
||||||
defaultUIConfig := GetDefaultUIConfig()
|
|
||||||
if defaultUIConfig.Title != defaultTitle {
|
|
||||||
t.Error("expected GetDefaultUIConfig() to return defaultTitle, got", defaultUIConfig.Title)
|
|
||||||
}
|
|
||||||
if defaultUIConfig.Logo != defaultLogo {
|
|
||||||
t.Error("expected GetDefaultUIConfig() to return defaultLogo, got", defaultUIConfig.Logo)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
package config
|
package web
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
)
|
)
|
||||||
|
|
||||||
// WebConfig is the structure which supports the configuration of the endpoint
|
const (
|
||||||
|
// DefaultAddress is the default address the application will bind to
|
||||||
|
DefaultAddress = "0.0.0.0"
|
||||||
|
|
||||||
|
// DefaultPort is the default port the application will listen on
|
||||||
|
DefaultPort = 8080
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config is the structure which supports the configuration of the endpoint
|
||||||
// which provides access to the web frontend
|
// which provides access to the web frontend
|
||||||
type WebConfig struct {
|
type Config struct {
|
||||||
// Address to listen on (defaults to 0.0.0.0 specified by DefaultAddress)
|
// Address to listen on (defaults to 0.0.0.0 specified by DefaultAddress)
|
||||||
Address string `yaml:"address"`
|
Address string `yaml:"address"`
|
||||||
|
|
||||||
@@ -15,13 +23,13 @@ type WebConfig struct {
|
|||||||
Port int `yaml:"port"`
|
Port int `yaml:"port"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultWebConfig returns a WebConfig struct with the default values
|
// GetDefaultConfig returns a Config struct with the default values
|
||||||
func GetDefaultWebConfig() *WebConfig {
|
func GetDefaultConfig() *Config {
|
||||||
return &WebConfig{Address: DefaultAddress, Port: DefaultPort}
|
return &Config{Address: DefaultAddress, Port: DefaultPort}
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateAndSetDefaults checks and sets the default values for fields that are not set
|
// ValidateAndSetDefaults validates the web configuration and sets the default values if necessary.
|
||||||
func (web *WebConfig) validateAndSetDefaults() error {
|
func (web *Config) ValidateAndSetDefaults() error {
|
||||||
// Validate the Address
|
// Validate the Address
|
||||||
if len(web.Address) == 0 {
|
if len(web.Address) == 0 {
|
||||||
web.Address = DefaultAddress
|
web.Address = DefaultAddress
|
||||||
@@ -36,6 +44,6 @@ func (web *WebConfig) validateAndSetDefaults() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SocketAddress returns the combination of the Address and the Port
|
// SocketAddress returns the combination of the Address and the Port
|
||||||
func (web *WebConfig) SocketAddress() string {
|
func (web *Config) SocketAddress() string {
|
||||||
return fmt.Sprintf("%s:%d", web.Address, web.Port)
|
return fmt.Sprintf("%s:%d", web.Address, web.Port)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetDefaultConfig(t *testing.T) {
|
||||||
|
defaultConfig := GetDefaultConfig()
|
||||||
|
if defaultConfig.Port != DefaultPort {
|
||||||
|
t.Error("expected default config to have the default port")
|
||||||
|
}
|
||||||
|
if defaultConfig.Address != DefaultAddress {
|
||||||
|
t.Error("expected default config to have the default address")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfig_ValidateAndSetDefaults(t *testing.T) {
|
||||||
|
scenarios := []struct {
|
||||||
|
name string
|
||||||
|
cfg *Config
|
||||||
|
expectedAddress string
|
||||||
|
expectedPort int
|
||||||
|
expectedErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "no-explicit-config",
|
||||||
|
cfg: &Config{},
|
||||||
|
expectedAddress: "0.0.0.0",
|
||||||
|
expectedPort: 8080,
|
||||||
|
expectedErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid-port",
|
||||||
|
cfg: &Config{Port: 100000000},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.name, func(t *testing.T) {
|
||||||
|
err := scenario.cfg.ValidateAndSetDefaults()
|
||||||
|
if (err != nil) != scenario.expectedErr {
|
||||||
|
t.Errorf("expected the existence of an error to be %v, got %v", scenario.expectedErr, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !scenario.expectedErr {
|
||||||
|
if scenario.cfg.Port != scenario.expectedPort {
|
||||||
|
t.Errorf("expected port to be %d, got %d", scenario.expectedPort, scenario.cfg.Port)
|
||||||
|
}
|
||||||
|
if scenario.cfg.Address != scenario.expectedAddress {
|
||||||
|
t.Errorf("expected address to be %s, got %s", scenario.expectedAddress, scenario.cfg.Address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfig_SocketAddress(t *testing.T) {
|
||||||
|
web := &Config{
|
||||||
|
Address: "0.0.0.0",
|
||||||
|
Port: 8081,
|
||||||
|
}
|
||||||
|
if web.SocketAddress() != "0.0.0.0:8081" {
|
||||||
|
t.Errorf("expected %s, got %s", "0.0.0.0:8081", web.SocketAddress())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestWebConfig_SocketAddress(t *testing.T) {
|
|
||||||
web := &WebConfig{
|
|
||||||
Address: "0.0.0.0",
|
|
||||||
Port: 8081,
|
|
||||||
}
|
|
||||||
if web.SocketAddress() != "0.0.0.0:8081" {
|
|
||||||
t.Errorf("expected %s, got %s", "0.0.0.0:8081", web.SocketAddress())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,9 +8,10 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config/ui"
|
||||||
"github.com/TwinProduction/gatus/controller/handler"
|
"github.com/TwiN/gatus/v3/config/web"
|
||||||
"github.com/TwinProduction/gatus/security"
|
"github.com/TwiN/gatus/v3/controller/handler"
|
||||||
|
"github.com/TwiN/gatus/v3/security"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -20,8 +21,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Handle creates the router and starts the server
|
// Handle creates the router and starts the server
|
||||||
func Handle(securityConfig *security.Config, webConfig *config.WebConfig, uiConfig *config.UIConfig, enableMetrics bool) {
|
func Handle(securityConfig *security.Config, webConfig *web.Config, uiConfig *ui.Config, enableMetrics bool) {
|
||||||
var router http.Handler = handler.CreateRouter(config.StaticFolder, securityConfig, uiConfig, enableMetrics)
|
var router http.Handler = handler.CreateRouter(ui.StaticFolder, securityConfig, uiConfig, enableMetrics)
|
||||||
if os.Getenv("ENVIRONMENT") == "dev" {
|
if os.Getenv("ENVIRONMENT") == "dev" {
|
||||||
router = handler.DevelopmentCORS(router)
|
router = handler.DevelopmentCORS(router)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,17 +7,18 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/config/web"
|
||||||
|
"github.com/TwiN/gatus/v3/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestHandle(t *testing.T) {
|
func TestHandle(t *testing.T) {
|
||||||
cfg := &config.Config{
|
cfg := &config.Config{
|
||||||
Web: &config.WebConfig{
|
Web: &web.Config{
|
||||||
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",
|
||||||
@@ -33,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 {
|
||||||
|
|||||||
+14
-16
@@ -7,8 +7,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwinProduction/gatus/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,16 +40,15 @@ 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)
|
formattedDate := time.Now().Format(http.TimeFormat)
|
||||||
@@ -60,7 +59,7 @@ func UptimeBadge(writer http.ResponseWriter, request *http.Request) {
|
|||||||
_, _ = 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,16 +78,15 @@ 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)
|
formattedDate := time.Now().Format(http.TimeFormat)
|
||||||
|
|||||||
@@ -7,18 +7,18 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwinProduction/gatus/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,8 +7,8 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwinProduction/gatus/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"
|
||||||
"github.com/wcharczuk/go-chart/v2/drawing"
|
"github.com/wcharczuk/go-chart/v2/drawing"
|
||||||
@@ -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{
|
||||||
|
|||||||
@@ -6,18 +6,18 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwinProduction/gatus/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")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,10 +10,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwinProduction/gatus/storage/store/common"
|
"github.com/TwiN/gatus/v3/storage/store/common"
|
||||||
"github.com/TwinProduction/gatus/storage/store/common/paging"
|
"github.com/TwiN/gatus/v3/storage/store/common/paging"
|
||||||
"github.com/TwinProduction/gocache"
|
"github.com/TwiN/gocache"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
+45
-34
@@ -6,10 +6,10 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwinProduction/gatus/watchdog"
|
"github.com/TwiN/gatus/v3/watchdog"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -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,14 +3,14 @@ package handler
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config/ui"
|
||||||
"github.com/TwinProduction/gatus/security"
|
"github.com/TwiN/gatus/v3/security"
|
||||||
"github.com/TwinProduction/health"
|
"github.com/TwiN/health"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateRouter(staticFolder string, securityConfig *security.Config, uiConfig *config.UIConfig, enabledMetrics bool) *mux.Router {
|
func CreateRouter(staticFolder string, securityConfig *security.Config, uiConfig *ui.Config, enabledMetrics bool) *mux.Router {
|
||||||
router := mux.NewRouter()
|
router := mux.NewRouter()
|
||||||
if enabledMetrics {
|
if enabledMetrics {
|
||||||
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
||||||
@@ -18,15 +18,21 @@ func CreateRouter(staticFolder string, securityConfig *security.Config, uiConfig
|
|||||||
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
|
// 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/endpoints/statuses", secureIfNecessary(securityConfig, EndpointStatuses)).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")
|
router.HandleFunc("/api/v1/endpoints/{key}/statuses", secureIfNecessary(securityConfig, GzipHandlerFunc(EndpointStatus))).Methods("GET")
|
||||||
// TODO: router.HandleFunc("/api/v1/services/{key}/uptimes", secureIfNecessary(securityConfig, GzipHandlerFunc(serviceUptimesHandler))).Methods("GET")
|
router.HandleFunc("/api/v1/endpoints/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET")
|
||||||
// TODO: router.HandleFunc("/api/v1/services/{key}/events", secureIfNecessary(securityConfig, GzipHandlerFunc(serviceEventsHandler))).Methods("GET")
|
router.HandleFunc("/api/v1/endpoints/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge).Methods("GET")
|
||||||
|
router.HandleFunc("/api/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
|
||||||
|
router.HandleFunc("/api/v1/services/statuses", secureIfNecessary(securityConfig, EndpointStatuses)).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(EndpointStatus))).Methods("GET")
|
||||||
router.HandleFunc("/api/v1/services/{key}/uptimes/{duration}/badge.svg", UptimeBadge).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}/badge.svg", ResponseTimeBadge).Methods("GET")
|
||||||
router.HandleFunc("/api/v1/services/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET")
|
router.HandleFunc("/api/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
|
||||||
// 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))))
|
||||||
|
|||||||
@@ -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")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,10 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config/ui"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SinglePageApplication(staticFolder string, ui *config.UIConfig) http.HandlerFunc {
|
func SinglePageApplication(staticFolder string, ui *ui.Config) http.HandlerFunc {
|
||||||
return func(writer http.ResponseWriter, request *http.Request) {
|
return func(writer http.ResponseWriter, request *http.Request) {
|
||||||
t, err := template.ParseFiles(staticFolder + "/index.html")
|
t, err := template.ParseFiles(staticFolder + "/index.html")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -6,18 +6,18 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/config"
|
"github.com/TwiN/gatus/v3/config"
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwiN/gatus/v3/core"
|
||||||
"github.com/TwinProduction/gatus/storage"
|
"github.com/TwiN/gatus/v3/storage/store"
|
||||||
"github.com/TwinProduction/gatus/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")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/storage/store/common"
|
"github.com/TwiN/gatus/v3/storage/store/common"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
+4
-4
@@ -6,8 +6,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/jsonpath"
|
"github.com/TwiN/gatus/v3/jsonpath"
|
||||||
"github.com/TwinProduction/gatus/pattern"
|
"github.com/TwiN/gatus/v3/pattern"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -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.
|
||||||
|
|||||||
@@ -7,15 +7,14 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestCondition_evaluate(t *testing.T) {
|
func TestCondition_evaluate(t *testing.T) {
|
||||||
type scenario struct {
|
scenarios := []struct {
|
||||||
Name string
|
Name string
|
||||||
Condition Condition
|
Condition Condition
|
||||||
Result *Result
|
Result *Result
|
||||||
DontResolveFailedConditions bool
|
DontResolveFailedConditions bool
|
||||||
ExpectedSuccess bool
|
ExpectedSuccess bool
|
||||||
ExpectedOutput string
|
ExpectedOutput string
|
||||||
}
|
}{
|
||||||
scenarios := []scenario{
|
|
||||||
{
|
{
|
||||||
Name: "ip",
|
Name: "ip",
|
||||||
Condition: Condition("[IP] == 127.0.0.1"),
|
Condition: Condition("[IP] == 127.0.0.1"),
|
||||||
|
|||||||
+1
-1
@@ -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"`
|
||||||
|
|||||||
+5
-5
@@ -3,7 +3,7 @@ package core
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/pattern"
|
"github.com/TwiN/gatus/v3/pattern"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestIntegrationQuery(t *testing.T) {
|
func TestIntegrationQuery(t *testing.T) {
|
||||||
@@ -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,299 @@
|
|||||||
|
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 (
|
||||||
|
// 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")
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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 endpointAlert.FailureThreshold <= 0 {
|
||||||
|
endpointAlert.FailureThreshold = 3
|
||||||
|
}
|
||||||
|
if endpointAlert.SuccessThreshold <= 0 {
|
||||||
|
endpointAlert.SuccessThreshold = 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(endpoint.Name) == 0 {
|
||||||
|
return ErrEndpointWithNoName
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 = ioutil.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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,60 +6,72 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
"github.com/TwiN/gatus/v3/alerting/alert"
|
||||||
"github.com/TwinProduction/gatus/client"
|
"github.com/TwiN/gatus/v3/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaults(t *testing.T) {
|
func TestEndpoint_IsEnabled(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
if !(Endpoint{Enabled: nil}).IsEnabled() {
|
||||||
service := Service{
|
t.Error("endpoint.IsEnabled() should've returned true, because Enabled was set to nil")
|
||||||
Name: "twinnation-health",
|
|
||||||
URL: "https://twinnation.org/health",
|
|
||||||
Conditions: []*Condition{&condition},
|
|
||||||
Alerts: []*alert.Alert{{Type: alert.TypePagerDuty}},
|
|
||||||
}
|
}
|
||||||
service.ValidateAndSetDefaults()
|
if value := false; (Endpoint{Enabled: &value}).IsEnabled() {
|
||||||
if service.ClientConfig == nil {
|
t.Error("endpoint.IsEnabled() should've returned false, because Enabled was set to false")
|
||||||
t.Error("client configuration should've been set to the default configuration")
|
|
||||||
} else {
|
|
||||||
if service.ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
|
||||||
t.Errorf("Default client configuration should've set Insecure to %v, got %v", client.GetDefaultConfig().Insecure, service.ClientConfig.Insecure)
|
|
||||||
}
|
|
||||||
if service.ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
|
||||||
t.Errorf("Default client configuration should've set IgnoreRedirect to %v, got %v", client.GetDefaultConfig().IgnoreRedirect, service.ClientConfig.IgnoreRedirect)
|
|
||||||
}
|
|
||||||
if service.ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
|
||||||
t.Errorf("Default client configuration should've set Timeout to %v, got %v", client.GetDefaultConfig().Timeout, service.ClientConfig.Timeout)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if service.Method != "GET" {
|
if value := true; !(Endpoint{Enabled: &value}).IsEnabled() {
|
||||||
t.Error("Service method should've defaulted to GET")
|
t.Error("Endpoint.IsEnabled() should've returned true, because Enabled was set to true")
|
||||||
}
|
|
||||||
if service.Interval != time.Minute {
|
|
||||||
t.Error("Service interval should've defaulted to 1 minute")
|
|
||||||
}
|
|
||||||
if service.Headers == nil {
|
|
||||||
t.Error("Service headers should've defaulted to an empty map")
|
|
||||||
}
|
|
||||||
if len(service.Alerts) != 1 {
|
|
||||||
t.Error("Service should've had 1 alert")
|
|
||||||
}
|
|
||||||
if service.Alerts[0].IsEnabled() {
|
|
||||||
t.Error("Service alert should've defaulted to disabled")
|
|
||||||
}
|
|
||||||
if service.Alerts[0].SuccessThreshold != 2 {
|
|
||||||
t.Error("Service alert should've defaulted to a success threshold of 2")
|
|
||||||
}
|
|
||||||
if service.Alerts[0].FailureThreshold != 3 {
|
|
||||||
t.Error("Service alert should've defaulted to a failure threshold of 3")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestService_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaults(t *testing.T) {
|
||||||
condition := Condition("[STATUS] == 200")
|
condition := Condition("[STATUS] == 200")
|
||||||
service := Service{
|
endpoint := Endpoint{
|
||||||
Name: "twinnation-health",
|
Name: "website-health",
|
||||||
URL: "https://twinnation.org/health",
|
URL: "https://twin.sh/health",
|
||||||
|
Conditions: []*Condition{&condition},
|
||||||
|
Alerts: []*alert.Alert{{Type: alert.TypePagerDuty}},
|
||||||
|
}
|
||||||
|
endpoint.ValidateAndSetDefaults()
|
||||||
|
if endpoint.ClientConfig == nil {
|
||||||
|
t.Error("client configuration should've been set to the default configuration")
|
||||||
|
} else {
|
||||||
|
if endpoint.ClientConfig.Insecure != client.GetDefaultConfig().Insecure {
|
||||||
|
t.Errorf("Default client configuration should've set Insecure to %v, got %v", client.GetDefaultConfig().Insecure, endpoint.ClientConfig.Insecure)
|
||||||
|
}
|
||||||
|
if endpoint.ClientConfig.IgnoreRedirect != client.GetDefaultConfig().IgnoreRedirect {
|
||||||
|
t.Errorf("Default client configuration should've set IgnoreRedirect to %v, got %v", client.GetDefaultConfig().IgnoreRedirect, endpoint.ClientConfig.IgnoreRedirect)
|
||||||
|
}
|
||||||
|
if endpoint.ClientConfig.Timeout != client.GetDefaultConfig().Timeout {
|
||||||
|
t.Errorf("Default client configuration should've set Timeout to %v, got %v", client.GetDefaultConfig().Timeout, endpoint.ClientConfig.Timeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if endpoint.Method != "GET" {
|
||||||
|
t.Error("Endpoint method should've defaulted to GET")
|
||||||
|
}
|
||||||
|
if endpoint.Interval != time.Minute {
|
||||||
|
t.Error("Endpoint interval should've defaulted to 1 minute")
|
||||||
|
}
|
||||||
|
if endpoint.Headers == nil {
|
||||||
|
t.Error("Endpoint headers should've defaulted to an empty map")
|
||||||
|
}
|
||||||
|
if len(endpoint.Alerts) != 1 {
|
||||||
|
t.Error("Endpoint should've had 1 alert")
|
||||||
|
}
|
||||||
|
if endpoint.Alerts[0].IsEnabled() {
|
||||||
|
t.Error("Endpoint alert should've defaulted to disabled")
|
||||||
|
}
|
||||||
|
if endpoint.Alerts[0].SuccessThreshold != 2 {
|
||||||
|
t.Error("Endpoint alert should've defaulted to a success threshold of 2")
|
||||||
|
}
|
||||||
|
if endpoint.Alerts[0].FailureThreshold != 3 {
|
||||||
|
t.Error("Endpoint alert should've defaulted to a failure threshold of 3")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEndpoint_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
|
||||||
|
condition := Condition("[STATUS] == 200")
|
||||||
|
endpoint := Endpoint{
|
||||||
|
Name: "website-health",
|
||||||
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
ClientConfig: &client.Config{
|
ClientConfig: &client.Config{
|
||||||
Insecure: true,
|
Insecure: true,
|
||||||
@@ -67,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{
|
||||||
@@ -135,71 +147,71 @@ 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: "twinnation-health",
|
Name: "website-health",
|
||||||
URL: "https://twinnation.org/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)
|
||||||
}
|
}
|
||||||
if request.Host != "twinnation.org" {
|
if request.Host != "twin.sh" {
|
||||||
t.Error("request.Host should've been twinnation.org, but was", request.Host)
|
t.Error("request.Host should've been twin.sh, but was", request.Host)
|
||||||
}
|
}
|
||||||
if userAgent := request.Header.Get("User-Agent"); userAgent != GatusUserAgent {
|
if userAgent := request.Header.Get("User-Agent"); userAgent != GatusUserAgent {
|
||||||
t.Errorf("request.Header.Get(User-Agent) should've been %s, but was %s", GatusUserAgent, userAgent)
|
t.Errorf("request.Header.Get(User-Agent) should've been %s, but was %s", GatusUserAgent, userAgent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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: "twinnation-health",
|
Name: "website-health",
|
||||||
URL: "https://twinnation.org/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
Headers: map[string]string{
|
Headers: map[string]string{
|
||||||
"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)
|
||||||
}
|
}
|
||||||
if request.Host != "twinnation.org" {
|
if request.Host != "twin.sh" {
|
||||||
t.Error("request.Host should've been twinnation.org, but was", request.Host)
|
t.Error("request.Host should've been twin.sh, but was", request.Host)
|
||||||
}
|
}
|
||||||
if userAgent := request.Header.Get("User-Agent"); userAgent != "Test/2.0" {
|
if userAgent := request.Header.Get("User-Agent"); userAgent != "Test/2.0" {
|
||||||
t.Errorf("request.Header.Get(User-Agent) should've been %s, but was %s", "Test/2.0", userAgent)
|
t.Errorf("request.Header.Get(User-Agent) should've been %s, but was %s", "Test/2.0", userAgent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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: "twinnation-health",
|
Name: "website-health",
|
||||||
URL: "https://twinnation.org/health",
|
URL: "https://twin.sh/health",
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
Headers: map[string]string{
|
Headers: map[string]string{
|
||||||
"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)
|
||||||
}
|
}
|
||||||
@@ -208,11 +220,11 @@ 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: "twinnation-graphql",
|
Name: "website-graphql",
|
||||||
URL: "https://twinnation.org/graphql",
|
URL: "https://twin.sh/graphql",
|
||||||
Method: "POST",
|
Method: "POST",
|
||||||
Conditions: []*Condition{&condition},
|
Conditions: []*Condition{&condition},
|
||||||
GraphQL: true,
|
GraphQL: true,
|
||||||
@@ -225,8 +237,8 @@ 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)
|
||||||
}
|
}
|
||||||
@@ -242,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: "twinnation-health",
|
Name: "website-health",
|
||||||
URL: "https://twinnation.org/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)
|
||||||
}
|
}
|
||||||
@@ -262,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: "twinnation-health",
|
Name: "website-health",
|
||||||
URL: "https://twinnation.org/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)
|
||||||
}
|
}
|
||||||
@@ -283,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{
|
||||||
@@ -292,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)
|
||||||
}
|
}
|
||||||
@@ -307,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)
|
||||||
}
|
}
|
||||||
@@ -325,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")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+3
-3
@@ -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"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+10
-10
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
-283
@@ -1,283 +0,0 @@
|
|||||||
package core
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io/ioutil"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/alerting/alert"
|
|
||||||
"github.com/TwinProduction/gatus/client"
|
|
||||||
"github.com/TwinProduction/gatus/core/ui"
|
|
||||||
"github.com/TwinProduction/gatus/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
|
|
||||||
type Service struct {
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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://")
|
|
||||||
isServiceHTTP := !isServiceDNS && !isServiceTCP && !isServiceICMP && !isServiceStartTLS
|
|
||||||
if isServiceHTTP {
|
|
||||||
request = service.buildHTTPRequest()
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
|
||||||
if isServiceDNS {
|
|
||||||
service.DNS.query(service.URL, result)
|
|
||||||
result.Duration = time.Since(startTime)
|
|
||||||
} else if isServiceStartTLS {
|
|
||||||
result.Connected, certificate, err = client.CanPerformStartTLS(strings.TrimPrefix(service.URL, "starttls://"), 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
package ui
|
package ui
|
||||||
|
|
||||||
// Config is the UI configuration for services
|
// Config is the UI configuration for core.Endpoint
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// HideHostname whether to hide the hostname in the Result
|
// HideHostname whether to hide the hostname in the Result
|
||||||
HideHostname bool `yaml:"hide-hostname"`
|
HideHostname bool `yaml:"hide-hostname"`
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
# PagerDuty + Gatus Integration Benefits
|
# PagerDuty + Gatus Integration Benefits
|
||||||
- Notify on-call responders based on alerts sent from Gatus.
|
- Notify on-call responders based on alerts sent from Gatus.
|
||||||
- Incidents will automatically resolve in PagerDuty when the service that caused the incident in Gatus returns to a healthy state.
|
- Incidents will automatically resolve in PagerDuty when the endpoint that caused the incident in Gatus returns to a healthy state.
|
||||||
|
|
||||||
|
|
||||||
# How it Works
|
# How it Works
|
||||||
- Services that do not meet the user-specified conditions and that are configured with alerts of type `pagerduty` will trigger a new incident on the corresponding PagerDuty service when the alert's defined `failure-threshold` has been reached.
|
- Endpoints that do not meet the user-specified conditions and that are configured with alerts of type `pagerduty` will trigger a new incident on the corresponding PagerDuty service when the alert's defined `failure-threshold` has been reached.
|
||||||
- Once the unhealthy services have returned to a healthy state for the number of executions defined in `success-threshold`, the previously triggered incident will be automatically resolved.
|
- Once the unhealthy endpoints have returned to a healthy state for the number of executions defined in `success-threshold`, the previously triggered incident will be automatically resolved.
|
||||||
|
|
||||||
|
|
||||||
# Requirements
|
# Requirements
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
|
|
||||||
# Support
|
# Support
|
||||||
If you need help with this integration, please create an issue at https://github.com/TwinProduction/gatus/issues
|
If you need help with this integration, please create an issue at https://github.com/TwiN/gatus/issues
|
||||||
|
|
||||||
|
|
||||||
# Integration Walkthrough
|
# Integration Walkthrough
|
||||||
@@ -26,7 +26,7 @@ If you need help with this integration, please create an issue at https://github
|
|||||||
3. Enter an **Integration Name** in the format `gatus-service-name` (e.g. `Gatus-Shopping-Cart`) and select **Gatus** from the Integration Type menu.
|
3. Enter an **Integration Name** in the format `gatus-service-name` (e.g. `Gatus-Shopping-Cart`) and select **Gatus** from the Integration Type menu.
|
||||||
4. Click the **Add Integration** button to save your new integration. You will be redirected to the Integrations tab for your service.
|
4. Click the **Add Integration** button to save your new integration. You will be redirected to the Integrations tab for your service.
|
||||||
5. An **Integration Key** will be generated on this screen. Keep this key saved in a safe place, as it will be used when you configure the integration with **Gatus** in the next section.
|
5. An **Integration Key** will be generated on this screen. Keep this key saved in a safe place, as it will be used when you configure the integration with **Gatus** in the next section.
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
## In Gatus
|
## In Gatus
|
||||||
@@ -36,12 +36,12 @@ alerting:
|
|||||||
pagerduty:
|
pagerduty:
|
||||||
integration-key: "********************************"
|
integration-key: "********************************"
|
||||||
```
|
```
|
||||||
You can now add alerts of type `pagerduty` in the services you've defined, like so:
|
You can now add alerts of type `pagerduty` in the endpoint you've defined, like so:
|
||||||
```yaml
|
```yaml
|
||||||
services:
|
endpoints:
|
||||||
- name: twinnation
|
- name: website
|
||||||
interval: 30s
|
interval: 30s
|
||||||
url: "https://twinnation.org/health"
|
url: "https://twin.sh/health"
|
||||||
alerts:
|
alerts:
|
||||||
- type: pagerduty
|
- type: pagerduty
|
||||||
enabled: true
|
enabled: true
|
||||||
@@ -56,12 +56,12 @@ services:
|
|||||||
```
|
```
|
||||||
|
|
||||||
The sample above will do the following:
|
The sample above will do the following:
|
||||||
- Send a request to the `https://twinnation.org/health` (`services[].url`) specified every **30s** (`services[].interval`)
|
- Send a request to the `https://twin.sh/health` (`endpoints[].url`) specified every **30s** (`endpoints[].interval`)
|
||||||
- Evaluate the conditions to determine whether the service is "healthy" or not
|
- Evaluate the conditions to determine whether the endpoint is "healthy" or not
|
||||||
- **If all conditions are not met 3 (`services[].alerts[].failure-threshold`) times in a row**: Gatus will create a new incident
|
- **If all conditions are not met 3 (`endpoints[].alerts[].failure-threshold`) times in a row**: Gatus will create a new incident
|
||||||
- **If, after an incident has been triggered, all conditions are met 5 (`services[].alerts[].success-threshold`) times in a row _AND_ `services[].alerts[].send-on-resolved` is set to `true`**: Gatus will resolve the triggered incident
|
- **If, after an incident has been triggered, all conditions are met 5 (`endpoints[].alerts[].success-threshold`) times in a row _AND_ `endpoints[].alerts[].send-on-resolved` is set to `true`**: Gatus will resolve the triggered incident
|
||||||
|
|
||||||
It is highly recommended to set `services[].alerts[].send-on-resolved` to true for alerts of type `pagerduty`.
|
It is highly recommended to set `endpoints[].alerts[].send-on-resolved` to true for alerts of type `pagerduty`.
|
||||||
|
|
||||||
|
|
||||||
# How to Uninstall
|
# How to Uninstall
|
||||||
|
|||||||
Loaded 100 of 1415 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user