Compare commits

...
92 Commits
Author SHA1 Message Date
TwiN fe4d9821f3 fix(alerting): Fix Discord alert payload missing required field 2022-10-20 20:23:10 -04:00
TwiN d01a5d418b test: Improve error readability 2022-10-20 20:23:10 -04:00
TwiN 34f8cd1eca docs: Update screenshot of Mattermost alerts 2022-10-20 20:23:10 -04:00
TwiN d101c17136 fix(alerting): Resolve Mattermost issue with bad payload when condition has " in it 2022-10-20 20:23:10 -04:00
TwiN ade3d05983 fix(alerting): Use required Field.Title in Slack provider even if it's not enforced
Just to prevent future issues
2022-10-20 20:23:10 -04:00
TwiN fbab0ef7ca fix(alerting): Resolve Discord issue with bad payload when condition has " in it 2022-10-20 20:23:10 -04:00
TwiN 9121ec1cc8 fix(alerting): Resolve Matrix issue with bad payload when condition has " in it 2022-10-20 20:23:10 -04:00
TwiN 6ddf1258e5 fix(alerting): Resolve PagerDuty issue with bad payload when alert description has " in it 2022-10-20 20:23:10 -04:00
TwiN 490610ccfd fix(alerting): Resolve Teams issue with bad payload when condition has " in it 2022-10-20 20:23:10 -04:00
TwiN 0eb6958085 fix(alerting): Resolve Telegram issue with bad payload when condition has " in it 2022-10-20 20:23:10 -04:00
TwiN d20a41c7a7 fix(alerting): Make sure to close response body 2022-10-20 20:23:10 -04:00
TwiN 4c18e0d602 chore(alerting): Remove unnecessary cast 2022-10-20 20:23:10 -04:00
TwiN da24b7e8ac fix(alerting): Resolve Slack issue with bad payload when condition has " in it 2022-10-20 20:23:10 -04:00
TwiN c619066e25 docs: Swap conditions/dark screenshots 2022-10-19 18:00:53 -04:00
TwiN 3688dd6e6f chore: Clean up unused assets 2022-10-19 17:53:43 -04:00
TwiN fc778300be ci: Update Go to 1.19 2022-10-19 17:52:53 -04:00
TwiN df560ad872 ui: Replace and reposition old icons by SVG icons (#349) 2022-10-19 17:38:32 -04:00
TwiN de9c366777 docs: Add Keeping your configuration small section 2022-10-19 16:51:14 -04:00
TwiN 6a5fec2c55 perf: Improve jsonpath speed (#348) 2022-10-19 15:52:20 -04:00
TwiN 01d2ed3f02 ui: Make it more obvious that the response time can be toggled between avg and min-max 2022-10-17 00:49:33 -04:00
TwiN 92b85ee1ab ui: Improve login page 2022-10-17 00:48:40 -04:00
TwiN a789deb8c2 ui: Render div instead of a when link is blank (#346)
Fixes #343
2022-10-17 00:03:15 -04:00
David Wheatley e5a94979dd fix: add Google Chat to list of alert types when determining valid providers (#341) 2022-10-15 17:56:38 -04:00
TwiN 3c0ea72a5c ci: Bump docker/build-push-action to v3 2022-10-10 22:11:19 -04:00
TwiN d17e893131 docs: Uniformize number of newlines between each header 2022-10-10 22:05:48 -04:00
TwiN 7ea34ec8a8 docs: Add link for sponsoring below description 2022-10-10 21:49:55 -04:00
TwiN f6b99f34db ci: Add missing concurrency.group parameter 2022-10-09 23:08:52 -04:00
TwiN 37495ac3f3 ci: Prevent publish-latest workflow from running concurrently 2022-10-09 23:02:05 -04:00
TwiN 557f696f88 fix(alerting): Encode messagebird request body using json.Marshal 2022-10-09 22:59:18 -04:00
TwiN c86492dbfd fix(alerting): Encode ntfy request body using json.Marshal
Relevant: #336
2022-10-09 22:58:18 -04:00
TwiN 8a4db600c9 test: Add tests for endpoint display name 2022-10-09 21:34:36 -04:00
TwiN 02879e2645 ci: Bump docker/build-push-action to v3 and add "stable" tag 2022-10-09 21:33:55 -04:00
TwiN 00b56ecefd feat: Bundle assets in binary using go:embed (#340)
Fixes #47
2022-10-09 21:33:31 -04:00
TwiN 47dd18a0b5 test(alerting): Add coverage for ntfy's request body 2022-10-09 16:45:01 -04:00
TwiN 1a708ebca2 test(alerting): Fix tests following change to defaults 2022-10-09 16:45:01 -04:00
TwiN 5f8e62dad0 fix(alerting): Make priority and url optional for ntfy 2022-10-09 16:45:01 -04:00
TwiN b74f7758dc docs(alerting): Document how to configure ntfy alerts 2022-10-09 16:45:01 -04:00
TwiN 899c19b2d7 fix: Swap tag for resolved and triggered 2022-10-09 16:45:01 -04:00
TwiN 35038a63c4 feat(alerting): Implement ntfy provider
Closes #308

Work remaining:
- Add the documentation on the README.md
- Test it with an actual Ntfy instance (I've only used https://ntfy.sh/docs/examples/#gatus as a reference; I haven't actually tested it yet)
2022-10-09 16:45:01 -04:00
TwiN 7b2af3c514 chore: Fix alerting provider order 2022-10-09 16:45:01 -04:00
TwiN 4ab7428599 chore: Format code 2022-10-09 16:45:01 -04:00
TwiN be88af5d48 chore: Update Go to 1.19 + Update dependencies 2022-09-21 20:16:00 -04:00
TwiN 5bb3f6d0a9 refactor: Use %w instead of %s for formatting errors 2022-09-20 21:54:59 -04:00
TwiN 17c14a7243 docs(alerting): Provide better Matrix examples 2022-09-19 22:08:39 -04:00
TwiN f44d4055e6 refactor(alerting): Clean up Matrix code 2022-09-19 22:08:18 -04:00
TwiN 38054f57e5 feat: Set minimum interval for endpoints with [DOMAIN_EXPIRATION] to 5m 2022-09-15 21:23:14 -04:00
TwiN 33ce0e99b5 chore: Fix typo in deprecation message 2022-09-15 17:41:24 -04:00
TwiN b5e6466c1d docs(security): Link "Securing Gatus with OIDC using Auth0" article 2022-09-09 22:59:13 -04:00
TwiN f89ecd5c64 fix(ui): Decrease size of error message 2022-09-09 22:58:45 -04:00
TwiN e434178a5c test(alerting): Make sure ClientConfig is set after IsValid() call in Telegram provider 2022-09-07 19:02:30 -04:00
Lukas Schlötterer 7a3ee1b557 feat(alerting): add client config for telegram (#324) 2022-09-07 18:50:59 -04:00
TwiN e51abaf5bd chore: Add check-domain-expiration to placeholder configuration file 2022-09-07 18:19:57 -04:00
TwiN 46d6d6c733 test(alerting): Improve coverage for custom alerting provider 2022-09-07 18:19:20 -04:00
TwiN d9f86f1155 fix(storage): Default domain_expiration to 0 for SQL when the column doesn't already exist
This will prevent temporary issues with the parsing of old results that would otherwise
have a value of NULL for domain_expiration

Fixes an issue introduced by #325
2022-09-07 18:18:26 -04:00
TwiN 01484832fc feat: Add [DOMAIN_EXPIRATION] placeholder for monitoring domain expiration using WHOIS (#325)
* feat: Add [DOMAIN_EXPIRATION] placeholder for monitoring domain expiration using WHOIS

* test: Fix issue caused by possibility of millisecond elapsed during previous tests

* test: Fix test with different behavior based on architecture

* docs: Revert accidental change to starttls example

* docs: Fix mistake in comment for Condition.hasIPPlaceholder()
2022-09-06 21:22:02 -04:00
TwiN 4857b43771 test: Improve coverage for Endpoint.Type() 2022-09-01 21:12:29 -04:00
TwiN 52d7cb6f04 ux: Improve endpoint validation by checking type on start 2022-09-01 21:12:29 -04:00
TwiN 5c6bf84106 ux: Improve error message when endpoint is invalid 2022-09-01 21:12:29 -04:00
TwiN c84ae1cd55 refactor: Remove unused file 2022-09-01 21:12:29 -04:00
TwiN daf8e3a16f test(chart): Improve coverage for response time charts 2022-08-30 20:00:04 -04:00
TwiN df719958cf chore(remote): Log message about feature being a candidate for removal 2022-08-23 21:38:50 -04:00
TwiN 2be81b8e1a docs(remote): Add "Remote instances (EXPERIMENTAL)" section 2022-08-22 18:26:36 -04:00
TwiN 4bed86dec9 ui(event): Add divider between each event 2022-08-18 20:24:52 -04:00
TwiN 072cf20cc6 chore(dependencies): Update tailwindcss to 3.1.8 2022-08-18 20:24:08 -04:00
TwiN cca421e283 refactor(storage): Remove TODO comment about writeThroughCache 2022-08-18 19:29:39 -04:00
TwiN a044f1d274 docs(storage): Add documentation for storage.caching 2022-08-18 19:29:39 -04:00
TwiN 9de6334f21 feat(storage): Add optional write-through cache to sql store 2022-08-18 19:29:39 -04:00
TwiN f01b66f083 refactor(storage): Remove decommissioned path for memory store (#313) 2022-08-11 20:42:56 -04:00
TwiN 262d436533 ci: Remove paths-ignore since workflow_run doesn't support it 2022-08-11 20:33:25 -04:00
TwiN b8ab17eee1 ci: Decrease timeout-minutes to 20 2022-08-11 20:31:36 -04:00
TwiN 7bbd7bcee3 ci: Stop publish-latest from being triggered by changes in .github folder 2022-08-11 20:29:33 -04:00
TwiN 4865d12147 chore(ci): Remove redundant input
Since we now get to pick from what branch to execute the workflow, it is no longer necessary to have a branch input.
2022-08-11 20:27:48 -04:00
TwiN 0713ca1c1a chore(ci): Remove useless "description" parameter 2022-08-11 20:25:10 -04:00
TwiN dce202d0be feat(ci): Add publish-experimental workflow 2022-08-11 20:24:23 -04:00
TwiN 4673d147db chore(ci): Update docker/login-action to v2 2022-08-11 20:17:17 -04:00
TwiN 0943c45ae6 test(badge): Add test cases for custom response-time badge thresholds 2022-08-10 21:26:36 -04:00
TwiN 798c4248ff refactor(badge): Fix formatting 2022-08-10 21:09:22 -04:00
JesibuandTwiN 1bce4e727e feat(api): Configurable response time badge thresholds (#309)
* recreated all changes for setting thresholds on Uptime Badges

* Suggestion accepted: Update core/ui/ui.go

Co-authored-by: TwiN <twin@linux.com>

* Suggestion accepted: Update core/ui/ui.go

Co-authored-by: TwiN <twin@linux.com>

* implemented final suggestions by Twin

* Update controller/handler/badge.go

* Update README.md

* test: added the suggestons to set the UiConfig at another line

Co-authored-by: TwiN <twin@linux.com>
2022-08-10 21:05:34 -04:00
TwiN 1aa94a3365 feat(remote): Implement lazy distributed feature (#64)
THIS IS AN EXPERIMENTAL FEATURE/IMPLEMENTATION, AND IT MAY BE REMOVED IN THE FUTURE.

Note that for now, it will be an undocumented feature.
2022-07-28 20:29:29 -04:00
TwiN 319f460553 docs: Update GetHTTPClient comment 2022-07-28 20:29:29 -04:00
TwiN 7daf2b5cac legal: Revert change to copyright appendix
relevant: #203
2022-07-28 17:55:23 -04:00
TwiN f0fc275f67 legal: Update copyright dates 2022-07-28 09:20:42 -04:00
Kalissaac 04a682eddc style(alerting): Alphabetically sort Matrix provider 2022-07-20 19:00:12 -04:00
Kalissaac 2fb807632c style(alerting): Add comments and rename character bytes constant 2022-07-20 19:00:12 -04:00
Kalissaac 4b339bca37 fix(alerting): Update Matrix send endpoint to v3 2022-07-20 19:00:12 -04:00
Kalissaac 09c3a6c72b fix(alerting): Reuse MatrixProviderConfig struct 2022-07-20 19:00:12 -04:00
Kalissaac 755c8bb43a fix(alerting): Alphabetically sort Matrix provider 2022-07-20 19:00:12 -04:00
Kalissaac 9d4a639f31 test(alerting): Add Matrix tests 2022-07-20 19:00:12 -04:00
Kalissaac 60e6b2b039 docs(alerting): Add Matrix alerts to README 2022-07-20 19:00:12 -04:00
Kalissaac 37f3f964ea feat(alerts): Add Matrix alert provider 2022-07-20 19:00:12 -04:00
TwiN 4a1a8ff380 ci: Increase timeout-minutes to 60 2022-07-18 20:45:42 -04:00
TwiN 6787fed062 docs: Update feedback/question contact 2022-07-14 18:13:46 -04:00
110 changed files with 5844 additions and 3365 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 48 KiB

+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
steps: steps:
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: 1.18 go-version: 1.19
repository: "${{ github.event.inputs.repository }}" repository: "${{ github.event.inputs.repository }}"
ref: "${{ github.event.inputs.ref }}" ref: "${{ github.event.inputs.ref }}"
- uses: actions/checkout@v3 - uses: actions/checkout@v3
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
steps: steps:
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: 1.18 go-version: 1.19
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Build binary to make sure it works - name: Build binary to make sure it works
run: go build -mod vendor run: go build -mod vendor
@@ -0,0 +1,27 @@
name: publish-experimental
on: [workflow_dispatch]
jobs:
publish-experimental:
name: publish-experimental
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v3
- name: Get image repository
run: echo IMAGE_REPOSITORY=$(echo ${{ secrets.DOCKER_USERNAME }}/${{ github.event.repository.name }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to Docker Registry
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push docker image
uses: docker/build-push-action@v3
with:
platforms: linux/amd64
pull: true
push: true
tags: ${{ env.IMAGE_REPOSITORY }}:experimental
+7 -5
View File
@@ -4,12 +4,15 @@ on:
workflows: ["build"] workflows: ["build"]
branches: [master] branches: [master]
types: [completed] types: [completed]
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: true
jobs: jobs:
publish-latest: publish-latest:
name: publish-latest name: publish-latest
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }} if: ${{ github.event.workflow_run.conclusion == 'success' }}
timeout-minutes: 45 timeout-minutes: 60
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Get image repository - name: Get image repository
@@ -19,15 +22,14 @@ jobs:
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1 uses: docker/setup-buildx-action@v1
- name: Login to Docker Registry - name: Login to Docker Registry
uses: docker/login-action@v1 uses: docker/login-action@v2
with: with:
username: ${{ secrets.DOCKER_USERNAME }} username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }} password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push docker image - name: Build and push docker image
uses: docker/build-push-action@v2 uses: docker/build-push-action@v3
with: with:
platforms: linux/amd64,linux/arm/v6,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: ${{ env.IMAGE_REPOSITORY }}:latest
${{ env.IMAGE_REPOSITORY }}:latest
+4 -5
View File
@@ -6,7 +6,7 @@ jobs:
publish-release: publish-release:
name: publish-release name: publish-release
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 45 timeout-minutes: 60
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Get image repository - name: Get image repository
@@ -18,15 +18,14 @@ jobs:
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1 uses: docker/setup-buildx-action@v1
- name: Login to Docker Registry - name: Login to Docker Registry
uses: docker/login-action@v1 uses: docker/login-action@v2
with: with:
username: ${{ secrets.DOCKER_USERNAME }} username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }} password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push docker image - name: Build and push docker image
uses: docker/build-push-action@v2 uses: docker/build-push-action@v3
with: with:
platforms: linux/amd64,linux/arm/v6,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: ${{ env.IMAGE_REPOSITORY }}:${{ env.RELEASE }},${{ env.IMAGE_REPOSITORY }}:stable
${{ env.IMAGE_REPOSITORY }}:${{ env.RELEASE }}
-1
View File
@@ -13,7 +13,6 @@ RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -a -installsuffix cgo -o gatus
FROM scratch FROM scratch
COPY --from=builder /app/gatus . COPY --from=builder /app/gatus .
COPY --from=builder /app/config.yaml ./config/config.yaml COPY --from=builder /app/config.yaml ./config/config.yaml
COPY --from=builder /app/web/static ./web/static
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
ENV PORT=8080 ENV PORT=8080
EXPOSE ${PORT} EXPOSE ${PORT}
+1 -1
View File
@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier same "printed page" as the copyright notice for easier
identification within third-party archives. identification within third-party archives.
Copyright 2021 TwiN Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
+218 -21
View File
@@ -24,9 +24,12 @@ docker run -p 8080:8080 --name gatus twinproduction/gatus
For more details, see [Usage](#usage) For more details, see [Usage](#usage)
</details> </details>
![Gatus dashboard conditions](.github/assets/dashboard-conditions.png) ![Gatus dashboard](.github/assets/dashboard-dark.png)
Have any feedback or questions? [Create a discussion](https://github.com/TwiN/gatus/discussions/new).
Like this project? Please consider [sponsoring me](https://github.com/sponsors/TwiN).
Have any feedback or want to share your good/bad experience with Gatus? Feel free to email me at [feedback@gatus.io](mailto:feedback@gatus.io)
## Table of Contents ## Table of Contents
- [Why Gatus?](#why-gatus) - [Why Gatus?](#why-gatus)
@@ -42,8 +45,10 @@ Have any feedback or want to share your good/bad experience with Gatus? Feel fre
- [Configuring Discord alerts](#configuring-discord-alerts) - [Configuring Discord alerts](#configuring-discord-alerts)
- [Configuring Email alerts](#configuring-email-alerts) - [Configuring Email alerts](#configuring-email-alerts)
- [Configuring Google Chat alerts](#configuring-google-chat-alerts) - [Configuring Google Chat alerts](#configuring-google-chat-alerts)
- [Configuring Matrix alerts](#configuring-matrix-alerts)
- [Configuring Mattermost alerts](#configuring-mattermost-alerts) - [Configuring Mattermost alerts](#configuring-mattermost-alerts)
- [Configuring Messagebird alerts](#configuring-messagebird-alerts) - [Configuring Messagebird alerts](#configuring-messagebird-alerts)
- [Configuring Ntfy alerts](#configuring-ntfy-alerts)
- [Configuring Opsgenie alerts](#configuring-opsgenie-alerts) - [Configuring Opsgenie alerts](#configuring-opsgenie-alerts)
- [Configuring PagerDuty alerts](#configuring-pagerduty-alerts) - [Configuring PagerDuty alerts](#configuring-pagerduty-alerts)
- [Configuring Slack alerts](#configuring-slack-alerts) - [Configuring Slack alerts](#configuring-slack-alerts)
@@ -55,8 +60,9 @@ Have any feedback or want to share your good/bad experience with Gatus? Feel fre
- [Maintenance](#maintenance) - [Maintenance](#maintenance)
- [Security](#security) - [Security](#security)
- [Basic](#basic) - [Basic](#basic)
- [OIDC (ALPHA)](#oidc-alpha) - [OIDC](#oidc)
- [Metrics](#metrics) - [Metrics](#metrics)
- [Remote instances (EXPERIMENTAL)](#remote-instances-experimental)
- [Deployment](#deployment) - [Deployment](#deployment)
- [Docker](#docker) - [Docker](#docker)
- [Helm Chart](#helm-chart) - [Helm Chart](#helm-chart)
@@ -72,10 +78,12 @@ Have any feedback or want to share your good/bad experience with Gatus? Feel fre
- [Monitoring an endpoint using DNS queries](#monitoring-an-endpoint-using-dns-queries) - [Monitoring an endpoint using DNS queries](#monitoring-an-endpoint-using-dns-queries)
- [Monitoring an endpoint using STARTTLS](#monitoring-an-endpoint-using-starttls) - [Monitoring an endpoint using STARTTLS](#monitoring-an-endpoint-using-starttls)
- [Monitoring an endpoint using TLS](#monitoring-an-endpoint-using-tls) - [Monitoring an endpoint using TLS](#monitoring-an-endpoint-using-tls)
- [Monitoring domain expiration](#monitoring-domain-expiration)
- [disable-monitoring-lock](#disable-monitoring-lock) - [disable-monitoring-lock](#disable-monitoring-lock)
- [Reloading configuration on the fly](#reloading-configuration-on-the-fly) - [Reloading configuration on the fly](#reloading-configuration-on-the-fly)
- [Endpoint groups](#endpoint-groups) - [Endpoint groups](#endpoint-groups)
- [Exposing Gatus on a custom port](#exposing-gatus-on-a-custom-port) - [Exposing Gatus on a custom port](#exposing-gatus-on-a-custom-port)
- [Keeping your configuration small](#keeping-your-configuration-small)
- [Badges](#badges) - [Badges](#badges)
- [Uptime](#uptime) - [Uptime](#uptime)
- [Health](#health) - [Health](#health)
@@ -84,6 +92,7 @@ Have any feedback or want to share your good/bad experience with Gatus? Feel fre
- [High level design overview](#high-level-design-overview) - [High level design overview](#high-level-design-overview)
- [Sponsors](#sponsors) - [Sponsors](#sponsors)
## Why Gatus? ## Why Gatus?
Before getting into the specifics, I want to address the most common question: Before getting into the specifics, I want to address the most common question:
> Why would I use Gatus when I can just use Prometheus’ Alertmanager, Cloudwatch or even Splunk? > Why would I use Gatus when I can just use Prometheus’ Alertmanager, Cloudwatch or even Splunk?
@@ -113,7 +122,8 @@ The main features of Gatus are:
- **[Badges](#badges)**: ![Uptime 7d](https://status.twin.sh/api/v1/endpoints/core_blog-external/uptimes/7d/badge.svg) ![Response time 24h](https://status.twin.sh/api/v1/endpoints/core_blog-external/response-times/24h/badge.svg) - **[Badges](#badges)**: ![Uptime 7d](https://status.twin.sh/api/v1/endpoints/core_blog-external/uptimes/7d/badge.svg) ![Response time 24h](https://status.twin.sh/api/v1/endpoints/core_blog-external/response-times/24h/badge.svg)
- **Dark mode** - **Dark mode**
![Gatus dashboard dark mode](.github/assets/dashboard-dark.png) ![Gatus dashboard conditions](.github/assets/dashboard-conditions.png)
## Usage ## Usage
By default, the configuration file is expected to be at `config/config.yaml`. By default, the configuration file is expected to be at `config/config.yaml`.
@@ -177,6 +187,7 @@ If you want to test it locally, see [Docker](#docker).
| `endpoints[].ui.hide-hostname` | Whether to hide the hostname in the result. | `false` | | `endpoints[].ui.hide-hostname` | Whether to hide the hostname in the result. | `false` |
| `endpoints[].ui.hide-url` | Whether to ensure the URL is not displayed in the results. Useful if the URL contains a token. | `false` | | `endpoints[].ui.hide-url` | Whether to ensure the URL is not displayed in the results. Useful if the URL contains a token. | `false` |
| `endpoints[].ui.dont-resolve-failed-conditions` | Whether to resolve failed conditions for the UI. | `false` | | `endpoints[].ui.dont-resolve-failed-conditions` | Whether to resolve failed conditions for the UI. | `false` |
| `endpoints[].ui.badge.reponse-time` | List of response time thresholds. Each time a threshold is reached, the badge has a different color. | `[50, 200, 300, 500, 750]` |
| `alerting` | [Alerting configuration](#alerting). | `{}` | | `alerting` | [Alerting configuration](#alerting). | `{}` |
| `security` | [Security configuration](#security). | `{}` | | `security` | [Security configuration](#security). | `{}` |
| `disable-monitoring-lock` | Whether to [disable the monitoring lock](#disable-monitoring-lock). | `false` | | `disable-monitoring-lock` | Whether to [disable the monitoring lock](#disable-monitoring-lock). | `false` |
@@ -219,18 +230,20 @@ Here are some examples of conditions you can use:
| `[BODY].name == pat(john*)` | String at JSONPath `$.name` matches pattern `john*` | `{"name":"john.doe"}` | `{"name":"bob"}` | | `[BODY].name == pat(john*)` | String at JSONPath `$.name` matches pattern `john*` | `{"name":"john.doe"}` | `{"name":"bob"}` |
| `[BODY].id == any(1, 2)` | Value at JSONPath `$.id` is equal to `1` or `2` | 1, 2 | 3, 4, 5 | | `[BODY].id == any(1, 2)` | Value at JSONPath `$.id` is equal to `1` or `2` | 1, 2 | 3, 4, 5 |
| `[CERTIFICATE_EXPIRATION] > 48h` | Certificate expiration is more than 48h away | 49h, 50h, 123h | 1h, 24h, ... | | `[CERTIFICATE_EXPIRATION] > 48h` | Certificate expiration is more than 48h away | 49h, 50h, 123h | 1h, 24h, ... |
| `[DOMAIN_EXPIRATION] > 720h` | The domain must expire in more than 720h | 4000h | 1h, 24h, ... |
#### Placeholders #### Placeholders
| Placeholder | Description | Example of resolved value | | Placeholder | Description | Example of resolved value |
|:---------------------------|:------------------------------------------------------------------------------------------|:---------------------------------------------| |:---------------------------|:------------------------------------------------------------------------------------------|:---------------------------------------------|
| `[STATUS]` | Resolves into the HTTP status of the request | 404 | | `[STATUS]` | Resolves into the HTTP status of the request | `404` |
| `[RESPONSE_TIME]` | Resolves into the response time the request took, in ms | 10 | | `[RESPONSE_TIME]` | Resolves into the response time the request took, in ms | `10` |
| `[IP]` | Resolves into the IP of the target host | 192.168.0.232 | | `[IP]` | Resolves into the IP of the target host | `192.168.0.232` |
| `[BODY]` | Resolves into the response body. Supports JSONPath. | `{"name":"john.doe"}` | | `[BODY]` | Resolves into the response body. Supports JSONPath. | `{"name":"john.doe"}` |
| `[CONNECTED]` | Resolves into whether a connection could be established | `true` | | `[CONNECTED]` | Resolves into whether a connection could be established | `true` |
| `[CERTIFICATE_EXPIRATION]` | Resolves into the duration before certificate expiration (valid units are "s", "m", "h".) | `24h`, `48h`, 0 (if not protocol with certs) | | `[CERTIFICATE_EXPIRATION]` | Resolves into the duration before certificate expiration (valid units are "s", "m", "h".) | `24h`, `48h`, 0 (if not protocol with certs) |
| `[DNS_RCODE]` | Resolves into the DNS status of the response | NOERROR | | `[DOMAIN_EXPIRATION]` | Resolves into the duration before the domain expires (valid units are "s", "m", "h".) | `24h`, `48h`, `1234h56m78s` |
| `[DNS_RCODE]` | Resolves into the DNS status of the response | `NOERROR` |
#### Functions #### Functions
@@ -245,11 +258,12 @@ Here are some examples of conditions you can use:
### Storage ### Storage
| Parameter | Description | Default | | Parameter | Description | Default |
|:---------------|:-------------------------------------------------------------------------------|:-----------| |:------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------|:-----------|
| `storage` | Storage configuration | `{}` | | `storage` | Storage configuration | `{}` |
| `storage.path` | Path to persist the data in. Only supported for types `sqlite` and `postgres`. | `""` | | `storage.path` | Path to persist the data in. Only supported for types `sqlite` and `postgres`. | `""` |
| `storage.type` | Type of storage. Valid types: `memory`, `sqlite`, `postgres`. | `"memory"` | | `storage.type` | Type of storage. Valid types: `memory`, `sqlite`, `postgres`. | `"memory"` |
| `storage.caching` | Whether to use write-through caching. Improves loading time for large dashboards. <br />Only supported if `storage.type` is `sqlite` or `postgres` | `false` |
- If `storage.type` is `memory` (default): - If `storage.type` is `memory` (default):
```yaml ```yaml
@@ -342,6 +356,7 @@ endpoints:
- "[STATUS] == 200" - "[STATUS] == 200"
``` ```
### Alerting ### Alerting
Gatus supports multiple alerting providers, such as Slack and PagerDuty, and supports different alerts for each Gatus supports multiple alerting providers, such as Slack and PagerDuty, and supports different alerts for each
individual endpoints with configurable descriptions and thresholds. individual endpoints with configurable descriptions and thresholds.
@@ -354,8 +369,10 @@ ignored.
| `alerting.discord` | Configuration for alerts of type `discord`. <br />See [Configuring Discord alerts](#configuring-discord-alerts). | `{}` | | `alerting.discord` | Configuration for alerts of type `discord`. <br />See [Configuring Discord alerts](#configuring-discord-alerts). | `{}` |
| `alerting.email` | Configuration for alerts of type `email`. <br />See [Configuring Email alerts](#configuring-email-alerts). | `{}` | | `alerting.email` | Configuration for alerts of type `email`. <br />See [Configuring Email alerts](#configuring-email-alerts). | `{}` |
| `alerting.googlechat` | Configuration for alerts of type `googlechat`. <br />See [Configuring Google Chat alerts](#configuring-google-chat-alerts). | `{}` | | `alerting.googlechat` | Configuration for alerts of type `googlechat`. <br />See [Configuring Google Chat alerts](#configuring-google-chat-alerts). | `{}` |
| `alerting.matrix` | Configuration for alerts of type `matrix`. <br />See [Configuring Matrix alerts](#configuring-matrix-alerts). | `{}` |
| `alerting.mattermost` | Configuration for alerts of type `mattermost`. <br />See [Configuring Mattermost alerts](#configuring-mattermost-alerts). | `{}` | | `alerting.mattermost` | Configuration for alerts of type `mattermost`. <br />See [Configuring Mattermost alerts](#configuring-mattermost-alerts). | `{}` |
| `alerting.messagebird` | Configuration for alerts of type `messagebird`. <br />See [Configuring Messagebird alerts](#configuring-messagebird-alerts). | `{}` | | `alerting.messagebird` | Configuration for alerts of type `messagebird`. <br />See [Configuring Messagebird alerts](#configuring-messagebird-alerts). | `{}` |
| `alerting.ntfy` | Configuration for alerts of type `ntfy`. <br />See [Configuring Ntfy alerts](#configuring-ntfy-alerts). | `{}` |
| `alerting.opsgenie` | Configuration for alerts of type `opsgenie`. <br />See [Configuring Opsgenie alerts](#configuring-opsgenie-alerts). | `{}` | | `alerting.opsgenie` | Configuration for alerts of type `opsgenie`. <br />See [Configuring Opsgenie alerts](#configuring-opsgenie-alerts). | `{}` |
| `alerting.pagerduty` | Configuration for alerts of type `pagerduty`. <br />See [Configuring PagerDuty alerts](#configuring-pagerduty-alerts). | `{}` | | `alerting.pagerduty` | Configuration for alerts of type `pagerduty`. <br />See [Configuring PagerDuty alerts](#configuring-pagerduty-alerts). | `{}` |
| `alerting.slack` | Configuration for alerts of type `slack`. <br />See [Configuring Slack alerts](#configuring-slack-alerts). | `{}` | | `alerting.slack` | Configuration for alerts of type `slack`. <br />See [Configuring Slack alerts](#configuring-slack-alerts). | `{}` |
@@ -364,6 +381,7 @@ ignored.
| `alerting.twilio` | Settings for alerts of type `twilio`. <br />See [Configuring Twilio alerts](#configuring-twilio-alerts). | `{}` | | `alerting.twilio` | Settings for alerts of type `twilio`. <br />See [Configuring Twilio alerts](#configuring-twilio-alerts). | `{}` |
| `alerting.custom` | Configuration for custom actions on failure or alerts. <br />See [Configuring Custom alerts](#configuring-custom-alerts). | `{}` | | `alerting.custom` | Configuration for custom actions on failure or alerts. <br />See [Configuring Custom alerts](#configuring-custom-alerts). | `{}` |
#### Configuring Discord alerts #### Configuring Discord alerts
| Parameter | Description | Default | | Parameter | Description | Default |
@@ -395,6 +413,7 @@ endpoints:
send-on-resolved: true send-on-resolved: true
``` ```
#### Configuring Email alerts #### Configuring Email alerts
| Parameter | Description | Default | | Parameter | Description | Default |
@@ -456,6 +475,7 @@ endpoints:
**NOTE:** Some mail servers are painfully slow. **NOTE:** Some mail servers are painfully slow.
#### Configuring Google Chat alerts #### Configuring Google Chat alerts
| Parameter | Description | Default | | Parameter | Description | Default |
@@ -476,7 +496,7 @@ alerting:
endpoints: endpoints:
- name: website - name: website
url: "https://twin.sh/health" url: "https://twin.sh/health"
interval: 30s interval: 5m
conditions: conditions:
- "[STATUS] == 200" - "[STATUS] == 200"
- "[BODY].status == UP" - "[BODY].status == UP"
@@ -488,6 +508,39 @@ endpoints:
send-on-resolved: true send-on-resolved: true
``` ```
#### Configuring Matrix alerts
| Parameter | Description | Default |
|:-----------------------------------------|:-------------------------------------------------------------------------------------------|:-----------------------------------|
| `alerting.matrix` | Configuration for alerts of type `matrix` | `{}` |
| `alerting.matrix.server-url` | Homeserver URL | `https://matrix-client.matrix.org` |
| `alerting.matrix.access-token` | Bot user access token (see https://webapps.stackexchange.com/q/131056) | Required `""` |
| `alerting.matrix.internal-room-id` | Internal room ID of room to send alerts to (can be found in Room Settings > Advanced) | Required `""` |
| `alerting.matrix.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A |
```yaml
alerting:
matrix:
server-url: "https://matrix-client.matrix.org"
access-token: "123456"
internal-room-id: "!example:matrix.org"
endpoints:
- name: website
interval: 5m
url: "https://twin.sh/health"
conditions:
- "[STATUS] == 200"
- "[BODY].status == UP"
- "[RESPONSE_TIME] < 300"
alerts:
- type: matrix
enabled: true
send-on-resolved: true
description: "healthcheck failed"
```
#### Configuring Mattermost alerts #### Configuring Mattermost alerts
| Parameter | Description | Default | | Parameter | Description | Default |
|:----------------------------------------------|:--------------------------------------------------------------------------------------------|:--------------| |:----------------------------------------------|:--------------------------------------------------------------------------------------------|:--------------|
@@ -509,7 +562,7 @@ alerting:
endpoints: endpoints:
- name: website - name: website
url: "https://twin.sh/health" url: "https://twin.sh/health"
interval: 30s interval: 5m
conditions: conditions:
- "[STATUS] == 200" - "[STATUS] == 200"
- "[BODY].status == UP" - "[BODY].status == UP"
@@ -525,10 +578,11 @@ Here's an example of what the notifications look like:
![Mattermost notifications](.github/assets/mattermost-alerts.png) ![Mattermost notifications](.github/assets/mattermost-alerts.png)
#### Configuring Messagebird alerts #### Configuring Messagebird alerts
| Parameter | Description | Default | | Parameter | Description | Default |
|:-------------------------------------|:-------------------------------------------------------------------------------------------|:--------------| |:-------------------------------------|:-------------------------------------------------------------------------------------------|:--------------|
| `alerting.messagebird` | Settings for alerts of type `messagebird` | `{}` | | `alerting.messagebird` | Configuration for alerts of type `messagebird` | `{}` |
| `alerting.messagebird.access-key` | Messagebird access key | Required `""` | | `alerting.messagebird.access-key` | Messagebird access key | Required `""` |
| `alerting.messagebird.originator` | The sender of the message | Required `""` | | `alerting.messagebird.originator` | The sender of the message | Required `""` |
| `alerting.messagebird.recipients` | The recipients of the message | Required `""` | | `alerting.messagebird.recipients` | The recipients of the message | Required `""` |
@@ -544,7 +598,7 @@ alerting:
endpoints: endpoints:
- name: website - name: website
interval: 30s interval: 5m
url: "https://twin.sh/health" url: "https://twin.sh/health"
conditions: conditions:
- "[STATUS] == 200" - "[STATUS] == 200"
@@ -559,6 +613,42 @@ endpoints:
``` ```
#### Configuring Ntfy alerts
| Parameter | Description | Default |
|:------------------------------|:-------------------------------------------------------------------------------------------|:------------------|
| `alerting.ntfy` | Configuration for alerts of type `ntfy` | `{}` |
| `alerting.ntfy.topic` | Topic at which the alert will be sent | Required `""` |
| `alerting.ntfy.url` | The URL of the target server | `https://ntfy.sh` |
| `alerting.ntfy.priority` | The priority of the alert | `3` |
| `alerting.ntfy.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A |
[ntfy](https://github.com/binwiederhier/ntfy) is an amazing project that allows you to subscribe to desktop
and mobile notifications, making it an awesome addition to Gatus.
Example:
```yaml
alerting:
ntfy:
topic: "gatus-test-topic"
priority: 2
default-alert:
enabled: true
failure-threshold: 3
send-on-resolved: true
endpoints:
- name: website
interval: 5m
url: "https://twin.sh/health"
conditions:
- "[STATUS] == 200"
- "[BODY].status == UP"
- "[RESPONSE_TIME] < 300"
alerts:
- type: ntfy
```
#### Configuring Opsgenie alerts #### Configuring Opsgenie alerts
| Parameter | Description | Default | | Parameter | Description | Default |
|:----------------------------------|:-------------------------------------------------------------------------------------------|:---------------------| |:----------------------------------|:-------------------------------------------------------------------------------------------|:---------------------|
@@ -734,6 +824,7 @@ Here's an example of what the notifications look like:
![Teams notifications](.github/assets/teams-alerts.png) ![Teams notifications](.github/assets/teams-alerts.png)
#### Configuring Telegram alerts #### Configuring Telegram alerts
| Parameter | Description | Default | | Parameter | Description | Default |
|:----------------------------------|:-------------------------------------------------------------------------------------------|:---------------------------| |:----------------------------------|:-------------------------------------------------------------------------------------------|:---------------------------|
@@ -741,6 +832,7 @@ Here's an example of what the notifications look like:
| `alerting.telegram.token` | Telegram Bot Token | Required `""` | | `alerting.telegram.token` | Telegram Bot Token | Required `""` |
| `alerting.telegram.id` | Telegram User ID | Required `""` | | `alerting.telegram.id` | Telegram User ID | Required `""` |
| `alerting.telegram.api-url` | Telegram API URL | `https://api.telegram.org` | | `alerting.telegram.api-url` | Telegram API URL | `https://api.telegram.org` |
| `alerting.telegram.client` | Client configuration. <br />See [Client configuration](#client-configuration). | `{}` |
| `alerting.telegram.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A | | `alerting.telegram.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A |
```yaml ```yaml
@@ -962,6 +1054,7 @@ endpoints:
- type: pagerduty - type: pagerduty
``` ```
### Maintenance ### Maintenance
If you have maintenance windows, you may not want to be annoyed by alerts. If you have maintenance windows, you may not want to be annoyed by alerts.
To do that, you'll have to use the maintenance configuration: To do that, you'll have to use the maintenance configuration:
@@ -1000,6 +1093,7 @@ maintenance:
| `security.basic` | HTTP Basic configuration | `{}` | | `security.basic` | HTTP Basic configuration | `{}` |
| `security.oidc` | OpenID Connect configuration | `{}` | | `security.oidc` | OpenID Connect configuration | `{}` |
#### Basic #### Basic
| Parameter | Description | Default | | Parameter | Description | Default |
|:----------------------------------------|:-----------------------------------------------------------------------------------|:--------------| |:----------------------------------------|:-----------------------------------------------------------------------------------|:--------------|
@@ -1018,7 +1112,8 @@ security:
**WARNING:** Make sure to carefully select to cost of the bcrypt hash. The higher the cost, the longer it takes to compute the hash, **WARNING:** Make sure to carefully select to cost of the bcrypt hash. The higher the cost, the longer it takes to compute the hash,
and basic auth verifies the password against the hash on every request. As of 2022-01-08, I suggest a cost of 8. and basic auth verifies the password against the hash on every request. As of 2022-01-08, I suggest a cost of 8.
#### OIDC (ALPHA)
#### OIDC
| Parameter | Description | Default | | Parameter | Description | Default |
|:---------------------------------|:---------------------------------------------------------------|:--------------| |:---------------------------------|:---------------------------------------------------------------|:--------------|
| `security.oidc` | OpenID Connect configuration | `{}` | | `security.oidc` | OpenID Connect configuration | `{}` |
@@ -1041,7 +1136,7 @@ security:
#allowed-subjects: ["johndoe@example.com"] #allowed-subjects: ["johndoe@example.com"]
``` ```
**NOTE:** The OIDC feature is currently in Alpha. Breaking changes may occur. Use this feature at your own risk. Confused? Read [Securing Gatus with OIDC using Auth0](https://twin.sh/articles/56/securing-gatus-with-oidc-using-auth0).
### Metrics ### Metrics
@@ -1059,6 +1154,32 @@ endpoint on the same port your application is configured to run on (`web.port`).
See [examples/docker-compose-grafana-prometheus](.examples/docker-compose-grafana-prometheus) for further documentation as well as an example. See [examples/docker-compose-grafana-prometheus](.examples/docker-compose-grafana-prometheus) for further documentation as well as an example.
### Remote instances (EXPERIMENTAL)
This feature allows you to retrieve endpoint statuses from a remote Gatus instance.
There are two main use cases for this:
- You have multiple Gatus instances running on different machines, and you wish to visually expose the statuses through a single dashboard
- You have one or more Gatus instances that are not publicly accessible (e.g. behind a firewall), and you wish to retrieve
This is an experimental feature. It may be removed or updated in a breaking manner at any time. Furthermore,
there are known issues with this feature. If you'd like to provide some feedback, please write a comment in [#64](https://github.com/TwiN/gatus/issues/64).
Use at your own risk.
| Parameter | Description | Default |
|:-----------------------------------|:---------------------------------------------|:---------------|
| `remote` | Remote configuration | `{}` |
| `remote.instances` | List of remote instances | Required `[]` |
| `remote.instances.endpoint-prefix` | String to prefix all endpoint names with | `""` |
| `remote.instances.url` | URL from which to retrieve endpoint statuses | Required `""` |
```yaml
remote:
instances:
- endpoint-prefix: "status.example.org-"
url: "https://status.example.org/api/v1/endpoints/statuses"
```
## Deployment ## Deployment
Many examples can be found in the [.examples](.examples) folder, but this section will focus on the most popular ways of deploying Gatus. Many examples can be found in the [.examples](.examples) folder, but this section will focus on the most popular ways of deploying Gatus.
@@ -1105,7 +1226,6 @@ and [helmfile example](https://github.com/avakarev/gatus-chart#helmfileyaml-exam
Gatus can be deployed on Terraform by using the following module: [terraform-kubernetes-gatus](https://github.com/TwiN/terraform-kubernetes-gatus). Gatus can be deployed on Terraform by using the following module: [terraform-kubernetes-gatus](https://github.com/TwiN/terraform-kubernetes-gatus).
## Running the tests ## Running the tests
```console ```console
go test ./... -mod vendor go test ./... -mod vendor
@@ -1277,6 +1397,25 @@ endpoints:
``` ```
### Monitoring domain expiration
You can monitor the expiration of a domain with all endpoint types except for DNS by using the `[DOMAIN_EXPIRATION]`
placeholder:
```yaml
endpoints:
- name: check-domain-and-certificate-expiration
url: "https://example.org"
interval: 1h
conditions:
- "[DOMAIN_EXPIRATION] > 720h"
- "[CERTIFICATE_EXPIRATION] > 240h"
```
**NOTE**: The usage of the `[DOMAIN_EXPIRATION]` placeholder requires Gatus to send a request to the official IANA WHOIS service [through a library](https://github.com/TwiN/whois)
and in some cases, a secondary request to a TLD-specific WHOIS server (e.g. `whois.nic.sh`).
To prevent the WHOIS service from throttling your IP address if you send too many requests, Gatus will prevent you from
using the `[DOMAIN_EXPIRATION]` placeholder on an endpoint with an interval of less than `5m`.
### disable-monitoring-lock ### disable-monitoring-lock
Setting `disable-monitoring-lock` to `true` means that multiple endpoints could be monitored at the same time. Setting `disable-monitoring-lock` to `true` means that multiple endpoints could be monitored at the same time.
@@ -1348,7 +1487,7 @@ endpoints:
conditions: conditions:
- "[STATUS] == 200" - "[STATUS] == 200"
- name: random endpoint that isn't part of a group - name: random endpoint that is not part of a group
url: "https://example.org/" url: "https://example.org/"
interval: 5m interval: 5m
conditions: conditions:
@@ -1374,6 +1513,44 @@ web:
port: ${PORT} port: ${PORT}
``` ```
### Keeping your configuration small
While not specific to Gatus, you can leverage YAML anchors to create a default configuration.
If you have a large configuration file, this should help you keep things clean.
<details>
<summary>Example</summary>
```yaml
default-endpoint: &defaults
group: core
interval: 5m
client:
insecure: true
timeout: 30s
conditions:
- "[STATUS] == 200"
endpoints:
- name: anchor-example-1
<<: *defaults # This will merge the configuration under &defaults with this endpoint
url: "https://example.org"
- name: anchor-example-2
<<: *defaults
group: example # This will override the group defined in &defaults
url: "https://example.com"
- name: anchor-example-3
<<: *defaults
url: "https://twin.sh/health"
conditions: # This will override the conditions defined in &defaults
- "[STATUS] == 200"
- "[BODY].status == UP"
```
</details>
### Badges ### Badges
#### Uptime #### Uptime
![Uptime 1h](https://status.twin.sh/api/v1/endpoints/core_blog-external/uptimes/1h/badge.svg) ![Uptime 1h](https://status.twin.sh/api/v1/endpoints/core_blog-external/uptimes/1h/badge.svg)
@@ -1439,6 +1616,26 @@ Where:
- `{key}` has the pattern `<GROUP_NAME>_<ENDPOINT_NAME>` in which both variables have ` `, `/`, `_`, `,` and `.` replaced by `-`. - `{key}` has the pattern `<GROUP_NAME>_<ENDPOINT_NAME>` in which both variables have ` `, `/`, `_`, `,` and `.` replaced by `-`.
##### How to change the color thresholds of the response time badge
To change the response time badges' threshold, a corresponding configuration can be added to an endpoint.
The values in the array correspond to the levels [Awesome, Great, Good, Passable, Bad]
All five values must be given in milliseconds (ms).
```
endpoints:
- name: nas
group: internal
url: "https://example.org/"
interval: 5m
conditions:
- "[STATUS] == 200"
ui:
badge:
response-time:
thresholds: [550, 850, 1350, 1650, 1750]
```
### API ### API
Gatus provides a simple read-only API that can be queried in order to programmatically determine endpoint status and history. Gatus provides a simple read-only API that can be queried in order to programmatically determine endpoint status and history.
+9 -3
View File
@@ -17,12 +17,21 @@ const (
// TypeGoogleChat is the Type for the googlechat alerting provider // TypeGoogleChat is the Type for the googlechat alerting provider
TypeGoogleChat Type = "googlechat" TypeGoogleChat Type = "googlechat"
// TypeMatrix is the Type for the matrix alerting provider
TypeMatrix Type = "matrix"
// TypeMattermost is the Type for the mattermost alerting provider // TypeMattermost is the Type for the mattermost alerting provider
TypeMattermost Type = "mattermost" TypeMattermost Type = "mattermost"
// TypeMessagebird is the Type for the messagebird alerting provider // TypeMessagebird is the Type for the messagebird alerting provider
TypeMessagebird Type = "messagebird" TypeMessagebird Type = "messagebird"
// TypeNtfy is the Type for the ntfy alerting provider
TypeNtfy Type = "ntfy"
// TypeOpsgenie is the Type for the opsgenie alerting provider
TypeOpsgenie Type = "opsgenie"
// TypePagerDuty is the Type for the pagerduty alerting provider // TypePagerDuty is the Type for the pagerduty alerting provider
TypePagerDuty Type = "pagerduty" TypePagerDuty Type = "pagerduty"
@@ -37,7 +46,4 @@ const (
// TypeTwilio is the Type for the twilio alerting provider // TypeTwilio is the Type for the twilio alerting provider
TypeTwilio Type = "twilio" TypeTwilio Type = "twilio"
// TypeOpsgenie is the Type for the opsgenie alerting provider
TypeOpsgenie Type = "opsgenie"
) )
+23 -3
View File
@@ -7,8 +7,10 @@ import (
"github.com/TwiN/gatus/v4/alerting/provider/discord" "github.com/TwiN/gatus/v4/alerting/provider/discord"
"github.com/TwiN/gatus/v4/alerting/provider/email" "github.com/TwiN/gatus/v4/alerting/provider/email"
"github.com/TwiN/gatus/v4/alerting/provider/googlechat" "github.com/TwiN/gatus/v4/alerting/provider/googlechat"
"github.com/TwiN/gatus/v4/alerting/provider/matrix"
"github.com/TwiN/gatus/v4/alerting/provider/mattermost" "github.com/TwiN/gatus/v4/alerting/provider/mattermost"
"github.com/TwiN/gatus/v4/alerting/provider/messagebird" "github.com/TwiN/gatus/v4/alerting/provider/messagebird"
"github.com/TwiN/gatus/v4/alerting/provider/ntfy"
"github.com/TwiN/gatus/v4/alerting/provider/opsgenie" "github.com/TwiN/gatus/v4/alerting/provider/opsgenie"
"github.com/TwiN/gatus/v4/alerting/provider/pagerduty" "github.com/TwiN/gatus/v4/alerting/provider/pagerduty"
"github.com/TwiN/gatus/v4/alerting/provider/slack" "github.com/TwiN/gatus/v4/alerting/provider/slack"
@@ -31,12 +33,21 @@ type Config struct {
// Email is the configuration for the email alerting provider // Email is the configuration for the email alerting provider
Email *email.AlertProvider `yaml:"email,omitempty"` Email *email.AlertProvider `yaml:"email,omitempty"`
// Matrix is the configuration for the matrix alerting provider
Matrix *matrix.AlertProvider `yaml:"matrix,omitempty"`
// Mattermost is the configuration for the mattermost alerting provider // Mattermost is the configuration for the mattermost alerting provider
Mattermost *mattermost.AlertProvider `yaml:"mattermost,omitempty"` Mattermost *mattermost.AlertProvider `yaml:"mattermost,omitempty"`
// Messagebird is the configuration for the messagebird alerting provider // Messagebird is the configuration for the messagebird alerting provider
Messagebird *messagebird.AlertProvider `yaml:"messagebird,omitempty"` Messagebird *messagebird.AlertProvider `yaml:"messagebird,omitempty"`
// Ntfy is the configuration for the ntfy alerting provider
Ntfy *ntfy.AlertProvider `yaml:"ntfy,omitempty"`
// Opsgenie is the configuration for the opsgenie alerting provider
Opsgenie *opsgenie.AlertProvider `yaml:"opsgenie,omitempty"`
// PagerDuty is the configuration for the pagerduty alerting provider // PagerDuty is the configuration for the pagerduty alerting provider
PagerDuty *pagerduty.AlertProvider `yaml:"pagerduty,omitempty"` PagerDuty *pagerduty.AlertProvider `yaml:"pagerduty,omitempty"`
@@ -51,9 +62,6 @@ type Config struct {
// Twilio is the configuration for the twilio alerting provider // Twilio is the configuration for the twilio alerting provider
Twilio *twilio.AlertProvider `yaml:"twilio,omitempty"` Twilio *twilio.AlertProvider `yaml:"twilio,omitempty"`
// Opsgenie is the configuration for the opsgenie alerting provider
Opsgenie *opsgenie.AlertProvider `yaml:"opsgenie,omitempty"`
} }
// GetAlertingProviderByAlertType returns an provider.AlertProvider by its corresponding alert.Type // GetAlertingProviderByAlertType returns an provider.AlertProvider by its corresponding alert.Type
@@ -83,6 +91,12 @@ func (config Config) GetAlertingProviderByAlertType(alertType alert.Type) provid
return nil return nil
} }
return config.GoogleChat return config.GoogleChat
case alert.TypeMatrix:
if config.Matrix == nil {
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
return nil
}
return config.Matrix
case alert.TypeMattermost: case alert.TypeMattermost:
if config.Mattermost == nil { if config.Mattermost == nil {
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil // Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
@@ -95,6 +109,12 @@ func (config Config) GetAlertingProviderByAlertType(alertType alert.Type) provid
return nil return nil
} }
return config.Messagebird return config.Messagebird
case alert.TypeNtfy:
if config.Ntfy == nil {
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
return nil
}
return config.Ntfy
case alert.TypeOpsgenie: case alert.TypeOpsgenie:
if config.Opsgenie == nil { if config.Opsgenie == nil {
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil // Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
+1
View File
@@ -84,6 +84,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
+18 -8
View File
@@ -13,14 +13,24 @@ import (
) )
func TestAlertProvider_IsValid(t *testing.T) { func TestAlertProvider_IsValid(t *testing.T) {
invalidProvider := AlertProvider{URL: ""} t.Run("invalid-provider", func(t *testing.T) {
if invalidProvider.IsValid() { invalidProvider := AlertProvider{URL: ""}
t.Error("provider shouldn't have been valid") if invalidProvider.IsValid() {
} t.Error("provider shouldn't have been valid")
validProvider := AlertProvider{URL: "https://example.com"} }
if !validProvider.IsValid() { })
t.Error("provider should've been valid") t.Run("valid-provider", func(t *testing.T) {
} validProvider := AlertProvider{URL: "https://example.com"}
if validProvider.ClientConfig != nil {
t.Error("provider client config should have been nil prior to IsValid() being executed")
}
if !validProvider.IsValid() {
t.Error("provider should've been valid")
}
if validProvider.ClientConfig == nil {
t.Error("provider client config should have been set after IsValid() was executed")
}
})
} }
func TestAlertProvider_Send(t *testing.T) { func TestAlertProvider_Send(t *testing.T) {
+42 -21
View File
@@ -2,6 +2,7 @@ package discord
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -44,7 +45,7 @@ func (provider *AlertProvider) IsValid() bool {
// Send an alert using the provider // Send an alert using the provider
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved))) buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
request, err := http.NewRequest(http.MethodPost, provider.getWebhookURLForGroup(endpoint.Group), buffer) request, err := http.NewRequest(http.MethodPost, provider.getWebhookURLForGroup(endpoint.Group), buffer)
if err != nil { if err != nil {
return err return err
@@ -54,6 +55,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -61,8 +63,26 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return err return err
} }
type Body struct {
Content string `json:"content"`
Embeds []Embed `json:"embeds"`
}
type Embed struct {
Title string `json:"title"`
Description string `json:"description"`
Color int `json:"color"`
Fields []Field `json:"fields"`
}
type Field struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline"`
}
// buildRequestBody builds the request body for the provider // buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string { func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
var message, results string var message, results string
var colorCode int var colorCode int
if resolved { if resolved {
@@ -79,29 +99,30 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
} else { } else {
prefix = ":x:" prefix = ":x:"
} }
results += fmt.Sprintf("%s - `%s`\\n", prefix, conditionResult.Condition) results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
} }
var description string var description string
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 { if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
description = ":\\n> " + alertDescription description = ":\n> " + alertDescription
} }
return fmt.Sprintf(`{ body, _ := json.Marshal(Body{
"content": "", Content: "",
"embeds": [ Embeds: []Embed{
{ {
"title": ":helmet_with_white_cross: Gatus", Title: ":helmet_with_white_cross: Gatus",
"description": "%s%s", Description: message + description,
"color": %d, Color: colorCode,
"fields": [ Fields: []Field{
{ {
"name": "Condition results", Name: "Condition results",
"value": "%s", Value: results,
"inline": false Inline: false,
} },
] },
} },
] },
}`, message, description, colorCode, results) })
return body
} }
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group // getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
+6 -5
View File
@@ -151,14 +151,14 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Provider: AlertProvider{}, Provider: AlertProvider{},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false, Resolved: false,
ExpectedBody: "{\n \"content\": \"\",\n \"embeds\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"description\": \"An alert for **endpoint-name** has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"color\": 15158332,\n \"fields\": [\n {\n \"name\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"inline\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"content\":\"\",\"embeds\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"description\":\"An alert for **endpoint-name** has been triggered due to having failed 3 time(s) in a row:\\n\\u003e description-1\",\"color\":15158332,\"fields\":[{\"name\":\"Condition results\",\"value\":\":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n:x: - `[BODY] != \\\"\\\"`\\n\",\"inline\":false}]}]}",
}, },
{ {
Name: "resolved", Name: "resolved",
Provider: AlertProvider{}, Provider: AlertProvider{},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true, Resolved: true,
ExpectedBody: "{\n \"content\": \"\",\n \"embeds\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"description\": \"An alert for **endpoint-name** has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"color\": 3066993,\n \"fields\": [\n {\n \"name\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"inline\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"content\":\"\",\"embeds\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"description\":\"An alert for **endpoint-name** has been resolved after passing successfully 5 time(s) in a row:\\n\\u003e description-2\",\"color\":3066993,\"fields\":[{\"name\":\"Condition results\",\"value\":\":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n:white_check_mark: - `[BODY] != \\\"\\\"`\\n\",\"inline\":false}]}]}",
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
@@ -170,15 +170,16 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
ConditionResults: []*core.ConditionResult{ ConditionResults: []*core.ConditionResult{
{Condition: "[CONNECTED] == true", Success: scenario.Resolved}, {Condition: "[CONNECTED] == true", Success: scenario.Resolved},
{Condition: "[STATUS] == 200", Success: scenario.Resolved}, {Condition: "[STATUS] == 200", Success: scenario.Resolved},
{Condition: "[BODY] != \"\"", Success: scenario.Resolved},
}, },
}, },
scenario.Resolved, scenario.Resolved,
) )
if body != scenario.ExpectedBody { if string(body) != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body) t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error()) t.Error("expected body to be valid JSON, got error:", err.Error())
} }
}) })
@@ -62,6 +62,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -177,7 +177,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
b, _ := json.Marshal(body) b, _ := json.Marshal(body)
e, _ := json.Marshal(scenario.ExpectedBody) e, _ := json.Marshal(scenario.ExpectedBody)
if body != scenario.ExpectedBody { if body != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", e, b) t.Errorf("expected:\n%s\ngot:\n%s", e, b)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal([]byte(body), &out); err != nil {
+190
View File
@@ -0,0 +1,190 @@
package matrix
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"time"
"github.com/TwiN/gatus/v4/alerting/alert"
"github.com/TwiN/gatus/v4/client"
"github.com/TwiN/gatus/v4/core"
)
// AlertProvider is the configuration necessary for sending an alert using Matrix
type AlertProvider struct {
MatrixProviderConfig `yaml:",inline"`
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
// Overrides is a list of Override that may be prioritized over the default configuration
Overrides []Override `yaml:"overrides,omitempty"`
}
// Override is a case under which the default integration is overridden
type Override struct {
Group string `yaml:"group"`
MatrixProviderConfig `yaml:",inline"`
}
const defaultHomeserverURL = "https://matrix-client.matrix.org"
type MatrixProviderConfig struct {
// ServerURL is the custom homeserver to use (optional)
ServerURL string `yaml:"server-url"`
// AccessToken is the bot user's access token to send messages
AccessToken string `yaml:"access-token"`
// InternalRoomID is the room that the bot user has permissions to send messages to
InternalRoomID string `yaml:"internal-room-id"`
}
// IsValid returns whether the provider's configuration is valid
func (provider *AlertProvider) IsValid() bool {
registeredGroups := make(map[string]bool)
if provider.Overrides != nil {
for _, override := range provider.Overrides {
if isAlreadyRegistered := registeredGroups[override.Group]; isAlreadyRegistered || override.Group == "" || len(override.AccessToken) == 0 || len(override.InternalRoomID) == 0 {
return false
}
registeredGroups[override.Group] = true
}
}
return len(provider.AccessToken) > 0 && len(provider.InternalRoomID) > 0
}
// Send an alert using the provider
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
config := provider.getConfigForGroup(endpoint.Group)
if config.ServerURL == "" {
config.ServerURL = defaultHomeserverURL
}
// The Matrix endpoint requires a unique transaction ID for each event sent
txnId := randStringBytes(24)
request, err := http.NewRequest(
http.MethodPut,
fmt.Sprintf("%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s?access_token=%s",
config.ServerURL,
url.PathEscape(config.InternalRoomID),
txnId,
url.QueryEscape(config.AccessToken),
),
buffer,
)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
response, err := client.GetHTTPClient(nil).Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
}
return err
}
type Body struct {
MsgType string `json:"msgtype"`
Format string `json:"format"`
Body string `json:"body"`
FormattedBody string `json:"formatted_body"`
}
// buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
body, _ := json.Marshal(Body{
MsgType: "m.text",
Format: "org.matrix.custom.html",
Body: buildPlaintextMessageBody(endpoint, alert, result, resolved),
FormattedBody: buildHTMLMessageBody(endpoint, alert, result, resolved),
})
return body
}
// buildPlaintextMessageBody builds the message body in plaintext to include in request
func buildPlaintextMessageBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
var message, results string
if resolved {
message = fmt.Sprintf("An alert for `%s` has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
} else {
message = fmt.Sprintf("An alert for `%s` has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
}
for _, conditionResult := range result.ConditionResults {
var prefix string
if conditionResult.Success {
prefix = "✓"
} else {
prefix = "✕"
}
results += fmt.Sprintf("\n%s - %s", prefix, conditionResult.Condition)
}
var description string
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
description = "\n" + alertDescription
}
return fmt.Sprintf("%s%s\n%s", message, description, results)
}
// buildHTMLMessageBody builds the message body in HTML to include in request
func buildHTMLMessageBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
var message, results string
if resolved {
message = fmt.Sprintf("An alert for <code>%s</code> has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
} else {
message = fmt.Sprintf("An alert for <code>%s</code> has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
}
for _, conditionResult := range result.ConditionResults {
var prefix string
if conditionResult.Success {
prefix = "✅"
} else {
prefix = "❌"
}
results += fmt.Sprintf("<li>%s - <code>%s</code></li>", prefix, conditionResult.Condition)
}
var description string
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
description = fmt.Sprintf("\n<blockquote>%s</blockquote>", alertDescription)
}
return fmt.Sprintf("<h3>%s</h3>%s\n<h5>Condition results</h5><ul>%s</ul>", message, description, results)
}
// getConfigForGroup returns the appropriate configuration for a given group
func (provider *AlertProvider) getConfigForGroup(group string) MatrixProviderConfig {
if provider.Overrides != nil {
for _, override := range provider.Overrides {
if group == override.Group {
return override.MatrixProviderConfig
}
}
}
return provider.MatrixProviderConfig
}
func randStringBytes(n int) string {
// All the compatible characters to use in a transaction ID
const availableCharacterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, n)
rand.Seed(time.Now().UnixNano())
for i := range b {
b[i] = availableCharacterBytes[rand.Intn(len(availableCharacterBytes))]
}
return string(b)
}
// GetDefaultAlert returns the provider's default alert configuration
func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
return provider.DefaultAlert
}
+331
View File
@@ -0,0 +1,331 @@
package matrix
import (
"encoding/json"
"net/http"
"testing"
"github.com/TwiN/gatus/v4/alerting/alert"
"github.com/TwiN/gatus/v4/client"
"github.com/TwiN/gatus/v4/core"
"github.com/TwiN/gatus/v4/test"
)
func TestAlertProvider_IsValid(t *testing.T) {
invalidProvider := AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
AccessToken: "",
InternalRoomID: "",
},
}
if invalidProvider.IsValid() {
t.Error("provider shouldn't have been valid")
}
validProvider := AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
}
if !validProvider.IsValid() {
t.Error("provider should've been valid")
}
validProviderWithHomeserver := AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
}
if !validProviderWithHomeserver.IsValid() {
t.Error("provider with homeserver should've been valid")
}
}
func TestAlertProvider_IsValidWithOverride(t *testing.T) {
providerWithInvalidOverrideGroup := AlertProvider{
Overrides: []Override{
{
Group: "",
MatrixProviderConfig: MatrixProviderConfig{
AccessToken: "",
InternalRoomID: "",
},
},
},
}
if providerWithInvalidOverrideGroup.IsValid() {
t.Error("provider Group shouldn't have been valid")
}
providerWithInvalidOverrideTo := AlertProvider{
Overrides: []Override{
{
Group: "group",
MatrixProviderConfig: MatrixProviderConfig{
AccessToken: "",
InternalRoomID: "",
},
},
},
}
if providerWithInvalidOverrideTo.IsValid() {
t.Error("provider integration key shouldn't have been valid")
}
providerWithValidOverride := AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
Overrides: []Override{
{
Group: "group",
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
},
},
}
if !providerWithValidOverride.IsValid() {
t.Error("provider should've been valid")
}
}
func TestAlertProvider_Send(t *testing.T) {
defer client.InjectHTTPClient(nil)
firstDescription := "description-1"
secondDescription := "description-2"
scenarios := []struct {
Name string
Provider AlertProvider
Alert alert.Alert
Resolved bool
MockRoundTripper test.MockRoundTripper
ExpectedError bool
}{
{
Name: "triggered",
Provider: AlertProvider{},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false,
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
}),
ExpectedError: false,
},
{
Name: "triggered-error",
Provider: AlertProvider{},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false,
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
}),
ExpectedError: true,
},
{
Name: "resolved",
Provider: AlertProvider{},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true,
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
}),
ExpectedError: false,
},
{
Name: "resolved-error",
Provider: AlertProvider{},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true,
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
}),
ExpectedError: true,
},
}
for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) {
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
err := scenario.Provider.Send(
&core.Endpoint{Name: "endpoint-name"},
&scenario.Alert,
&core.Result{
ConditionResults: []*core.ConditionResult{
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
},
},
scenario.Resolved,
)
if scenario.ExpectedError && err == nil {
t.Error("expected error, got none")
}
if !scenario.ExpectedError && err != nil {
t.Error("expected no error, got", err.Error())
}
})
}
}
func TestAlertProvider_buildRequestBody(t *testing.T) {
firstDescription := "description-1"
secondDescription := "description-2"
scenarios := []struct {
Name string
Provider AlertProvider
Alert alert.Alert
Resolved bool
ExpectedBody string
}{
{
Name: "triggered",
Provider: AlertProvider{},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false,
ExpectedBody: "{\"msgtype\":\"m.text\",\"format\":\"org.matrix.custom.html\",\"body\":\"An alert for `endpoint-name` has been triggered due to having failed 3 time(s) in a row\\ndescription-1\\n\\n✕ - [CONNECTED] == true\\n✕ - [STATUS] == 200\",\"formatted_body\":\"\\u003ch3\\u003eAn alert for \\u003ccode\\u003eendpoint-name\\u003c/code\\u003e has been triggered due to having failed 3 time(s) in a row\\u003c/h3\\u003e\\n\\u003cblockquote\\u003edescription-1\\u003c/blockquote\\u003e\\n\\u003ch5\\u003eCondition results\\u003c/h5\\u003e\\u003cul\\u003e\\u003cli\\u003e❌ - \\u003ccode\\u003e[CONNECTED] == true\\u003c/code\\u003e\\u003c/li\\u003e\\u003cli\\u003e❌ - \\u003ccode\\u003e[STATUS] == 200\\u003c/code\\u003e\\u003c/li\\u003e\\u003c/ul\\u003e\"}",
},
{
Name: "resolved",
Provider: AlertProvider{},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true,
ExpectedBody: "{\"msgtype\":\"m.text\",\"format\":\"org.matrix.custom.html\",\"body\":\"An alert for `endpoint-name` has been resolved after passing successfully 5 time(s) in a row\\ndescription-2\\n\\n✓ - [CONNECTED] == true\\n✓ - [STATUS] == 200\",\"formatted_body\":\"\\u003ch3\\u003eAn alert for \\u003ccode\\u003eendpoint-name\\u003c/code\\u003e has been resolved after passing successfully 5 time(s) in a row\\u003c/h3\\u003e\\n\\u003cblockquote\\u003edescription-2\\u003c/blockquote\\u003e\\n\\u003ch5\\u003eCondition results\\u003c/h5\\u003e\\u003cul\\u003e\\u003cli\\u003e✅ - \\u003ccode\\u003e[CONNECTED] == true\\u003c/code\\u003e\\u003c/li\\u003e\\u003cli\\u003e✅ - \\u003ccode\\u003e[STATUS] == 200\\u003c/code\\u003e\\u003c/li\\u003e\\u003c/ul\\u003e\"}",
},
}
for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) {
body := scenario.Provider.buildRequestBody(
&core.Endpoint{Name: "endpoint-name"},
&scenario.Alert,
&core.Result{
ConditionResults: []*core.ConditionResult{
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
},
},
scenario.Resolved,
)
if string(body) != scenario.ExpectedBody {
t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
}
out := make(map[string]interface{})
if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error())
}
})
}
}
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
t.Error("expected default alert to be not nil")
}
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
t.Error("expected default alert to be nil")
}
}
func TestAlertProvider_getConfigForGroup(t *testing.T) {
tests := []struct {
Name string
Provider AlertProvider
InputGroup string
ExpectedOutput MatrixProviderConfig
}{
{
Name: "provider-no-override-specify-no-group-should-default",
Provider: AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
Overrides: nil,
},
InputGroup: "",
ExpectedOutput: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
},
{
Name: "provider-no-override-specify-group-should-default",
Provider: AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
Overrides: nil,
},
InputGroup: "group",
ExpectedOutput: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
},
{
Name: "provider-with-override-specify-no-group-should-default",
Provider: AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
Overrides: []Override{
{
Group: "group",
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example01.com",
AccessToken: "12",
InternalRoomID: "!a:example01.com",
},
},
},
},
InputGroup: "",
ExpectedOutput: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
},
{
Name: "provider-with-override-specify-group-should-override",
Provider: AlertProvider{
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
Overrides: []Override{
{
Group: "group",
MatrixProviderConfig: MatrixProviderConfig{
ServerURL: "https://example01.com",
AccessToken: "12",
InternalRoomID: "!a:example01.com",
},
},
},
},
InputGroup: "group",
ExpectedOutput: MatrixProviderConfig{
ServerURL: "https://example01.com",
AccessToken: "12",
InternalRoomID: "!a:example01.com",
},
},
}
for _, tt := range tests {
t.Run(tt.Name, func(t *testing.T) {
if got := tt.Provider.getConfigForGroup(tt.InputGroup); got != tt.ExpectedOutput {
t.Errorf("AlertProvider.getConfigForGroup() = %v, want %v", got, tt.ExpectedOutput)
}
})
}
}
+50 -31
View File
@@ -2,6 +2,7 @@ package mattermost
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -60,6 +61,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -67,9 +69,31 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return err return err
} }
type Body struct {
Text string `json:"text"`
Username string `json:"username"`
IconURL string `json:"icon_url"`
Attachments []Attachment `json:"attachments"`
}
type Attachment struct {
Title string `json:"title"`
Fallback string `json:"fallback"`
Text string `json:"text"`
Short bool `json:"short"`
Color string `json:"color"`
Fields []Field `json:"fields"`
}
type Field struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
// buildRequestBody builds the request body for the provider // buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string { func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
var message, color 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", endpoint.DisplayName(), alert.SuccessThreshold) message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
color = "#36A64F" color = "#36A64F"
@@ -77,7 +101,6 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold) message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
color = "#DD0000" color = "#DD0000"
} }
var results string
for _, conditionResult := range result.ConditionResults { for _, conditionResult := range result.ConditionResults {
var prefix string var prefix string
if conditionResult.Success { if conditionResult.Success {
@@ -85,38 +108,34 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
} else { } else {
prefix = ":x:" prefix = ":x:"
} }
results += fmt.Sprintf("%s - `%s`\\n", prefix, conditionResult.Condition) results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
} }
var description string var description string
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 { if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
description = ":\\n> " + alertDescription description = ":\n> " + alertDescription
} }
return fmt.Sprintf(`{ body, _ := json.Marshal(Body{
"text": "", Text: "",
"username": "gatus", Username: "gatus",
"icon_url": "https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png", IconURL: "https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png",
"attachments": [ Attachments: []Attachment{
{ {
"title": ":rescue_worker_helmet: Gatus", Title: ":helmet_with_white_cross: Gatus",
"fallback": "Gatus - %s", Fallback: "Gatus - " + message,
"text": "%s%s", Text: message + description,
"short": false, Short: false,
"color": "%s", Color: color,
"fields": [ Fields: []Field{
{ {
"title": "URL", Title: "Condition results",
"value": "%s", Value: results,
"short": false Short: false,
}, },
{ },
"title": "Condition results", },
"value": "%s", },
"short": false })
} return body
]
}
]
}`, message, message, description, color, endpoint.URL, results)
} }
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group // getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
@@ -155,14 +155,14 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Provider: AlertProvider{}, Provider: AlertProvider{},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false, Resolved: false,
ExpectedBody: "{\n \"text\": \"\",\n \"username\": \"gatus\",\n \"icon_url\": \"https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png\",\n \"attachments\": [\n {\n \"title\": \":rescue_worker_helmet: Gatus\",\n \"fallback\": \"Gatus - An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row\",\n \"text\": \"An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"short\": false,\n \"color\": \"#DD0000\",\n \"fields\": [\n {\n \"title\": \"URL\",\n \"value\": \"\",\n \"short\": false\n },\n {\n \"title\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"text\":\"\",\"username\":\"gatus\",\"icon_url\":\"https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png\",\"attachments\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"fallback\":\"Gatus - An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row\",\"text\":\"An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row:\\n\\u003e description-1\",\"short\":false,\"color\":\"#DD0000\",\"fields\":[{\"title\":\"Condition results\",\"value\":\":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\"short\":false}]}]}",
}, },
{ {
Name: "resolved", Name: "resolved",
Provider: AlertProvider{}, Provider: AlertProvider{},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true, Resolved: true,
ExpectedBody: "{\n \"text\": \"\",\n \"username\": \"gatus\",\n \"icon_url\": \"https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png\",\n \"attachments\": [\n {\n \"title\": \":rescue_worker_helmet: Gatus\",\n \"fallback\": \"Gatus - An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row\",\n \"text\": \"An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"short\": false,\n \"color\": \"#36A64F\",\n \"fields\": [\n {\n \"title\": \"URL\",\n \"value\": \"\",\n \"short\": false\n },\n {\n \"title\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"text\":\"\",\"username\":\"gatus\",\"icon_url\":\"https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png\",\"attachments\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"fallback\":\"Gatus - An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row\",\"text\":\"An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row:\\n\\u003e description-2\",\"short\":false,\"color\":\"#36A64F\",\"fields\":[{\"title\":\"Condition results\",\"value\":\":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\"short\":false}]}]}",
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
@@ -178,11 +178,11 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
}, },
scenario.Resolved, scenario.Resolved,
) )
if body != scenario.ExpectedBody { if string(body) != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body) t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error()) t.Error("expected body to be valid JSON, got error:", err.Error())
} }
}) })
+16 -7
View File
@@ -2,6 +2,7 @@ package messagebird
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -33,7 +34,7 @@ func (provider *AlertProvider) IsValid() bool {
// Send an alert using the provider // Send an alert using the provider
// Reference doc for messagebird: https://developers.messagebird.com/api/sms-messaging/#send-outbound-sms // Reference doc for messagebird: https://developers.messagebird.com/api/sms-messaging/#send-outbound-sms
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved))) buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
request, err := http.NewRequest(http.MethodPost, restAPIURL, buffer) request, err := http.NewRequest(http.MethodPost, restAPIURL, buffer)
if err != nil { if err != nil {
return err return err
@@ -44,6 +45,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -51,19 +53,26 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return err return err
} }
type Body struct {
Originator string `json:"originator"`
Recipients string `json:"recipients"`
Body string `json:"body"`
}
// buildRequestBody builds the request body for the provider // buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string { func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
var message string var message string
if resolved { if resolved {
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.DisplayName(), alert.GetDescription()) message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
} else { } else {
message = fmt.Sprintf("TRIGGERED: %s - %s", endpoint.DisplayName(), alert.GetDescription()) message = fmt.Sprintf("TRIGGERED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
} }
return fmt.Sprintf(`{ body, _ := json.Marshal(Body{
"originator": "%s", Originator: provider.Originator,
"recipients": "%s", Recipients: provider.Recipients,
"body": "%s" Body: message,
}`, provider.Originator, provider.Recipients, message) })
return body
} }
// GetDefaultAlert returns the provider's default alert configuration // GetDefaultAlert returns the provider's default alert configuration
@@ -118,14 +118,14 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Provider: AlertProvider{AccessKey: "1", Originator: "2", Recipients: "3"}, Provider: AlertProvider{AccessKey: "1", Originator: "2", Recipients: "3"},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false, Resolved: false,
ExpectedBody: "{\n \"originator\": \"2\",\n \"recipients\": \"3\",\n \"body\": \"TRIGGERED: endpoint-name - description-1\"\n}", ExpectedBody: "{\"originator\":\"2\",\"recipients\":\"3\",\"body\":\"TRIGGERED: endpoint-name - description-1\"}",
}, },
{ {
Name: "resolved", Name: "resolved",
Provider: AlertProvider{AccessKey: "4", Originator: "5", Recipients: "6"}, Provider: AlertProvider{AccessKey: "4", Originator: "5", Recipients: "6"},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true, Resolved: true,
ExpectedBody: "{\n \"originator\": \"5\",\n \"recipients\": \"6\",\n \"body\": \"RESOLVED: endpoint-name - description-2\"\n}", ExpectedBody: "{\"originator\":\"5\",\"recipients\":\"6\",\"body\":\"RESOLVED: endpoint-name - description-2\"}",
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
@@ -141,8 +141,8 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
}, },
scenario.Resolved, scenario.Resolved,
) )
if body != scenario.ExpectedBody { if string(body) != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body) t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal([]byte(body), &out); err != nil {
+95
View File
@@ -0,0 +1,95 @@
package ntfy
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/TwiN/gatus/v4/alerting/alert"
"github.com/TwiN/gatus/v4/client"
"github.com/TwiN/gatus/v4/core"
)
const (
DefaultURL = "https://ntfy.sh"
DefaultPriority = 3
)
// AlertProvider is the configuration necessary for sending an alert using Slack
type AlertProvider struct {
Topic string `yaml:"topic"`
URL string `yaml:"url,omitempty"` // Defaults to DefaultURL
Priority int `yaml:"priority,omitempty"` // Defaults to DefaultPriority
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
}
// IsValid returns whether the provider's configuration is valid
func (provider *AlertProvider) IsValid() bool {
if len(provider.URL) == 0 {
provider.URL = DefaultURL
}
if provider.Priority == 0 {
provider.Priority = DefaultPriority
}
return len(provider.URL) > 0 && len(provider.Topic) > 0 && provider.Priority > 0 && provider.Priority < 6
}
// Send an alert using the provider
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
request, err := http.NewRequest(http.MethodPost, provider.URL, buffer)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
response, err := client.GetHTTPClient(nil).Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
}
return err
}
type Body struct {
Topic string `json:"topic"`
Title string `json:"title"`
Message string `json:"message"`
Tags []string `json:"tags"`
Priority int `json:"priority"`
}
// buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
var message, tag string
if len(alert.GetDescription()) > 0 {
message = endpoint.DisplayName() + " - " + alert.GetDescription()
} else {
message = endpoint.DisplayName()
}
if resolved {
tag = "white_check_mark"
} else {
tag = "x"
}
body, _ := json.Marshal(Body{
Topic: provider.Topic,
Title: "Gatus",
Message: message,
Tags: []string{tag},
Priority: provider.Priority,
})
return body
}
// GetDefaultAlert returns the provider's default alert configuration
func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
return provider.DefaultAlert
}
+104
View File
@@ -0,0 +1,104 @@
package ntfy
import (
"encoding/json"
"testing"
"github.com/TwiN/gatus/v4/alerting/alert"
"github.com/TwiN/gatus/v4/core"
)
func TestAlertDefaultProvider_IsValid(t *testing.T) {
scenarios := []struct {
name string
provider AlertProvider
expected bool
}{
{
name: "valid",
provider: AlertProvider{URL: "https://ntfy.sh", Topic: "example", Priority: 1},
expected: true,
},
{
name: "no-url-should-use-default-value",
provider: AlertProvider{Topic: "example", Priority: 1},
expected: true,
},
{
name: "invalid-topic",
provider: AlertProvider{URL: "https://ntfy.sh", Topic: "", Priority: 1},
expected: false,
},
{
name: "invalid-priority-too-high",
provider: AlertProvider{URL: "https://ntfy.sh", Topic: "example", Priority: 6},
expected: false,
},
{
name: "invalid-priority-too-low",
provider: AlertProvider{URL: "https://ntfy.sh", Topic: "example", Priority: -1},
expected: false,
},
{
name: "no-priority-should-use-default-value",
provider: AlertProvider{URL: "https://ntfy.sh", Topic: "example"},
expected: true,
},
}
for _, scenario := range scenarios {
t.Run(scenario.name, func(t *testing.T) {
if scenario.provider.IsValid() != scenario.expected {
t.Errorf("expected %t, got %t", scenario.expected, scenario.provider.IsValid())
}
})
}
}
func TestAlertProvider_buildRequestBody(t *testing.T) {
firstDescription := "description-1"
secondDescription := "description-2"
scenarios := []struct {
Name string
Provider AlertProvider
Alert alert.Alert
Resolved bool
ExpectedBody string
}{
{
Name: "triggered",
Provider: AlertProvider{URL: "https://ntfy.sh", Topic: "example", Priority: 1},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false,
ExpectedBody: "{\"topic\":\"example\",\"title\":\"Gatus\",\"message\":\"endpoint-name - description-1\",\"tags\":[\"x\"],\"priority\":1}",
},
{
Name: "resolved",
Provider: AlertProvider{URL: "https://ntfy.sh", Topic: "example", Priority: 2},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true,
ExpectedBody: "{\"topic\":\"example\",\"title\":\"Gatus\",\"message\":\"endpoint-name - description-2\",\"tags\":[\"white_check_mark\"],\"priority\":2}",
},
}
for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) {
body := scenario.Provider.buildRequestBody(
&core.Endpoint{Name: "endpoint-name"},
&scenario.Alert,
&core.Result{
ConditionResults: []*core.ConditionResult{
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
},
},
scenario.Resolved,
)
if string(body) != scenario.ExpectedBody {
t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
}
out := make(map[string]interface{})
if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error())
}
})
}
}
+12 -13
View File
@@ -83,37 +83,36 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
func (provider *AlertProvider) createAlert(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) createAlert(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
payload := provider.buildCreateRequestBody(endpoint, alert, result, resolved) payload := provider.buildCreateRequestBody(endpoint, alert, result, resolved)
_, err := provider.sendRequest(restAPI, http.MethodPost, payload) return provider.sendRequest(restAPI, http.MethodPost, payload)
return err
} }
func (provider *AlertProvider) closeAlert(endpoint *core.Endpoint, alert *alert.Alert) error { func (provider *AlertProvider) closeAlert(endpoint *core.Endpoint, alert *alert.Alert) error {
payload := provider.buildCloseRequestBody(endpoint, alert) payload := provider.buildCloseRequestBody(endpoint, alert)
url := restAPI + "/" + provider.alias(buildKey(endpoint)) + "/close?identifierType=alias" url := restAPI + "/" + provider.alias(buildKey(endpoint)) + "/close?identifierType=alias"
_, err := provider.sendRequest(url, http.MethodPost, payload) return provider.sendRequest(url, http.MethodPost, payload)
return err
} }
func (provider *AlertProvider) sendRequest(url, method string, payload interface{}) (*http.Response, error) { func (provider *AlertProvider) sendRequest(url, method string, payload interface{}) error {
body, err := json.Marshal(payload) body, err := json.Marshal(payload)
if err != nil { if err != nil {
return nil, fmt.Errorf("fail to build alert payload: %v", payload) return fmt.Errorf("error build alert with payload %v: %w", payload, err)
} }
request, err := http.NewRequest(method, url, bytes.NewBuffer(body)) request, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil { if err != nil {
return nil, err return err
} }
request.Header.Set("Content-Type", "application/json") request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", "GenieKey "+provider.APIKey) request.Header.Set("Authorization", "GenieKey "+provider.APIKey)
res, err := client.GetHTTPClient(nil).Do(request) response, err := client.GetHTTPClient(nil).Do(request)
if err != nil { if err != nil {
return nil, err return err
} }
if res.StatusCode > 399 { defer response.Body.Close()
rBody, _ := io.ReadAll(res.Body) if response.StatusCode > 399 {
return nil, fmt.Errorf("call to provider alert returned status code %d: %s", res.StatusCode, string(rBody)) rBody, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(rBody))
} }
return res, nil return nil
} }
func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) alertCreateRequest { func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) alertCreateRequest {
+27 -12
View File
@@ -53,7 +53,7 @@ func (provider *AlertProvider) IsValid() bool {
// //
// 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) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved))) buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
request, err := http.NewRequest(http.MethodPost, restAPIURL, buffer) request, err := http.NewRequest(http.MethodPost, restAPIURL, buffer)
if err != nil { if err != nil {
return err return err
@@ -63,6 +63,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -86,8 +87,21 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return nil return nil
} }
type Body struct {
RoutingKey string `json:"routing_key"`
DedupKey string `json:"dedup_key"`
EventAction string `json:"event_action"`
Payload Payload `json:"payload"`
}
type Payload struct {
Summary string `json:"summary"`
Source string `json:"source"`
Severity string `json:"severity"`
}
// buildRequestBody builds the request body for the provider // buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string { func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
var message, eventAction, resolveKey string var message, eventAction, resolveKey string
if resolved { if resolved {
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.DisplayName(), alert.GetDescription()) message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.DisplayName(), alert.GetDescription())
@@ -98,16 +112,17 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
eventAction = "trigger" eventAction = "trigger"
resolveKey = "" resolveKey = ""
} }
return fmt.Sprintf(`{ body, _ := json.Marshal(Body{
"routing_key": "%s", RoutingKey: provider.getIntegrationKeyForGroup(endpoint.Group),
"dedup_key": "%s", DedupKey: resolveKey,
"event_action": "%s", EventAction: eventAction,
"payload": { Payload: Payload{
"summary": "%s", Summary: message,
"source": "%s", Source: "Gatus",
"severity": "critical" Severity: "critical",
} },
}`, provider.getIntegrationKeyForGroup(endpoint.Group), resolveKey, eventAction, message, endpoint.Name) })
return body
} }
// getIntegrationKeyForGroup returns the appropriate pagerduty integration key for a given group // getIntegrationKeyForGroup returns the appropriate pagerduty integration key for a given group
@@ -149,24 +149,24 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Provider: AlertProvider{IntegrationKey: "00000000000000000000000000000000"}, Provider: AlertProvider{IntegrationKey: "00000000000000000000000000000000"},
Alert: alert.Alert{Description: &description}, Alert: alert.Alert{Description: &description},
Resolved: false, Resolved: false,
ExpectedBody: "{\n \"routing_key\": \"00000000000000000000000000000000\",\n \"dedup_key\": \"\",\n \"event_action\": \"trigger\",\n \"payload\": {\n \"summary\": \"TRIGGERED: - test\",\n \"source\": \"\",\n \"severity\": \"critical\"\n }\n}", ExpectedBody: "{\"routing_key\":\"00000000000000000000000000000000\",\"dedup_key\":\"\",\"event_action\":\"trigger\",\"payload\":{\"summary\":\"TRIGGERED: endpoint-name - test\",\"source\":\"Gatus\",\"severity\":\"critical\"}}",
}, },
{ {
Name: "resolved", Name: "resolved",
Provider: AlertProvider{IntegrationKey: "00000000000000000000000000000000"}, Provider: AlertProvider{IntegrationKey: "00000000000000000000000000000000"},
Alert: alert.Alert{Description: &description, ResolveKey: "key"}, Alert: alert.Alert{Description: &description, ResolveKey: "key"},
Resolved: true, Resolved: true,
ExpectedBody: "{\n \"routing_key\": \"00000000000000000000000000000000\",\n \"dedup_key\": \"key\",\n \"event_action\": \"resolve\",\n \"payload\": {\n \"summary\": \"RESOLVED: - test\",\n \"source\": \"\",\n \"severity\": \"critical\"\n }\n}", ExpectedBody: "{\"routing_key\":\"00000000000000000000000000000000\",\"dedup_key\":\"key\",\"event_action\":\"resolve\",\"payload\":{\"summary\":\"RESOLVED: endpoint-name - test\",\"source\":\"Gatus\",\"severity\":\"critical\"}}",
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) { t.Run(scenario.Name, func(t *testing.T) {
body := scenario.Provider.buildRequestBody(&core.Endpoint{}, &scenario.Alert, &core.Result{}, scenario.Resolved) body := scenario.Provider.buildRequestBody(&core.Endpoint{Name: "endpoint-name"}, &scenario.Alert, &core.Result{}, scenario.Resolved)
if body != scenario.ExpectedBody { if string(body) != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body) t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error()) t.Error("expected body to be valid JSON, got error:", err.Error())
} }
}) })
+4
View File
@@ -6,8 +6,10 @@ import (
"github.com/TwiN/gatus/v4/alerting/provider/discord" "github.com/TwiN/gatus/v4/alerting/provider/discord"
"github.com/TwiN/gatus/v4/alerting/provider/email" "github.com/TwiN/gatus/v4/alerting/provider/email"
"github.com/TwiN/gatus/v4/alerting/provider/googlechat" "github.com/TwiN/gatus/v4/alerting/provider/googlechat"
"github.com/TwiN/gatus/v4/alerting/provider/matrix"
"github.com/TwiN/gatus/v4/alerting/provider/mattermost" "github.com/TwiN/gatus/v4/alerting/provider/mattermost"
"github.com/TwiN/gatus/v4/alerting/provider/messagebird" "github.com/TwiN/gatus/v4/alerting/provider/messagebird"
"github.com/TwiN/gatus/v4/alerting/provider/ntfy"
"github.com/TwiN/gatus/v4/alerting/provider/opsgenie" "github.com/TwiN/gatus/v4/alerting/provider/opsgenie"
"github.com/TwiN/gatus/v4/alerting/provider/pagerduty" "github.com/TwiN/gatus/v4/alerting/provider/pagerduty"
"github.com/TwiN/gatus/v4/alerting/provider/slack" "github.com/TwiN/gatus/v4/alerting/provider/slack"
@@ -57,8 +59,10 @@ var (
_ AlertProvider = (*discord.AlertProvider)(nil) _ AlertProvider = (*discord.AlertProvider)(nil)
_ AlertProvider = (*email.AlertProvider)(nil) _ AlertProvider = (*email.AlertProvider)(nil)
_ AlertProvider = (*googlechat.AlertProvider)(nil) _ AlertProvider = (*googlechat.AlertProvider)(nil)
_ AlertProvider = (*matrix.AlertProvider)(nil)
_ AlertProvider = (*mattermost.AlertProvider)(nil) _ AlertProvider = (*mattermost.AlertProvider)(nil)
_ AlertProvider = (*messagebird.AlertProvider)(nil) _ AlertProvider = (*messagebird.AlertProvider)(nil)
_ AlertProvider = (*ntfy.AlertProvider)(nil)
_ AlertProvider = (*opsgenie.AlertProvider)(nil) _ AlertProvider = (*opsgenie.AlertProvider)(nil)
_ AlertProvider = (*pagerduty.AlertProvider)(nil) _ AlertProvider = (*pagerduty.AlertProvider)(nil)
_ AlertProvider = (*slack.AlertProvider)(nil) _ AlertProvider = (*slack.AlertProvider)(nil)
+44 -22
View File
@@ -2,6 +2,7 @@ package slack
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -42,7 +43,7 @@ func (provider *AlertProvider) IsValid() bool {
// Send an alert using the provider // Send an alert using the provider
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved))) buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
request, err := http.NewRequest(http.MethodPost, provider.getWebhookURLForGroup(endpoint.Group), buffer) request, err := http.NewRequest(http.MethodPost, provider.getWebhookURLForGroup(endpoint.Group), buffer)
if err != nil { if err != nil {
return err return err
@@ -52,6 +53,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -59,8 +61,27 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return err return err
} }
type Body struct {
Text string `json:"text"`
Attachments []Attachment `json:"attachments"`
}
type Attachment struct {
Title string `json:"title"`
Text string `json:"text"`
Short bool `json:"short"`
Color string `json:"color"`
Fields []Field `json:"fields"`
}
type Field struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
// buildRequestBody builds the request body for the provider // buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string { func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
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", endpoint.DisplayName(), alert.SuccessThreshold) message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
@@ -76,30 +97,31 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
} else { } else {
prefix = ":x:" prefix = ":x:"
} }
results += fmt.Sprintf("%s - `%s`\\n", prefix, conditionResult.Condition) results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
} }
var description string var description string
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 { if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
description = ":\\n> " + alertDescription description = ":\n> " + alertDescription
} }
return fmt.Sprintf(`{ body, _ := json.Marshal(Body{
"text": "", Text: "",
"attachments": [ Attachments: []Attachment{
{ {
"title": ":helmet_with_white_cross: Gatus", Title: ":helmet_with_white_cross: Gatus",
"text": "%s%s", Text: message + description,
"short": false, Short: false,
"color": "%s", Color: color,
"fields": [ Fields: []Field{
{ {
"title": "Condition results", Title: "Condition results",
"value": "%s", Value: results,
"short": false Short: false,
} },
] },
} },
] },
}`, message, description, color, results) })
return body
} }
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group // getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
+9 -8
View File
@@ -20,8 +20,8 @@ func TestAlertDefaultProvider_IsValid(t *testing.T) {
if !validProvider.IsValid() { if !validProvider.IsValid() {
t.Error("provider should've been valid") t.Error("provider should've been valid")
} }
} }
func TestAlertProvider_IsValidWithOverride(t *testing.T) { func TestAlertProvider_IsValidWithOverride(t *testing.T) {
providerWithInvalidOverrideGroup := AlertProvider{ providerWithInvalidOverrideGroup := AlertProvider{
Overrides: []Override{ Overrides: []Override{
@@ -58,6 +58,7 @@ func TestAlertProvider_IsValidWithOverride(t *testing.T) {
t.Error("provider should've been valid") t.Error("provider should've been valid")
} }
} }
func TestAlertProvider_Send(t *testing.T) { func TestAlertProvider_Send(t *testing.T) {
defer client.InjectHTTPClient(nil) defer client.InjectHTTPClient(nil)
firstDescription := "description-1" firstDescription := "description-1"
@@ -152,7 +153,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Endpoint: core.Endpoint{Name: "name"}, Endpoint: core.Endpoint{Name: "name"},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false, Resolved: false,
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"short\": false,\n \"color\": \"#DD0000\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"text\":\"\",\"attachments\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"text\":\"An alert for *name* has been triggered due to having failed 3 time(s) in a row:\\n\\u003e description-1\",\"short\":false,\"color\":\"#DD0000\",\"fields\":[{\"title\":\"Condition results\",\"value\":\":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\"short\":false}]}]}",
}, },
{ {
Name: "triggered-with-group", Name: "triggered-with-group",
@@ -160,7 +161,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Endpoint: core.Endpoint{Name: "name", Group: "group"}, Endpoint: core.Endpoint{Name: "name", Group: "group"},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false, Resolved: false,
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *group/name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"short\": false,\n \"color\": \"#DD0000\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"text\":\"\",\"attachments\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"text\":\"An alert for *group/name* has been triggered due to having failed 3 time(s) in a row:\\n\\u003e description-1\",\"short\":false,\"color\":\"#DD0000\",\"fields\":[{\"title\":\"Condition results\",\"value\":\":x: - `[CONNECTED] == true`\\n:x: - `[STATUS] == 200`\\n\",\"short\":false}]}]}",
}, },
{ {
Name: "resolved", Name: "resolved",
@@ -168,7 +169,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Endpoint: core.Endpoint{Name: "name"}, Endpoint: core.Endpoint{Name: "name"},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true, Resolved: true,
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"short\": false,\n \"color\": \"#36A64F\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"text\":\"\",\"attachments\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"text\":\"An alert for *name* has been resolved after passing successfully 5 time(s) in a row:\\n\\u003e description-2\",\"short\":false,\"color\":\"#36A64F\",\"fields\":[{\"title\":\"Condition results\",\"value\":\":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\"short\":false}]}]}",
}, },
{ {
Name: "resolved-with-group", Name: "resolved-with-group",
@@ -176,7 +177,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Endpoint: core.Endpoint{Name: "name", Group: "group"}, Endpoint: core.Endpoint{Name: "name", Group: "group"},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true, Resolved: true,
ExpectedBody: "{\n \"text\": \"\",\n \"attachments\": [\n {\n \"title\": \":helmet_with_white_cross: Gatus\",\n \"text\": \"An alert for *group/name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"short\": false,\n \"color\": \"#36A64F\",\n \"fields\": [\n {\n \"title\": \"Condition results\",\n \"value\": \":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\n \"short\": false\n }\n ]\n }\n ]\n}", ExpectedBody: "{\"text\":\"\",\"attachments\":[{\"title\":\":helmet_with_white_cross: Gatus\",\"text\":\"An alert for *group/name* has been resolved after passing successfully 5 time(s) in a row:\\n\\u003e description-2\",\"short\":false,\"color\":\"#36A64F\",\"fields\":[{\"title\":\"Condition results\",\"value\":\":white_check_mark: - `[CONNECTED] == true`\\n:white_check_mark: - `[STATUS] == 200`\\n\",\"short\":false}]}]}",
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
@@ -192,11 +193,11 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
}, },
scenario.Resolved, scenario.Resolved,
) )
if body != scenario.ExpectedBody { if string(body) != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body) t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error()) t.Error("expected body to be valid JSON, got error:", err.Error())
} }
}) })
+33 -20
View File
@@ -2,6 +2,7 @@ package teams
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -44,7 +45,7 @@ func (provider *AlertProvider) IsValid() bool {
// Send an alert using the provider // Send an alert using the provider
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved))) buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
request, err := http.NewRequest(http.MethodPost, provider.getWebhookURLForGroup(endpoint.Group), buffer) request, err := http.NewRequest(http.MethodPost, provider.getWebhookURLForGroup(endpoint.Group), buffer)
if err != nil { if err != nil {
return err return err
@@ -54,6 +55,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -61,8 +63,22 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return err return err
} }
type Body struct {
Type string `json:"@type"`
Context string `json:"@context"`
ThemeColor string `json:"themeColor"`
Title string `json:"title"`
Text string `json:"text"`
Sections []Section `json:"sections"`
}
type Section struct {
ActivityTitle string `json:"activityTitle"`
Text string `json:"text"`
}
// buildRequestBody builds the request body for the provider // buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string { func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
var message, color string var message, color string
if resolved { if resolved {
message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold) message = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
@@ -83,25 +99,22 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
} }
var description string var description string
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 { if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
description = ":\\n> " + alertDescription description = ": " + alertDescription
} }
return fmt.Sprintf(`{ body, _ := json.Marshal(Body{
"@type": "MessageCard", Type: "MessageCard",
"@context": "http://schema.org/extensions", Context: "http://schema.org/extensions",
"themeColor": "%s", ThemeColor: color,
"title": "&#x1F6A8; Gatus", Title: "&#x1F6A8; Gatus",
"text": "%s%s", Text: message + description,
"sections": [ Sections: []Section{
{ {
"activityTitle": "URL", ActivityTitle: "Condition results",
"text": "%s" Text: results,
}, },
{ },
"activityTitle": "Condition results", })
"text": "%s" return body
}
]
}`, color, message, description, endpoint.URL, results)
} }
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group // getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
+5 -5
View File
@@ -151,14 +151,14 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Provider: AlertProvider{}, Provider: AlertProvider{},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false, Resolved: false,
ExpectedBody: "{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"#DD0000\",\n \"title\": \"&#x1F6A8; Gatus\",\n \"text\": \"An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row:\\n> description-1\",\n \"sections\": [\n {\n \"activityTitle\": \"URL\",\n \"text\": \"\"\n },\n {\n \"activityTitle\": \"Condition results\",\n \"text\": \"&#x274C; - `[CONNECTED] == true`<br/>&#x274C; - `[STATUS] == 200`<br/>\"\n }\n ]\n}", ExpectedBody: "{\"@type\":\"MessageCard\",\"@context\":\"http://schema.org/extensions\",\"themeColor\":\"#DD0000\",\"title\":\"\\u0026#x1F6A8; Gatus\",\"text\":\"An alert for *endpoint-name* has been triggered due to having failed 3 time(s) in a row: description-1\",\"sections\":[{\"activityTitle\":\"Condition results\",\"text\":\"\\u0026#x274C; - `[CONNECTED] == true`\\u003cbr/\\u003e\\u0026#x274C; - `[STATUS] == 200`\\u003cbr/\\u003e\"}]}",
}, },
{ {
Name: "resolved", Name: "resolved",
Provider: AlertProvider{}, Provider: AlertProvider{},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true, Resolved: true,
ExpectedBody: "{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"#36A64F\",\n \"title\": \"&#x1F6A8; Gatus\",\n \"text\": \"An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row:\\n> description-2\",\n \"sections\": [\n {\n \"activityTitle\": \"URL\",\n \"text\": \"\"\n },\n {\n \"activityTitle\": \"Condition results\",\n \"text\": \"&#x2705; - `[CONNECTED] == true`<br/>&#x2705; - `[STATUS] == 200`<br/>\"\n }\n ]\n}", ExpectedBody: "{\"@type\":\"MessageCard\",\"@context\":\"http://schema.org/extensions\",\"themeColor\":\"#36A64F\",\"title\":\"\\u0026#x1F6A8; Gatus\",\"text\":\"An alert for *endpoint-name* has been resolved after passing successfully 5 time(s) in a row: description-2\",\"sections\":[{\"activityTitle\":\"Condition results\",\"text\":\"\\u0026#x2705; - `[CONNECTED] == true`\\u003cbr/\\u003e\\u0026#x2705; - `[STATUS] == 200`\\u003cbr/\\u003e\"}]}",
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
@@ -174,11 +174,11 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
}, },
scenario.Resolved, scenario.Resolved,
) )
if body != scenario.ExpectedBody { if string(body) != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body) t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error()) t.Error("expected body to be valid JSON, got error:", err.Error())
} }
}) })
+28 -9
View File
@@ -2,6 +2,7 @@ package telegram
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -19,18 +20,24 @@ type AlertProvider struct {
ID string `yaml:"id"` ID string `yaml:"id"`
APIURL string `yaml:"api-url"` APIURL string `yaml:"api-url"`
// ClientConfig is the configuration of the client used to communicate with the provider's target
ClientConfig *client.Config `yaml:"client,omitempty"`
// DefaultAlert is the default alert configuration to use for endpoints 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,omitempty"` DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
} }
// IsValid returns whether the provider's configuration is valid // IsValid returns whether the provider's configuration is valid
func (provider *AlertProvider) IsValid() bool { func (provider *AlertProvider) IsValid() bool {
if provider.ClientConfig == nil {
provider.ClientConfig = client.GetDefaultConfig()
}
return len(provider.Token) > 0 && len(provider.ID) > 0 return len(provider.Token) > 0 && len(provider.ID) > 0
} }
// Send an alert using the provider // Send an alert using the provider
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved))) buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
apiURL := provider.APIURL apiURL := provider.APIURL
if apiURL == "" { if apiURL == "" {
apiURL = defaultAPIURL apiURL = defaultAPIURL
@@ -40,10 +47,11 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return err return err
} }
request.Header.Set("Content-Type", "application/json") request.Header.Set("Content-Type", "application/json")
response, err := client.GetHTTPClient(nil).Do(request) response, err := client.GetHTTPClient(provider.ClientConfig).Do(request)
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
@@ -51,13 +59,19 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
return err return err
} }
type Body struct {
ChatID string `json:"chat_id"`
Text string `json:"text"`
ParseMode string `json:"parse_mode"`
}
// buildRequestBody builds the request body for the provider // buildRequestBody builds the request body for the provider
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string { func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
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— ", endpoint.DisplayName(), alert.FailureThreshold) message = fmt.Sprintf("An alert for *%s* has been resolved:\n—\n _healthcheck passing successfully %d time(s) in a row_\n— ", endpoint.DisplayName(), alert.FailureThreshold)
} else { } else {
message = fmt.Sprintf("An alert for *%s* has been triggered:\\n—\\n _healthcheck failed %d time(s) in a row_\\n— ", endpoint.DisplayName(), alert.FailureThreshold) message = fmt.Sprintf("An alert for *%s* has been triggered:\n—\n _healthcheck failed %d time(s) in a row_\n— ", endpoint.DisplayName(), alert.FailureThreshold)
} }
for _, conditionResult := range result.ConditionResults { for _, conditionResult := range result.ConditionResults {
var prefix string var prefix string
@@ -66,15 +80,20 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
} else { } else {
prefix = "❌" prefix = "❌"
} }
results += fmt.Sprintf("%s - `%s`\\n", prefix, conditionResult.Condition) results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
} }
var text string var text string
if len(alert.GetDescription()) > 0 { if len(alert.GetDescription()) > 0 {
text = fmt.Sprintf("⛑ *Gatus* \\n%s \\n*Description* \\n_%s_ \\n\\n*Condition results*\\n%s", message, alert.GetDescription(), results) text = fmt.Sprintf("⛑ *Gatus* \n%s \n*Description* \n_%s_ \n\n*Condition results*\n%s", message, alert.GetDescription(), results)
} else { } else {
text = fmt.Sprintf("⛑ *Gatus* \\n%s \\n*Condition results*\\n%s", message, results) text = fmt.Sprintf("⛑ *Gatus* \n%s \n*Condition results*\n%s", message, results)
} }
return fmt.Sprintf(`{"chat_id": "%s", "text": "%s", "parse_mode": "MARKDOWN"}`, provider.ID, text) body, _ := json.Marshal(Body{
ChatID: provider.ID,
Text: text,
ParseMode: "MARKDOWN",
})
return body
} }
// GetDefaultAlert returns the provider's default alert configuration // GetDefaultAlert returns the provider's default alert configuration
+23 -13
View File
@@ -12,14 +12,24 @@ import (
) )
func TestAlertProvider_IsValid(t *testing.T) { func TestAlertProvider_IsValid(t *testing.T) {
invalidProvider := AlertProvider{Token: "", ID: ""} t.Run("invalid-provider", func(t *testing.T) {
if invalidProvider.IsValid() { invalidProvider := AlertProvider{Token: "", ID: ""}
t.Error("provider shouldn't have been valid") if invalidProvider.IsValid() {
} t.Error("provider shouldn't have been valid")
validProvider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "12345678"} }
if !validProvider.IsValid() { })
t.Error("provider should've been valid") t.Run("valid-provider", func(t *testing.T) {
} validProvider := AlertProvider{Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", ID: "12345678"}
if validProvider.ClientConfig != nil {
t.Error("provider client config should have been nil prior to IsValid() being executed")
}
if !validProvider.IsValid() {
t.Error("provider should've been valid")
}
if validProvider.ClientConfig == nil {
t.Error("provider client config should have been set after IsValid() was executed")
}
})
} }
func TestAlertProvider_Send(t *testing.T) { func TestAlertProvider_Send(t *testing.T) {
@@ -114,14 +124,14 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
Provider: AlertProvider{ID: "123"}, Provider: AlertProvider{ID: "123"},
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: false, Resolved: false,
ExpectedBody: "{\"chat_id\": \"123\", \"text\": \"⛑ *Gatus* \\nAn alert for *endpoint-name* has been triggered:\\n—\\n _healthcheck failed 3 time(s) in a row_\\n— \\n*Description* \\n_description-1_ \\n\\n*Condition results*\\n❌ - `[CONNECTED] == true`\\n❌ - `[STATUS] == 200`\\n\", \"parse_mode\": \"MARKDOWN\"}", ExpectedBody: "{\"chat_id\":\"123\",\"text\":\"⛑ *Gatus* \\nAn alert for *endpoint-name* has been triggered:\\n—\\n _healthcheck failed 3 time(s) in a row_\\n— \\n*Description* \\n_description-1_ \\n\\n*Condition results*\\n❌ - `[CONNECTED] == true`\\n❌ - `[STATUS] == 200`\\n\",\"parse_mode\":\"MARKDOWN\"}",
}, },
{ {
Name: "resolved", Name: "resolved",
Provider: AlertProvider{ID: "123"}, Provider: AlertProvider{ID: "123"},
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3}, Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
Resolved: true, Resolved: true,
ExpectedBody: "{\"chat_id\": \"123\", \"text\": \"⛑ *Gatus* \\nAn alert for *endpoint-name* has been resolved:\\n—\\n _healthcheck passing successfully 3 time(s) in a row_\\n— \\n*Description* \\n_description-2_ \\n\\n*Condition results*\\n✅ - `[CONNECTED] == true`\\n✅ - `[STATUS] == 200`\\n\", \"parse_mode\": \"MARKDOWN\"}", ExpectedBody: "{\"chat_id\":\"123\",\"text\":\"⛑ *Gatus* \\nAn alert for *endpoint-name* has been resolved:\\n—\\n _healthcheck passing successfully 3 time(s) in a row_\\n— \\n*Description* \\n_description-2_ \\n\\n*Condition results*\\n✅ - `[CONNECTED] == true`\\n✅ - `[STATUS] == 200`\\n\",\"parse_mode\":\"MARKDOWN\"}",
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
@@ -137,11 +147,11 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
}, },
scenario.Resolved, scenario.Resolved,
) )
if body != scenario.ExpectedBody { if string(body) != scenario.ExpectedBody {
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body) t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
} }
out := make(map[string]interface{}) out := make(map[string]interface{})
if err := json.Unmarshal([]byte(body), &out); err != nil { if err := json.Unmarshal(body, &out); err != nil {
t.Error("expected body to be valid JSON, got error:", err.Error()) t.Error("expected body to be valid JSON, got error:", err.Error())
} }
}) })
+1
View File
@@ -42,6 +42,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
if err != nil { if err != nil {
return err return err
} }
defer response.Body.Close()
if response.StatusCode > 399 { if response.StatusCode > 399 {
body, _ := io.ReadAll(response.Body) body, _ := io.ReadAll(response.Body)
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body)) return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
+1 -1
View File
@@ -17,7 +17,7 @@ import (
// injectedHTTPClient is used for testing purposes // injectedHTTPClient is used for testing purposes
var injectedHTTPClient *http.Client var injectedHTTPClient *http.Client
// GetHTTPClient returns the shared HTTP client // GetHTTPClient returns the shared HTTP client, or the client from the configuration passed
func GetHTTPClient(config *Config) *http.Client { func GetHTTPClient(config *Config) *http.Client {
if injectedHTTPClient != nil { if injectedHTTPClient != nil {
return injectedHTTPClient return injectedHTTPClient
+6
View File
@@ -45,3 +45,9 @@ endpoints:
interval: 1m interval: 1m
conditions: conditions:
- "[CONNECTED] == true" - "[CONNECTED] == true"
- name: check-domain-expiration
url: "https://example.org/"
interval: 1h
conditions:
- "[DOMAIN_EXPIRATION] > 720h"
+33 -1
View File
@@ -2,6 +2,7 @@ package config
import ( import (
"errors" "errors"
"fmt"
"log" "log"
"os" "os"
"time" "time"
@@ -10,11 +11,13 @@ import (
"github.com/TwiN/gatus/v4/alerting/alert" "github.com/TwiN/gatus/v4/alerting/alert"
"github.com/TwiN/gatus/v4/alerting/provider" "github.com/TwiN/gatus/v4/alerting/provider"
"github.com/TwiN/gatus/v4/config/maintenance" "github.com/TwiN/gatus/v4/config/maintenance"
"github.com/TwiN/gatus/v4/config/remote"
"github.com/TwiN/gatus/v4/config/ui" "github.com/TwiN/gatus/v4/config/ui"
"github.com/TwiN/gatus/v4/config/web" "github.com/TwiN/gatus/v4/config/web"
"github.com/TwiN/gatus/v4/core" "github.com/TwiN/gatus/v4/core"
"github.com/TwiN/gatus/v4/security" "github.com/TwiN/gatus/v4/security"
"github.com/TwiN/gatus/v4/storage" "github.com/TwiN/gatus/v4/storage"
"github.com/TwiN/gatus/v4/util"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
@@ -85,10 +88,24 @@ type Config struct {
// Maintenance is the configuration for creating a maintenance window in which no alerts are sent // Maintenance is the configuration for creating a maintenance window in which no alerts are sent
Maintenance *maintenance.Config `yaml:"maintenance,omitempty"` Maintenance *maintenance.Config `yaml:"maintenance,omitempty"`
// Remote is the configuration for remote Gatus instances
// WARNING: This is in ALPHA and may change or be completely removed in the future
Remote *remote.Config `yaml:"remote,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
} }
func (config *Config) GetEndpointByKey(key string) *core.Endpoint {
for i := 0; i < len(config.Endpoints); i++ {
ep := config.Endpoints[i]
if util.ConvertGroupAndEndpointNameToKey(ep.Group, ep.Name) == key {
return ep
}
}
return nil
}
// HasLoadedConfigurationFileBeenModified returns whether the file that the // HasLoadedConfigurationFileBeenModified returns whether the file that the
// configuration has been loaded from has been modified since it was last read // configuration has been loaded from has been modified since it was last read
func (config Config) HasLoadedConfigurationFileBeenModified() bool { func (config Config) HasLoadedConfigurationFileBeenModified() bool {
@@ -185,10 +202,22 @@ func parseAndValidateConfigBytes(yamlBytes []byte) (config *Config, err error) {
if err := validateStorageConfig(config); err != nil { if err := validateStorageConfig(config); err != nil {
return nil, err return nil, err
} }
if err := validateRemoteConfig(config); err != nil {
return nil, err
}
} }
return return
} }
func validateRemoteConfig(config *Config) error {
if config.Remote != nil {
if err := config.Remote.ValidateAndSetDefaults(); err != nil {
return err
}
}
return nil
}
func validateStorageConfig(config *Config) error { func validateStorageConfig(config *Config) error {
if config.Storage == nil { if config.Storage == nil {
config.Storage = &storage.Config{ config.Storage = &storage.Config{
@@ -239,7 +268,7 @@ func validateEndpointsConfig(config *Config) error {
log.Printf("[config][validateEndpointsConfig] Validating endpoint '%s'", endpoint.Name) log.Printf("[config][validateEndpointsConfig] Validating endpoint '%s'", endpoint.Name)
} }
if err := endpoint.ValidateAndSetDefaults(); err != nil { if err := endpoint.ValidateAndSetDefaults(); err != nil {
return err return fmt.Errorf("invalid endpoint %s: %s", endpoint.DisplayName(), err)
} }
} }
log.Printf("[config][validateEndpointsConfig] Validated %d endpoints", len(config.Endpoints)) log.Printf("[config][validateEndpointsConfig] Validated %d endpoints", len(config.Endpoints))
@@ -273,9 +302,12 @@ func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.E
alertTypes := []alert.Type{ alertTypes := []alert.Type{
alert.TypeCustom, alert.TypeCustom,
alert.TypeDiscord, alert.TypeDiscord,
alert.TypeGoogleChat,
alert.TypeEmail, alert.TypeEmail,
alert.TypeMatrix,
alert.TypeMattermost, alert.TypeMattermost,
alert.TypeMessagebird, alert.TypeMessagebird,
alert.TypeNtfy,
alert.TypeOpsgenie, alert.TypeOpsgenie,
alert.TypePagerDuty, alert.TypePagerDuty,
alert.TypeSlack, alert.TypeSlack,
+1 -6
View File
@@ -17,7 +17,6 @@ import (
"github.com/TwiN/gatus/v4/alerting/provider/telegram" "github.com/TwiN/gatus/v4/alerting/provider/telegram"
"github.com/TwiN/gatus/v4/alerting/provider/twilio" "github.com/TwiN/gatus/v4/alerting/provider/twilio"
"github.com/TwiN/gatus/v4/client" "github.com/TwiN/gatus/v4/client"
"github.com/TwiN/gatus/v4/config/ui"
"github.com/TwiN/gatus/v4/config/web" "github.com/TwiN/gatus/v4/config/web"
"github.com/TwiN/gatus/v4/core" "github.com/TwiN/gatus/v4/core"
"github.com/TwiN/gatus/v4/storage" "github.com/TwiN/gatus/v4/storage"
@@ -39,10 +38,6 @@ func TestLoadDefaultConfigurationFile(t *testing.T) {
func TestParseAndValidateConfigBytes(t *testing.T) { func TestParseAndValidateConfigBytes(t *testing.T) {
file := t.TempDir() + "/test.db" file := t.TempDir() + "/test.db"
ui.StaticFolder = "../web/static"
defer func() {
ui.StaticFolder = "./web/static"
}()
config, err := parseAndValidateConfigBytes([]byte(fmt.Sprintf(` config, err := parseAndValidateConfigBytes([]byte(fmt.Sprintf(`
storage: storage:
type: sqlite type: sqlite
@@ -1125,7 +1120,7 @@ endpoints:
conditions: conditions:
- "[STATUS] == 200" - "[STATUS] == 200"
`)) `))
if err != core.ErrEndpointWithNoName { if err == nil {
t.Error("should've returned an error") t.Error("should've returned an error")
} }
} }
+39
View File
@@ -0,0 +1,39 @@
package remote
import (
"log"
"github.com/TwiN/gatus/v4/client"
)
// NOTICE: This is an experimental alpha feature and may be updated/removed in future versions.
// For more information, see https://github.com/TwiN/gatus/issues/64
type Config struct {
// Instances is a list of remote instances to retrieve endpoint statuses from.
Instances []Instance `yaml:"instances,omitempty"`
// ClientConfig is the configuration of the client used to communicate with the provider's target
ClientConfig *client.Config `yaml:"client,omitempty"`
}
type Instance struct {
EndpointPrefix string `yaml:"endpoint-prefix"`
URL string `yaml:"url"`
}
func (c *Config) ValidateAndSetDefaults() error {
if c.ClientConfig == nil {
c.ClientConfig = client.GetDefaultConfig()
} else {
if err := c.ClientConfig.ValidateAndSetDefaults(); err != nil {
return err
}
}
if len(c.Instances) > 0 {
log.Println("WARNING: Your configuration is using 'remote', which is in alpha and may be updated/removed in future versions.")
log.Println("WARNING: See https://github.com/TwiN/gatus/issues/64 for more information")
log.Println("WARNING: This feature is a candidate for removal in future versions. Please comment on the issue above if you need this feature.")
}
return nil
}
+3 -5
View File
@@ -4,6 +4,8 @@ import (
"bytes" "bytes"
"errors" "errors"
"html/template" "html/template"
"github.com/TwiN/gatus/v4/web"
) )
const ( const (
@@ -14,10 +16,6 @@ const (
) )
var ( 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"
ErrButtonValidationFailed = errors.New("invalid button configuration: missing required name or link") ErrButtonValidationFailed = errors.New("invalid button configuration: missing required name or link")
) )
@@ -71,7 +69,7 @@ func (cfg *Config) ValidateAndSetDefaults() error {
} }
} }
// Validate that the template works // Validate that the template works
t, err := template.ParseFiles(StaticFolder + "/index.html") t, err := template.ParseFS(static.FileSystem, static.IndexPath)
if err != nil { if err != nil {
return err return err
} }
-4
View File
@@ -6,10 +6,6 @@ import (
) )
func TestConfig_ValidateAndSetDefaults(t *testing.T) { func TestConfig_ValidateAndSetDefaults(t *testing.T) {
StaticFolder = "../../web/static"
defer func() {
StaticFolder = "./web/static"
}()
cfg := &Config{ cfg := &Config{
Title: "", Title: "",
Header: "", Header: "",
+5 -7
View File
@@ -8,10 +8,8 @@ import (
"os" "os"
"time" "time"
"github.com/TwiN/gatus/v4/config/ui" "github.com/TwiN/gatus/v4/config"
"github.com/TwiN/gatus/v4/config/web"
"github.com/TwiN/gatus/v4/controller/handler" "github.com/TwiN/gatus/v4/controller/handler"
"github.com/TwiN/gatus/v4/security"
) )
var ( var (
@@ -21,19 +19,19 @@ var (
) )
// Handle creates the router and starts the server // Handle creates the router and starts the server
func Handle(securityConfig *security.Config, webConfig *web.Config, uiConfig *ui.Config, enableMetrics bool) { func Handle(cfg *config.Config) {
var router http.Handler = handler.CreateRouter(ui.StaticFolder, securityConfig, uiConfig, enableMetrics) var router http.Handler = handler.CreateRouter(cfg)
if os.Getenv("ENVIRONMENT") == "dev" { if os.Getenv("ENVIRONMENT") == "dev" {
router = handler.DevelopmentCORS(router) router = handler.DevelopmentCORS(router)
} }
server = &http.Server{ server = &http.Server{
Addr: fmt.Sprintf("%s:%d", webConfig.Address, webConfig.Port), Addr: fmt.Sprintf("%s:%d", cfg.Web.Address, cfg.Web.Port),
Handler: router, Handler: router,
ReadTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second,
IdleTimeout: 15 * time.Second, IdleTimeout: 15 * time.Second,
} }
log.Println("[controller][Handle] Listening on " + webConfig.SocketAddress()) log.Println("[controller][Handle] Listening on " + cfg.Web.SocketAddress())
if os.Getenv("ROUTER_TEST") == "true" { if os.Getenv("ROUTER_TEST") == "true" {
return return
} }
+1 -1
View File
@@ -32,7 +32,7 @@ func TestHandle(t *testing.T) {
_ = os.Setenv("ROUTER_TEST", "true") _ = os.Setenv("ROUTER_TEST", "true")
_ = os.Setenv("ENVIRONMENT", "dev") _ = os.Setenv("ENVIRONMENT", "dev")
defer os.Clearenv() defer os.Clearenv()
Handle(cfg.Security, cfg.Web, cfg.UI, cfg.Metrics) Handle(cfg)
defer Shutdown() defer Shutdown()
request, _ := http.NewRequest("GET", "/health", http.NoBody) request, _ := http.NewRequest("GET", "/health", http.NoBody)
responseRecorder := httptest.NewRecorder() responseRecorder := httptest.NewRecorder()
+46 -43
View File
@@ -7,6 +7,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/TwiN/gatus/v4/config"
"github.com/TwiN/gatus/v4/storage/store" "github.com/TwiN/gatus/v4/storage/store"
"github.com/TwiN/gatus/v4/storage/store/common" "github.com/TwiN/gatus/v4/storage/store/common"
"github.com/TwiN/gatus/v4/storage/store/common/paging" "github.com/TwiN/gatus/v4/storage/store/common/paging"
@@ -28,6 +29,10 @@ const (
HealthStatusUnknown = "?" HealthStatusUnknown = "?"
) )
var (
badgeColors = []string{badgeColorHexAwesome, badgeColorHexGreat, badgeColorHexGood, badgeColorHexPassable, badgeColorHexBad}
)
// UptimeBadge handles the automatic generation of badge based on the group name and endpoint 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
@@ -68,38 +73,40 @@ func UptimeBadge(writer http.ResponseWriter, request *http.Request) {
// ResponseTimeBadge handles the automatic generation of badge based on the group name and endpoint 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(config *config.Config) http.HandlerFunc {
variables := mux.Vars(request) return func(writer http.ResponseWriter, request *http.Request) {
duration := variables["duration"] variables := mux.Vars(request)
var from time.Time duration := variables["duration"]
switch duration { var from time.Time
case "7d": switch duration {
from = time.Now().Add(-7 * 24 * time.Hour) case "7d":
case "24h": from = time.Now().Add(-7 * 24 * time.Hour)
from = time.Now().Add(-24 * time.Hour) case "24h":
case "1h": from = time.Now().Add(-24 * time.Hour)
from = time.Now().Add(-2 * time.Hour) // Because response time metrics are stored by hour, we have to cheat a little case "1h":
default: from = time.Now().Add(-2 * time.Hour) // Because response time metrics are stored by hour, we have to cheat a little
http.Error(writer, "Durations supported: 7d, 24h, 1h", http.StatusBadRequest) default:
return http.Error(writer, "Durations supported: 7d, 24h, 1h", http.StatusBadRequest)
} return
key := variables["key"]
averageResponseTime, err := store.Get().GetAverageResponseTimeByKey(key, from, time.Now())
if err != nil {
if err == common.ErrEndpointNotFound {
http.Error(writer, err.Error(), http.StatusNotFound)
} else if err == common.ErrInvalidTimeRange {
http.Error(writer, err.Error(), http.StatusBadRequest)
} else {
http.Error(writer, err.Error(), http.StatusInternalServerError)
} }
return key := variables["key"]
averageResponseTime, err := store.Get().GetAverageResponseTimeByKey(key, from, time.Now())
if err != nil {
if err == common.ErrEndpointNotFound {
http.Error(writer, err.Error(), http.StatusNotFound)
} else if err == common.ErrInvalidTimeRange {
http.Error(writer, err.Error(), http.StatusBadRequest)
} else {
http.Error(writer, err.Error(), http.StatusInternalServerError)
}
return
}
writer.Header().Set("Content-Type", "image/svg+xml")
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
writer.Header().Set("Expires", "0")
writer.WriteHeader(http.StatusOK)
_, _ = writer.Write(generateResponseTimeBadgeSVG(duration, averageResponseTime, key, config))
} }
writer.Header().Set("Content-Type", "image/svg+xml")
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
writer.Header().Set("Expires", "0")
writer.WriteHeader(http.StatusOK)
_, _ = writer.Write(generateResponseTimeBadgeSVG(duration, averageResponseTime))
} }
// HealthBadge handles the automatic generation of badge based on the group name and endpoint name passed. // HealthBadge handles the automatic generation of badge based on the group name and endpoint name passed.
@@ -199,7 +206,7 @@ func getBadgeColorFromUptime(uptime float64) string {
return badgeColorHexVeryBad return badgeColorHexVeryBad
} }
func generateResponseTimeBadgeSVG(duration string, averageResponseTime int) []byte { func generateResponseTimeBadgeSVG(duration string, averageResponseTime int, key string, cfg *config.Config) []byte {
var labelWidth, valueWidth int var labelWidth, valueWidth int
switch duration { switch duration {
case "7d": case "7d":
@@ -210,7 +217,7 @@ func generateResponseTimeBadgeSVG(duration string, averageResponseTime int) []by
labelWidth = 105 labelWidth = 105
default: default:
} }
color := getBadgeColorFromResponseTime(averageResponseTime) color := getBadgeColorFromResponseTime(averageResponseTime, key, cfg)
sanitizedValue := strconv.Itoa(averageResponseTime) + "ms" sanitizedValue := strconv.Itoa(averageResponseTime) + "ms"
valueWidth = len(sanitizedValue) * 11 valueWidth = len(sanitizedValue) * 11
width := labelWidth + valueWidth width := labelWidth + valueWidth
@@ -247,17 +254,13 @@ func generateResponseTimeBadgeSVG(duration string, averageResponseTime int) []by
return svg return svg
} }
func getBadgeColorFromResponseTime(responseTime int) string { func getBadgeColorFromResponseTime(responseTime int, key string, cfg *config.Config) string {
if responseTime <= 50 { endpoint := cfg.GetEndpointByKey(key)
return badgeColorHexAwesome // the threshold config requires 5 values, so we can be sure it's set here
} else if responseTime <= 200 { for i := 0; i < 5; i++ {
return badgeColorHexGreat if responseTime <= endpoint.UIConfig.Badge.ResponseTime.Thresholds[i] {
} else if responseTime <= 300 { return badgeColors[i]
return badgeColorHexGood }
} else if responseTime <= 500 {
return badgeColorHexPassable
} else if responseTime <= 750 {
return badgeColorHexBad
} }
return badgeColorHexVeryBad return badgeColorHexVeryBad
} }
+118 -4
View File
@@ -9,6 +9,7 @@ import (
"github.com/TwiN/gatus/v4/config" "github.com/TwiN/gatus/v4/config"
"github.com/TwiN/gatus/v4/core" "github.com/TwiN/gatus/v4/core"
"github.com/TwiN/gatus/v4/core/ui"
"github.com/TwiN/gatus/v4/storage/store" "github.com/TwiN/gatus/v4/storage/store"
"github.com/TwiN/gatus/v4/watchdog" "github.com/TwiN/gatus/v4/watchdog"
) )
@@ -29,9 +30,39 @@ func TestBadge(t *testing.T) {
}, },
}, },
} }
testSuccessfulResult = core.Result{
Hostname: "example.org",
IP: "127.0.0.1",
HTTPStatus: 200,
Errors: nil,
Connected: true,
Success: true,
Timestamp: timestamp,
Duration: 150 * time.Millisecond,
CertificateExpiration: 10 * time.Hour,
ConditionResults: []*core.ConditionResult{
{
Condition: "[STATUS] == 200",
Success: true,
},
{
Condition: "[RESPONSE_TIME] < 500",
Success: true,
},
{
Condition: "[CERTIFICATE_EXPIRATION] < 72h",
Success: true,
},
},
}
cfg.Endpoints[0].UIConfig = ui.GetDefaultConfig()
cfg.Endpoints[1].UIConfig = ui.GetDefaultConfig()
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Connected: true, Duration: time.Millisecond, Timestamp: time.Now()}) watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Connected: true, Duration: time.Millisecond, Timestamp: time.Now()})
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Connected: false, Duration: time.Second, Timestamp: time.Now()}) watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Connected: false, Duration: time.Second, Timestamp: time.Now()})
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics) router := CreateRouter(cfg)
type Scenario struct { type Scenario struct {
Name string Name string
Path string Path string
@@ -109,6 +140,16 @@ func TestBadge(t *testing.T) {
Path: "/api/v1/endpoints/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",
Path: "/api/v1/endpoints/core_frontend/response-times/7d/chart.svg",
ExpectedCode: http.StatusOK,
},
{
Name: "chart-response-time-with-invalid-duration",
Path: "/api/v1/endpoints/core_backend/response-times/3d/chart.svg",
ExpectedCode: http.StatusBadRequest,
},
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) { t.Run(scenario.Name, func(t *testing.T) {
@@ -181,55 +222,128 @@ func TestGetBadgeColorFromUptime(t *testing.T) {
} }
func TestGetBadgeColorFromResponseTime(t *testing.T) { func TestGetBadgeColorFromResponseTime(t *testing.T) {
defer store.Get().Clear()
defer cache.Clear()
var (
firstCondition = core.Condition("[STATUS] == 200")
secondCondition = core.Condition("[RESPONSE_TIME] < 500")
thirdCondition = core.Condition("[CERTIFICATE_EXPIRATION] < 72h")
)
firstTestEndpoint := core.Endpoint{
Name: "a",
URL: "https://example.org/what/ever",
Method: "GET",
Body: "body",
Interval: 30 * time.Second,
Conditions: []core.Condition{firstCondition, secondCondition, thirdCondition},
Alerts: nil,
NumberOfFailuresInARow: 0,
NumberOfSuccessesInARow: 0,
UIConfig: ui.GetDefaultConfig(),
}
secondTestEndpoint := core.Endpoint{
Name: "b",
URL: "https://example.org/what/ever",
Method: "GET",
Body: "body",
Interval: 30 * time.Second,
Conditions: []core.Condition{firstCondition, secondCondition, thirdCondition},
Alerts: nil,
NumberOfFailuresInARow: 0,
NumberOfSuccessesInARow: 0,
UIConfig: &ui.Config{
Badge: &ui.Badge{
ResponseTime: &ui.ResponseTime{
Thresholds: []int{100, 500, 1000, 2000, 3000},
},
},
},
}
cfg := &config.Config{
Metrics: true,
Endpoints: []*core.Endpoint{&firstTestEndpoint, &secondTestEndpoint},
}
store.Get().Insert(&firstTestEndpoint, &testSuccessfulResult)
store.Get().Insert(&secondTestEndpoint, &testSuccessfulResult)
scenarios := []struct { scenarios := []struct {
Key string
ResponseTime int ResponseTime int
ExpectedColor string ExpectedColor string
}{ }{
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 10, ResponseTime: 10,
ExpectedColor: badgeColorHexAwesome, ExpectedColor: badgeColorHexAwesome,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 50, ResponseTime: 50,
ExpectedColor: badgeColorHexAwesome, ExpectedColor: badgeColorHexAwesome,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 75, ResponseTime: 75,
ExpectedColor: badgeColorHexGreat, ExpectedColor: badgeColorHexGreat,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 150, ResponseTime: 150,
ExpectedColor: badgeColorHexGreat, ExpectedColor: badgeColorHexGreat,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 201, ResponseTime: 201,
ExpectedColor: badgeColorHexGood, ExpectedColor: badgeColorHexGood,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 300, ResponseTime: 300,
ExpectedColor: badgeColorHexGood, ExpectedColor: badgeColorHexGood,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 301, ResponseTime: 301,
ExpectedColor: badgeColorHexPassable, ExpectedColor: badgeColorHexPassable,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 450, ResponseTime: 450,
ExpectedColor: badgeColorHexPassable, ExpectedColor: badgeColorHexPassable,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 700, ResponseTime: 700,
ExpectedColor: badgeColorHexBad, ExpectedColor: badgeColorHexBad,
}, },
{ {
Key: firstTestEndpoint.Key(),
ResponseTime: 1500, ResponseTime: 1500,
ExpectedColor: badgeColorHexVeryBad, ExpectedColor: badgeColorHexVeryBad,
}, },
{
Key: secondTestEndpoint.Key(),
ResponseTime: 50,
ExpectedColor: badgeColorHexAwesome,
},
{
Key: secondTestEndpoint.Key(),
ResponseTime: 1500,
ExpectedColor: badgeColorHexPassable,
},
{
Key: secondTestEndpoint.Key(),
ResponseTime: 2222,
ExpectedColor: badgeColorHexBad,
},
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
t.Run("response-time-"+strconv.Itoa(scenario.ResponseTime), func(t *testing.T) { t.Run(scenario.Key+"-response-time-"+strconv.Itoa(scenario.ResponseTime), func(t *testing.T) {
if getBadgeColorFromResponseTime(scenario.ResponseTime) != scenario.ExpectedColor { if getBadgeColorFromResponseTime(scenario.ResponseTime, scenario.Key, cfg) != scenario.ExpectedColor {
t.Errorf("expected %s from %d, got %v", scenario.ExpectedColor, scenario.ResponseTime, getBadgeColorFromResponseTime(scenario.ResponseTime)) t.Errorf("expected %s from %d, got %v", scenario.ExpectedColor, scenario.ResponseTime, getBadgeColorFromResponseTime(scenario.ResponseTime, scenario.Key, cfg))
} }
}) })
} }
+1 -1
View File
@@ -30,7 +30,7 @@ func TestResponseTimeChart(t *testing.T) {
} }
watchdog.UpdateEndpointStatuses(cfg.Endpoints[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.UpdateEndpointStatuses(cfg.Endpoints[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(cfg)
type Scenario struct { type Scenario struct {
Name string Name string
Path string Path string
+85 -39
View File
@@ -5,11 +5,16 @@ import (
"compress/gzip" "compress/gzip"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"log" "log"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/TwiN/gatus/v4/client"
"github.com/TwiN/gatus/v4/config"
"github.com/TwiN/gatus/v4/config/remote"
"github.com/TwiN/gatus/v4/core"
"github.com/TwiN/gatus/v4/storage/store" "github.com/TwiN/gatus/v4/storage/store"
"github.com/TwiN/gatus/v4/storage/store/common" "github.com/TwiN/gatus/v4/storage/store/common"
"github.com/TwiN/gatus/v4/storage/store/common/paging" "github.com/TwiN/gatus/v4/storage/store/common/paging"
@@ -28,48 +33,89 @@ var (
// EndpointStatuses handles requests to retrieve all EndpointStatus // 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 EndpointStatuses(writer http.ResponseWriter, r *http.Request) { func EndpointStatuses(cfg *config.Config) http.HandlerFunc {
page, pageSize := extractPageAndPageSizeFromRequest(r) return func(writer http.ResponseWriter, r *http.Request) {
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") page, pageSize := extractPageAndPageSizeFromRequest(r)
var exists bool gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
var value interface{} var exists bool
if gzipped { var value interface{}
writer.Header().Set("Content-Encoding", "gzip")
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize))
} else {
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize))
}
var data []byte
if !exists {
var err error
buffer := &bytes.Buffer{}
gzipWriter := gzip.NewWriter(buffer)
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
if err != nil {
log.Printf("[handler][EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
data, err = json.Marshal(endpointStatuses)
if err != nil {
log.Printf("[handler][EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
return
}
_, _ = gzipWriter.Write(data)
_ = gzipWriter.Close()
gzippedData := buffer.Bytes()
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize), gzippedData, cacheTTL)
if gzipped { if gzipped {
data = gzippedData writer.Header().Set("Content-Encoding", "gzip")
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize))
} else {
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize))
} }
} else { var data []byte
data = value.([]byte) if !exists {
var err error
buffer := &bytes.Buffer{}
gzipWriter := gzip.NewWriter(buffer)
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
if err != nil {
log.Printf("[handler][EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
// ALPHA: Retrieve endpoint statuses from remote instances
if endpointStatusesFromRemote, err := getEndpointStatusesFromRemoteInstances(cfg.Remote); err != nil {
log.Printf("[handler][EndpointStatuses] Silently failed to retrieve endpoint statuses from remote: %s", err.Error())
} else if endpointStatusesFromRemote != nil {
endpointStatuses = append(endpointStatuses, endpointStatusesFromRemote...)
}
// Marshal endpoint statuses to JSON
data, err = json.Marshal(endpointStatuses)
if err != nil {
log.Printf("[handler][EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
return
}
_, _ = gzipWriter.Write(data)
_ = gzipWriter.Close()
gzippedData := buffer.Bytes()
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize), gzippedData, cacheTTL)
if gzipped {
data = gzippedData
}
} else {
data = value.([]byte)
}
writer.Header().Add("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
_, _ = writer.Write(data)
} }
writer.Header().Add("Content-Type", "application/json") }
writer.WriteHeader(http.StatusOK)
_, _ = writer.Write(data) func getEndpointStatusesFromRemoteInstances(remoteConfig *remote.Config) ([]*core.EndpointStatus, error) {
if remoteConfig == nil || len(remoteConfig.Instances) == 0 {
return nil, nil
}
var endpointStatusesFromAllRemotes []*core.EndpointStatus
httpClient := client.GetHTTPClient(remoteConfig.ClientConfig)
for _, instance := range remoteConfig.Instances {
response, err := httpClient.Get(instance.URL)
if err != nil {
return nil, err
}
body, err := io.ReadAll(response.Body)
if err != nil {
_ = response.Body.Close()
log.Printf("[handler][getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
continue
}
var endpointStatuses []*core.EndpointStatus
if err = json.Unmarshal(body, &endpointStatuses); err != nil {
_ = response.Body.Close()
log.Printf("[handler][getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
continue
}
_ = response.Body.Close()
for _, endpointStatus := range endpointStatuses {
endpointStatus.Name = instance.EndpointPrefix + endpointStatus.Name
}
endpointStatusesFromAllRemotes = append(endpointStatusesFromAllRemotes, endpointStatuses...)
}
return endpointStatusesFromAllRemotes, nil
} }
// EndpointStatus retrieves a single core.EndpointStatus by group and endpoint name // EndpointStatus retrieves a single core.EndpointStatus by group and endpoint name
+2 -2
View File
@@ -97,7 +97,7 @@ func TestEndpointStatus(t *testing.T) {
} }
watchdog.UpdateEndpointStatuses(cfg.Endpoints[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.UpdateEndpointStatuses(cfg.Endpoints[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(cfg)
type Scenario struct { type Scenario struct {
Name string Name string
@@ -153,7 +153,7 @@ func TestEndpointStatuses(t *testing.T) {
// 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{}
router := CreateRouter("../../web/static", nil, nil, false) router := CreateRouter(&config.Config{Metrics: true})
type Scenario struct { type Scenario struct {
Name string Name string
-12
View File
@@ -1,12 +0,0 @@
package handler
import (
"net/http"
)
// FavIcon handles requests for /favicon.ico
func FavIcon(staticFolder string) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
http.ServeFile(writer, request, staticFolder+"/favicon.ico")
}
}
-33
View File
@@ -1,33 +0,0 @@
package handler
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestFavIcon(t *testing.T) {
router := CreateRouter("../../web/static", nil, nil, false)
type Scenario struct {
Name string
Path string
ExpectedCode int
}
scenarios := []Scenario{
{
Name: "favicon",
Path: "/favicon.ico",
ExpectedCode: http.StatusOK,
},
}
for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) {
request, _ := http.NewRequest("GET", scenario.Path, http.NoBody)
responseRecorder := httptest.NewRecorder()
router.ServeHTTP(responseRecorder, request)
if responseRecorder.Code != scenario.ExpectedCode {
t.Errorf("%s %s should have returned %d, but returned %d instead", request.Method, request.URL, scenario.ExpectedCode, responseRecorder.Code)
}
})
}
}
+18 -14
View File
@@ -1,46 +1,50 @@
package handler package handler
import ( import (
"io/fs"
"net/http" "net/http"
"github.com/TwiN/gatus/v4/config/ui" "github.com/TwiN/gatus/v4/config"
"github.com/TwiN/gatus/v4/security" "github.com/TwiN/gatus/v4/web"
"github.com/TwiN/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 *ui.Config, enabledMetrics bool) *mux.Router { func CreateRouter(cfg *config.Config) *mux.Router {
router := mux.NewRouter() router := mux.NewRouter()
if enabledMetrics { if cfg.Metrics {
router.Handle("/metrics", promhttp.Handler()).Methods("GET") router.Handle("/metrics", promhttp.Handler()).Methods("GET")
} }
api := router.PathPrefix("/api").Subrouter() api := router.PathPrefix("/api").Subrouter()
protected := api.PathPrefix("/").Subrouter() protected := api.PathPrefix("/").Subrouter()
unprotected := api.PathPrefix("/").Subrouter() unprotected := api.PathPrefix("/").Subrouter()
if securityConfig != nil { if cfg.Security != nil {
if err := securityConfig.RegisterHandlers(router); err != nil { if err := cfg.Security.RegisterHandlers(router); err != nil {
panic(err) panic(err)
} }
if err := securityConfig.ApplySecurityMiddleware(protected); err != nil { if err := cfg.Security.ApplySecurityMiddleware(protected); err != nil {
panic(err) panic(err)
} }
} }
// Endpoints // Endpoints
unprotected.Handle("/v1/config", ConfigHandler{securityConfig: securityConfig}).Methods("GET") unprotected.Handle("/v1/config", ConfigHandler{securityConfig: cfg.Security}).Methods("GET")
protected.HandleFunc("/v1/endpoints/statuses", EndpointStatuses).Methods("GET") // No GzipHandler for this one, because we cache the content as Gzipped already protected.HandleFunc("/v1/endpoints/statuses", EndpointStatuses(cfg)).Methods("GET") // No GzipHandler for this one, because we cache the content as Gzipped already
protected.HandleFunc("/v1/endpoints/{key}/statuses", GzipHandlerFunc(EndpointStatus)).Methods("GET") protected.HandleFunc("/v1/endpoints/{key}/statuses", GzipHandlerFunc(EndpointStatus)).Methods("GET")
unprotected.HandleFunc("/v1/endpoints/{key}/health/badge.svg", HealthBadge).Methods("GET") unprotected.HandleFunc("/v1/endpoints/{key}/health/badge.svg", HealthBadge).Methods("GET")
unprotected.HandleFunc("/v1/endpoints/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET") unprotected.HandleFunc("/v1/endpoints/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET")
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge).Methods("GET") unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge(cfg)).Methods("GET")
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET") unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET")
// Misc // Misc
router.Handle("/health", health.Handler().WithJSON(true)).Methods("GET") router.Handle("/health", health.Handler().WithJSON(true)).Methods("GET")
router.HandleFunc("/favicon.ico", FavIcon(staticFolder)).Methods("GET")
// SPA // SPA
router.HandleFunc("/endpoints/{name}", SinglePageApplication(staticFolder, uiConfig)).Methods("GET") router.HandleFunc("/endpoints/{name}", SinglePageApplication(cfg.UI)).Methods("GET")
router.HandleFunc("/", SinglePageApplication(staticFolder, uiConfig)).Methods("GET") router.HandleFunc("/", SinglePageApplication(cfg.UI)).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)))) staticFileSystem, err := fs.Sub(static.FileSystem, static.RootPath)
if err != nil {
panic(err)
}
router.PathPrefix("/").Handler(GzipHandler(http.FileServer(http.FS(staticFileSystem))))
return router return router
} }
+21 -3
View File
@@ -4,10 +4,12 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"github.com/TwiN/gatus/v4/config"
) )
func TestCreateRouter(t *testing.T) { func TestCreateRouter(t *testing.T) {
router := CreateRouter("../../web/static", nil, nil, true) router := CreateRouter(&config.Config{Metrics: true})
type Scenario struct { type Scenario struct {
Name string Name string
Path string Path string
@@ -26,16 +28,32 @@ func TestCreateRouter(t *testing.T) {
ExpectedCode: http.StatusOK, ExpectedCode: http.StatusOK,
}, },
{ {
Name: "scripts", Name: "favicon.ico",
Path: "/favicon.ico",
ExpectedCode: http.StatusOK,
},
{
Name: "app.js",
Path: "/js/app.js", Path: "/js/app.js",
ExpectedCode: http.StatusOK, ExpectedCode: http.StatusOK,
}, },
{ {
Name: "scripts-gzipped", Name: "app.js-gzipped",
Path: "/js/app.js", Path: "/js/app.js",
ExpectedCode: http.StatusOK, ExpectedCode: http.StatusOK,
Gzip: true, Gzip: true,
}, },
{
Name: "chunk-vendors.js",
Path: "/js/chunk-vendors.js",
ExpectedCode: http.StatusOK,
},
{
Name: "chunk-vendors.js-gzipped",
Path: "/js/chunk-vendors.js",
ExpectedCode: http.StatusOK,
Gzip: true,
},
{ {
Name: "index-redirect", Name: "index-redirect",
Path: "/index.html", Path: "/index.html",
+10 -6
View File
@@ -1,26 +1,30 @@
package handler package handler
import ( import (
_ "embed"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"github.com/TwiN/gatus/v4/config/ui" "github.com/TwiN/gatus/v4/config/ui"
"github.com/TwiN/gatus/v4/web"
) )
func SinglePageApplication(staticFolder string, ui *ui.Config) http.HandlerFunc { func SinglePageApplication(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.ParseFS(static.FileSystem, static.IndexPath)
if err != nil { if err != nil {
log.Println("[handler][SinglePageApplication] Failed to parse template:", err.Error()) // This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
http.ServeFile(writer, request, staticFolder+"/index.html") log.Println("[handler][SinglePageApplication] Failed to parse template. This should never happen, because the template is validated on start. Error:", err.Error())
http.Error(writer, "Failed to parse template. This should never happen, because the template is validated on start.", http.StatusInternalServerError)
return return
} }
writer.Header().Set("Content-Type", "text/html") writer.Header().Set("Content-Type", "text/html")
err = t.Execute(writer, ui) err = t.Execute(writer, ui)
if err != nil { if err != nil {
log.Println("[handler][SinglePageApplication] Failed to parse template:", err.Error()) // This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
http.ServeFile(writer, request, staticFolder+"/index.html") log.Println("[handler][SinglePageApplication] Failed to execute template. This should never happen, because the template is validated on start. Error:", err.Error())
http.Error(writer, "Failed to execute template. This should never happen, because the template is validated on start.", http.StatusInternalServerError)
return return
} }
} }
+1 -1
View File
@@ -30,7 +30,7 @@ func TestSinglePageApplication(t *testing.T) {
} }
watchdog.UpdateEndpointStatuses(cfg.Endpoints[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.UpdateEndpointStatuses(cfg.Endpoints[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(cfg)
type Scenario struct { type Scenario struct {
Name string Name string
Path string Path string
+18 -1
View File
@@ -46,6 +46,9 @@ const (
// Values that could replace the placeholder: 4461677039 (~52 days) // Values that could replace the placeholder: 4461677039 (~52 days)
CertificateExpirationPlaceholder = "[CERTIFICATE_EXPIRATION]" CertificateExpirationPlaceholder = "[CERTIFICATE_EXPIRATION]"
// DomainExpirationPlaceholder is a placeholder for the duration before the domain expires, in milliseconds.
DomainExpirationPlaceholder = "[DOMAIN_EXPIRATION]"
// LengthFunctionPrefix is the prefix for the length function // LengthFunctionPrefix is the prefix for the length function
// //
// Usage: len([BODY].articles) == 10, len([BODY].name) > 5 // Usage: len([BODY].articles) == 10, len([BODY].name) > 5
@@ -142,9 +145,21 @@ func (c Condition) hasBodyPlaceholder() bool {
return strings.Contains(string(c), BodyPlaceholder) return strings.Contains(string(c), BodyPlaceholder)
} }
// hasDomainExpirationPlaceholder checks whether the condition has a DomainExpirationPlaceholder
// Used for determining whether a whois operation is necessary
func (c Condition) hasDomainExpirationPlaceholder() bool {
return strings.Contains(string(c), DomainExpirationPlaceholder)
}
// hasIPPlaceholder checks whether the condition has an IPPlaceholder
// Used for determining whether an IP lookup is necessary
func (c Condition) hasIPPlaceholder() bool {
return strings.Contains(string(c), IPPlaceholder)
}
// isEqual compares two strings. // isEqual compares two strings.
// //
// Supports the pattern and the any functions. // Supports the "pat" and the "any" functions.
// i.e. if one of the parameters starts with PatternFunctionPrefix and ends with FunctionSuffix, it will be treated like // i.e. if one of the parameters starts with PatternFunctionPrefix and ends with FunctionSuffix, it will be treated like
// a pattern. // a pattern.
func isEqual(first, second string) bool { func isEqual(first, second string) bool {
@@ -219,6 +234,8 @@ func sanitizeAndResolve(elements []string, result *Result) ([]string, []string)
element = strconv.FormatBool(result.Connected) element = strconv.FormatBool(result.Connected)
case CertificateExpirationPlaceholder: case CertificateExpirationPlaceholder:
element = strconv.FormatInt(result.CertificateExpiration.Milliseconds(), 10) element = strconv.FormatInt(result.CertificateExpiration.Milliseconds(), 10)
case DomainExpirationPlaceholder:
element = strconv.FormatInt(result.DomainExpiration.Milliseconds(), 10)
default: default:
// if contains the BodyPlaceholder, then evaluate json path // if contains the BodyPlaceholder, then evaluate json path
if strings.Contains(element, BodyPlaceholder) { if strings.Contains(element, BodyPlaceholder) {
+80 -16
View File
@@ -16,6 +16,7 @@ import (
"github.com/TwiN/gatus/v4/client" "github.com/TwiN/gatus/v4/client"
"github.com/TwiN/gatus/v4/core/ui" "github.com/TwiN/gatus/v4/core/ui"
"github.com/TwiN/gatus/v4/util" "github.com/TwiN/gatus/v4/util"
"github.com/TwiN/whois"
) )
type EndpointType string type EndpointType string
@@ -33,13 +34,13 @@ const (
// GatusUserAgent is the default user agent that Gatus uses to send requests. // GatusUserAgent is the default user agent that Gatus uses to send requests.
GatusUserAgent = "Gatus/1.0" GatusUserAgent = "Gatus/1.0"
// EndpointType enum for the endpoint type.
EndpointTypeDNS EndpointType = "DNS" EndpointTypeDNS EndpointType = "DNS"
EndpointTypeTCP EndpointType = "TCP" EndpointTypeTCP EndpointType = "TCP"
EndpointTypeICMP EndpointType = "ICMP" EndpointTypeICMP EndpointType = "ICMP"
EndpointTypeSTARTTLS EndpointType = "STARTTLS" EndpointTypeSTARTTLS EndpointType = "STARTTLS"
EndpointTypeTLS EndpointType = "TLS" EndpointTypeTLS EndpointType = "TLS"
EndpointTypeHTTP EndpointType = "HTTP" EndpointTypeHTTP EndpointType = "HTTP"
EndpointTypeUNKNOWN EndpointType = "UNKNOWN"
) )
var ( var (
@@ -54,6 +55,15 @@ var (
// ErrEndpointWithInvalidNameOrGroup is the error with which Gatus will panic if an endpoint has an invalid character where it shouldn't // ErrEndpointWithInvalidNameOrGroup is the error with which Gatus will panic if an endpoint has an invalid character where it shouldn't
ErrEndpointWithInvalidNameOrGroup = errors.New("endpoint name and group must not have \" or \\") ErrEndpointWithInvalidNameOrGroup = errors.New("endpoint name and group must not have \" or \\")
// ErrUnknownEndpointType is the error with which Gatus will panic if an endpoint has an unknown type
ErrUnknownEndpointType = errors.New("unknown endpoint type")
// ErrInvalidEndpointIntervalForDomainExpirationPlaceholder is the error with which Gatus will panic if an endpoint
// has both an interval smaller than 5 minutes and a condition with DomainExpirationPlaceholder.
// This is because the free whois service we are using should not be abused, especially considering the fact that
// the data takes a while to be updated.
ErrInvalidEndpointIntervalForDomainExpirationPlaceholder = errors.New("the minimum interval for an endpoint with a condition using the " + DomainExpirationPlaceholder + " placeholder is 300s (5m)")
) )
// Endpoint is the configuration of a monitored // Endpoint is the configuration of a monitored
@@ -128,12 +138,14 @@ func (endpoint Endpoint) Type() EndpointType {
return EndpointTypeSTARTTLS return EndpointTypeSTARTTLS
case strings.HasPrefix(endpoint.URL, "tls://"): case strings.HasPrefix(endpoint.URL, "tls://"):
return EndpointTypeTLS return EndpointTypeTLS
default: case strings.HasPrefix(endpoint.URL, "http://") || strings.HasPrefix(endpoint.URL, "https://"):
return EndpointTypeHTTP return EndpointTypeHTTP
default:
return EndpointTypeUNKNOWN
} }
} }
// ValidateAndSetDefaults validates the endpoint's configuration and sets the default value of fields that have one // ValidateAndSetDefaults validates the endpoint's configuration and sets the default value of args that have one
func (endpoint *Endpoint) ValidateAndSetDefaults() error { func (endpoint *Endpoint) ValidateAndSetDefaults() error {
// Set default values // Set default values
if endpoint.ClientConfig == nil { if endpoint.ClientConfig == nil {
@@ -145,6 +157,10 @@ func (endpoint *Endpoint) ValidateAndSetDefaults() error {
} }
if endpoint.UIConfig == nil { if endpoint.UIConfig == nil {
endpoint.UIConfig = ui.GetDefaultConfig() endpoint.UIConfig = ui.GetDefaultConfig()
} else {
if err := endpoint.UIConfig.ValidateAndSetDefaults(); err != nil {
return err
}
} }
if endpoint.Interval == 0 { if endpoint.Interval == 0 {
endpoint.Interval = 1 * time.Minute endpoint.Interval = 1 * time.Minute
@@ -181,9 +197,19 @@ func (endpoint *Endpoint) ValidateAndSetDefaults() error {
if len(endpoint.Conditions) == 0 { if len(endpoint.Conditions) == 0 {
return ErrEndpointWithNoCondition return ErrEndpointWithNoCondition
} }
if endpoint.Interval < 5*time.Minute {
for _, condition := range endpoint.Conditions {
if condition.hasDomainExpirationPlaceholder() {
return ErrInvalidEndpointIntervalForDomainExpirationPlaceholder
}
}
}
if endpoint.DNS != nil { if endpoint.DNS != nil {
return endpoint.DNS.validateAndSetDefault() return endpoint.DNS.validateAndSetDefault()
} }
if endpoint.Type() == EndpointTypeUNKNOWN {
return ErrUnknownEndpointType
}
// Make sure that the request can be created // Make sure that the request can be created
_, err := http.NewRequest(endpoint.Method, endpoint.URL, bytes.NewBuffer([]byte(endpoint.Body))) _, err := http.NewRequest(endpoint.Method, endpoint.URL, bytes.NewBuffer([]byte(endpoint.Body)))
if err != nil { if err != nil {
@@ -208,7 +234,26 @@ func (endpoint Endpoint) Key() string {
// EvaluateHealth sends a request to the endpoint's URL and evaluates the conditions of the endpoint. // EvaluateHealth sends a request to the endpoint's URL and evaluates the conditions of the endpoint.
func (endpoint *Endpoint) EvaluateHealth() *Result { func (endpoint *Endpoint) EvaluateHealth() *Result {
result := &Result{Success: true, Errors: []string{}} result := &Result{Success: true, Errors: []string{}}
endpoint.getIP(result) // Parse or extract hostname from URL
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())
} else {
result.Hostname = urlObject.Hostname()
}
}
// Retrieve IP if necessary
if endpoint.needsToRetrieveIP() {
endpoint.getIP(result)
}
// Retrieve domain expiration if necessary
if endpoint.needsToRetrieveDomainExpiration() && len(result.Hostname) > 0 {
endpoint.getDomainExpiration(result)
}
//
if len(result.Errors) == 0 { if len(result.Errors) == 0 {
endpoint.call(result) endpoint.call(result)
} else { } else {
@@ -239,16 +284,6 @@ func (endpoint *Endpoint) EvaluateHealth() *Result {
} }
func (endpoint *Endpoint) getIP(result *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) ips, err := net.LookupIP(result.Hostname)
if err != nil { if err != nil {
result.AddError(err.Error()) result.AddError(err.Error())
@@ -257,6 +292,15 @@ func (endpoint *Endpoint) getIP(result *Result) {
result.IP = ips[0].String() result.IP = ips[0].String()
} }
func (endpoint *Endpoint) getDomainExpiration(result *Result) {
whoisClient := whois.NewClient()
if whoisResponse, err := whoisClient.QueryAndParse(result.Hostname); err != nil {
result.AddError("error querying and parsing hostname using whois client: " + err.Error())
} else {
result.DomainExpiration = time.Until(whoisResponse.ExpirationDate)
}
}
func (endpoint *Endpoint) call(result *Result) { func (endpoint *Endpoint) call(result *Result) {
var request *http.Request var request *http.Request
var response *http.Response var response *http.Response
@@ -305,7 +349,7 @@ func (endpoint *Endpoint) call(result *Result) {
if endpoint.needsToReadBody() { if endpoint.needsToReadBody() {
result.body, err = io.ReadAll(response.Body) result.body, err = io.ReadAll(response.Body)
if err != nil { if err != nil {
result.AddError(err.Error()) result.AddError("error reading response body:" + err.Error())
} }
} }
} }
@@ -332,7 +376,7 @@ func (endpoint *Endpoint) buildHTTPRequest() *http.Request {
return request return request
} }
// needsToReadBody checks if there's any conditions that requires the response body to be read // needsToReadBody checks if there's any condition that requires the response body to be read
func (endpoint *Endpoint) needsToReadBody() bool { func (endpoint *Endpoint) needsToReadBody() bool {
for _, condition := range endpoint.Conditions { for _, condition := range endpoint.Conditions {
if condition.hasBodyPlaceholder() { if condition.hasBodyPlaceholder() {
@@ -341,3 +385,23 @@ func (endpoint *Endpoint) needsToReadBody() bool {
} }
return false return false
} }
// needsToRetrieveDomainExpiration checks if there's any condition that requires a whois query to be performed
func (endpoint *Endpoint) needsToRetrieveDomainExpiration() bool {
for _, condition := range endpoint.Conditions {
if condition.hasDomainExpirationPlaceholder() {
return true
}
}
return false
}
// needsToRetrieveIP checks if there's any condition that requires an IP lookup
func (endpoint *Endpoint) needsToRetrieveIP() bool {
for _, condition := range endpoint.Conditions {
if condition.hasIPPlaceholder() {
return true
}
}
return false
}
+373 -131
View File
@@ -1,7 +1,11 @@
package core package core
import ( import (
"bytes"
"crypto/tls"
"crypto/x509"
"io" "io"
"net/http"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -9,8 +13,233 @@ import (
"github.com/TwiN/gatus/v4/alerting/alert" "github.com/TwiN/gatus/v4/alerting/alert"
"github.com/TwiN/gatus/v4/client" "github.com/TwiN/gatus/v4/client"
"github.com/TwiN/gatus/v4/core/ui" "github.com/TwiN/gatus/v4/core/ui"
"github.com/TwiN/gatus/v4/test"
) )
func TestEndpoint(t *testing.T) {
defer client.InjectHTTPClient(nil)
scenarios := []struct {
Name string
Endpoint Endpoint
ExpectedResult *Result
MockRoundTripper test.MockRoundTripper
}{
{
Name: "success",
Endpoint: Endpoint{
Name: "website-health",
URL: "https://twin.sh/health",
Conditions: []Condition{"[STATUS] == 200", "[BODY].status == UP", "[CERTIFICATE_EXPIRATION] > 24h"},
},
ExpectedResult: &Result{
Success: true,
Connected: true,
Hostname: "twin.sh",
ConditionResults: []*ConditionResult{
{Condition: "[STATUS] == 200", Success: true},
{Condition: "[BODY].status == UP", Success: true},
{Condition: "[CERTIFICATE_EXPIRATION] > 24h", Success: true},
},
DomainExpiration: 0, // Because there's no [DOMAIN_EXPIRATION] condition, this is not resolved, so it should be 0.
},
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"status": "UP"}`)),
TLS: &tls.ConnectionState{PeerCertificates: []*x509.Certificate{{NotAfter: time.Now().Add(9999 * time.Hour)}}},
}
}),
},
{
Name: "failed-body-condition",
Endpoint: Endpoint{
Name: "website-health",
URL: "https://twin.sh/health",
Conditions: []Condition{"[STATUS] == 200", "[BODY].status == UP"},
},
ExpectedResult: &Result{
Success: false,
Connected: true,
Hostname: "twin.sh",
ConditionResults: []*ConditionResult{
{Condition: "[STATUS] == 200", Success: true},
{Condition: "[BODY].status (DOWN) == UP", Success: false},
},
DomainExpiration: 0, // Because there's no [DOMAIN_EXPIRATION] condition, this is not resolved, so it should be 0.
},
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString(`{"status": "DOWN"}`))}
}),
},
{
Name: "failed-status-condition",
Endpoint: Endpoint{
Name: "website-health",
URL: "https://twin.sh/health",
Conditions: []Condition{"[STATUS] == 200"},
},
ExpectedResult: &Result{
Success: false,
Connected: true,
Hostname: "twin.sh",
ConditionResults: []*ConditionResult{
{Condition: "[STATUS] (502) == 200", Success: false},
},
DomainExpiration: 0, // Because there's no [DOMAIN_EXPIRATION] condition, this is not resolved, so it should be 0.
},
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{StatusCode: http.StatusBadGateway, Body: http.NoBody}
}),
},
{
Name: "condition-with-failed-certificate-expiration",
Endpoint: Endpoint{
Name: "website-health",
URL: "https://twin.sh/health",
Conditions: []Condition{"[CERTIFICATE_EXPIRATION] > 100h"},
UIConfig: &ui.Config{DontResolveFailedConditions: true},
},
ExpectedResult: &Result{
Success: false,
Connected: true,
Hostname: "twin.sh",
ConditionResults: []*ConditionResult{
// Because UIConfig.DontResolveFailedConditions is true, the values in the condition should not be resolved
{Condition: "[CERTIFICATE_EXPIRATION] > 100h", Success: false},
},
DomainExpiration: 0, // Because there's no [DOMAIN_EXPIRATION] condition, this is not resolved, so it should be 0.
},
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
TLS: &tls.ConnectionState{PeerCertificates: []*x509.Certificate{{NotAfter: time.Now().Add(5 * time.Hour)}}},
}
}),
},
{
Name: "domain-expiration",
Endpoint: Endpoint{
Name: "website-health",
URL: "https://twin.sh/health",
Conditions: []Condition{"[DOMAIN_EXPIRATION] > 100h"},
},
ExpectedResult: &Result{
Success: true,
Connected: true,
Hostname: "twin.sh",
ConditionResults: []*ConditionResult{
{Condition: "[DOMAIN_EXPIRATION] > 100h", Success: true},
},
DomainExpiration: 999999 * time.Hour, // Note that this test only checks if it's non-zero.
},
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
}),
},
{
Name: "endpoint-that-will-time-out-and-hidden-hostname",
Endpoint: Endpoint{
Name: "endpoint-that-will-time-out",
URL: "https://twin.sh/health",
Conditions: []Condition{"[CONNECTED] == true"},
UIConfig: &ui.Config{HideHostname: true},
ClientConfig: &client.Config{Timeout: time.Millisecond},
},
ExpectedResult: &Result{
Success: false,
Connected: false,
Hostname: "", // Because Endpoint.UIConfig.HideHostname is true, this should be empty.
ConditionResults: []*ConditionResult{
{Condition: "[CONNECTED] (false) == true", Success: false},
},
// Because there's no [DOMAIN_EXPIRATION] condition, this is not resolved, so it should be 0.
DomainExpiration: 0,
// Because Endpoint.UIConfig.HideHostname is true, the hostname should be replaced by <redacted>.
Errors: []string{`Get "https://<redacted>/health": context deadline exceeded (Client.Timeout exceeded while awaiting headers)`},
},
MockRoundTripper: nil,
},
{
Name: "endpoint-that-will-time-out-and-hidden-url",
Endpoint: Endpoint{
Name: "endpoint-that-will-time-out",
URL: "https://twin.sh/health",
Conditions: []Condition{"[CONNECTED] == true"},
UIConfig: &ui.Config{HideURL: true},
ClientConfig: &client.Config{Timeout: time.Millisecond},
},
ExpectedResult: &Result{
Success: false,
Connected: false,
Hostname: "twin.sh",
ConditionResults: []*ConditionResult{
{Condition: "[CONNECTED] (false) == true", Success: false},
},
// Because there's no [DOMAIN_EXPIRATION] condition, this is not resolved, so it should be 0.
DomainExpiration: 0,
// Because Endpoint.UIConfig.HideURL is true, the URL should be replaced by <redacted>.
Errors: []string{`Get "<redacted>": context deadline exceeded (Client.Timeout exceeded while awaiting headers)`},
},
MockRoundTripper: nil,
},
}
for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) {
if scenario.MockRoundTripper != nil {
mockClient := &http.Client{Transport: scenario.MockRoundTripper}
if scenario.Endpoint.ClientConfig != nil && scenario.Endpoint.ClientConfig.Timeout > 0 {
mockClient.Timeout = scenario.Endpoint.ClientConfig.Timeout
}
client.InjectHTTPClient(mockClient)
} else {
client.InjectHTTPClient(nil)
}
scenario.Endpoint.ValidateAndSetDefaults()
result := scenario.Endpoint.EvaluateHealth()
if result.Success != scenario.ExpectedResult.Success {
t.Errorf("Expected success to be %v, got %v", scenario.ExpectedResult.Success, result.Success)
}
if result.Connected != scenario.ExpectedResult.Connected {
t.Errorf("Expected connected to be %v, got %v", scenario.ExpectedResult.Connected, result.Connected)
}
if result.Hostname != scenario.ExpectedResult.Hostname {
t.Errorf("Expected hostname to be %v, got %v", scenario.ExpectedResult.Hostname, result.Hostname)
}
if len(result.ConditionResults) != len(scenario.ExpectedResult.ConditionResults) {
t.Errorf("Expected %v condition results, got %v", len(scenario.ExpectedResult.ConditionResults), len(result.ConditionResults))
} else {
for i, conditionResult := range result.ConditionResults {
if conditionResult.Condition != scenario.ExpectedResult.ConditionResults[i].Condition {
t.Errorf("Expected condition to be %v, got %v", scenario.ExpectedResult.ConditionResults[i].Condition, conditionResult.Condition)
}
if conditionResult.Success != scenario.ExpectedResult.ConditionResults[i].Success {
t.Errorf("Expected success of condition '%s' to be %v, got %v", conditionResult.Condition, scenario.ExpectedResult.ConditionResults[i].Success, conditionResult.Success)
}
}
}
if len(result.Errors) != len(scenario.ExpectedResult.Errors) {
t.Errorf("Expected %v errors, got %v", len(scenario.ExpectedResult.Errors), len(result.Errors))
} else {
for i, err := range result.Errors {
if err != scenario.ExpectedResult.Errors[i] {
t.Errorf("Expected error to be %v, got %v", scenario.ExpectedResult.Errors[i], err)
}
}
}
if result.DomainExpiration != scenario.ExpectedResult.DomainExpiration {
// Note that DomainExpiration is only resolved if there's a condition with the DomainExpirationPlaceholder in it.
// In other words, if there's no condition with [DOMAIN_EXPIRATION] in it, the DomainExpiration field will be 0.
// Because this is a live call, mocking it would be too much of a pain, so we're just going to check if
// the actual value is non-zero when the expected result is non-zero.
if scenario.ExpectedResult.DomainExpiration.Hours() > 0 && !(result.DomainExpiration.Hours() > 0) {
t.Errorf("Expected domain expiration to be non-zero, got %v", result.DomainExpiration)
}
}
})
}
}
func TestEndpoint_IsEnabled(t *testing.T) { func TestEndpoint_IsEnabled(t *testing.T) {
if !(Endpoint{Enabled: nil}).IsEnabled() { if !(Endpoint{Enabled: nil}).IsEnabled() {
t.Error("endpoint.IsEnabled() should've returned true, because Enabled was set to nil") t.Error("endpoint.IsEnabled() should've returned true, because Enabled was set to nil")
@@ -24,53 +253,72 @@ func TestEndpoint_IsEnabled(t *testing.T) {
} }
func TestEndpoint_Type(t *testing.T) { func TestEndpoint_Type(t *testing.T) {
type fields struct { type args struct {
URL string URL string
DNS *DNS DNS *DNS
} }
tests := []struct { tests := []struct {
fields fields args args
want EndpointType want EndpointType
}{{ }{
fields: fields{ {
URL: "1.1.1.1", args: args{
DNS: &DNS{ URL: "1.1.1.1",
QueryType: "A", DNS: &DNS{
QueryName: "example.com", QueryType: "A",
QueryName: "example.com",
},
}, },
want: EndpointTypeDNS,
}, },
want: EndpointTypeDNS, {
}, { args: args{
fields: fields{ URL: "tcp://127.0.0.1:6379",
URL: "tcp://127.0.0.1:6379", },
want: EndpointTypeTCP,
}, },
want: EndpointTypeTCP, {
}, { args: args{
fields: fields{ URL: "icmp://example.com",
URL: "icmp://example.com", },
want: EndpointTypeICMP,
}, },
want: EndpointTypeICMP, {
}, { args: args{
fields: fields{ URL: "starttls://smtp.gmail.com:587",
URL: "starttls://smtp.gmail.com:587", },
want: EndpointTypeSTARTTLS,
}, },
want: EndpointTypeSTARTTLS, {
}, { args: args{
fields: fields{ URL: "tls://example.com:443",
URL: "tls://example.com:443", },
want: EndpointTypeTLS,
}, },
want: EndpointTypeTLS, {
}, { args: args{
fields: fields{ URL: "https://twin.sh/health",
URL: "https://twin.sh/health", },
want: EndpointTypeHTTP,
}, },
want: EndpointTypeHTTP, {
}} args: args{
URL: "invalid://example.org",
},
want: EndpointTypeUNKNOWN,
},
{
args: args{
URL: "no-scheme",
},
want: EndpointTypeUNKNOWN,
},
}
for _, tt := range tests { for _, tt := range tests {
t.Run(string(tt.want), func(t *testing.T) { t.Run(string(tt.want), func(t *testing.T) {
endpoint := Endpoint{ endpoint := Endpoint{
URL: tt.fields.URL, URL: tt.args.URL,
DNS: tt.fields.DNS, DNS: tt.args.DNS,
} }
if got := endpoint.Type(); got != tt.want { if got := endpoint.Type(); got != tt.want {
t.Errorf("Endpoint.Type() = %v, want %v", got, tt.want) t.Errorf("Endpoint.Type() = %v, want %v", got, tt.want)
@@ -124,11 +372,10 @@ func TestEndpoint_ValidateAndSetDefaults(t *testing.T) {
} }
func TestEndpoint_ValidateAndSetDefaultsWithClientConfig(t *testing.T) { func TestEndpoint_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
condition := Condition("[STATUS] == 200")
endpoint := Endpoint{ endpoint := Endpoint{
Name: "website-health", Name: "website-health",
URL: "https://twin.sh/health", URL: "https://twin.sh/health",
Conditions: []Condition{condition}, Conditions: []Condition{Condition("[STATUS] == 200")},
ClientConfig: &client.Config{ ClientConfig: &client.Config{
Insecure: true, Insecure: true,
IgnoreRedirect: true, IgnoreRedirect: true,
@@ -151,51 +398,10 @@ func TestEndpoint_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
} }
} }
func TestEndpoint_ValidateAndSetDefaultsWithNoName(t *testing.T) {
defer func() { recover() }()
condition := Condition("[STATUS] == 200")
endpoint := &Endpoint{
Name: "",
URL: "http://example.com",
Conditions: []Condition{condition},
}
err := endpoint.ValidateAndSetDefaults()
if err == nil {
t.Fatal("Should've returned an error because endpoint didn't have a name, which is a mandatory field")
}
}
func TestEndpoint_ValidateAndSetDefaultsWithNoUrl(t *testing.T) {
defer func() { recover() }()
condition := Condition("[STATUS] == 200")
endpoint := &Endpoint{
Name: "example",
URL: "",
Conditions: []Condition{condition},
}
err := endpoint.ValidateAndSetDefaults()
if err == nil {
t.Fatal("Should've returned an error because endpoint didn't have an url, which is a mandatory field")
}
}
func TestEndpoint_ValidateAndSetDefaultsWithNoConditions(t *testing.T) {
defer func() { recover() }()
endpoint := &Endpoint{
Name: "example",
URL: "http://example.com",
Conditions: nil,
}
err := endpoint.ValidateAndSetDefaults()
if err == nil {
t.Fatal("Should've returned an error because endpoint didn't have at least 1 condition")
}
}
func TestEndpoint_ValidateAndSetDefaultsWithDNS(t *testing.T) { func TestEndpoint_ValidateAndSetDefaultsWithDNS(t *testing.T) {
endpoint := &Endpoint{ endpoint := &Endpoint{
Name: "dns-test", Name: "dns-test",
URL: "http://example.com", URL: "https://example.com",
DNS: &DNS{ DNS: &DNS{
QueryType: "A", QueryType: "A",
QueryName: "example.com", QueryName: "example.com",
@@ -204,13 +410,70 @@ func TestEndpoint_ValidateAndSetDefaultsWithDNS(t *testing.T) {
} }
err := endpoint.ValidateAndSetDefaults() err := endpoint.ValidateAndSetDefaults()
if err != nil { if err != nil {
t.Error("did not expect an error, got", err)
} }
if endpoint.DNS.QueryName != "example.com." { if endpoint.DNS.QueryName != "example.com." {
t.Error("Endpoint.dns.query-name should be formatted with . suffix") t.Error("Endpoint.dns.query-name should be formatted with . suffix")
} }
} }
func TestEndpoint_ValidateAndSetDefaultsWithSimpleErrors(t *testing.T) {
scenarios := []struct {
endpoint *Endpoint
expectedErr error
}{
{
endpoint: &Endpoint{
Name: "",
URL: "https://example.com",
Conditions: []Condition{Condition("[STATUS] == 200")},
},
expectedErr: ErrEndpointWithNoName,
},
{
endpoint: &Endpoint{
Name: "endpoint-with-no-url",
URL: "",
Conditions: []Condition{Condition("[STATUS] == 200")},
},
expectedErr: ErrEndpointWithNoURL,
},
{
endpoint: &Endpoint{
Name: "endpoint-with-no-conditions",
URL: "https://example.com",
Conditions: nil,
},
expectedErr: ErrEndpointWithNoCondition,
},
{
endpoint: &Endpoint{
Name: "domain-expiration-with-bad-interval",
URL: "https://example.com",
Interval: time.Minute,
Conditions: []Condition{Condition("[DOMAIN_EXPIRATION] > 720h")},
},
expectedErr: ErrInvalidEndpointIntervalForDomainExpirationPlaceholder,
},
{
endpoint: &Endpoint{
Name: "domain-expiration-with-good-interval",
URL: "https://example.com",
Interval: 5 * time.Minute,
Conditions: []Condition{Condition("[DOMAIN_EXPIRATION] > 720h")},
},
expectedErr: nil,
},
}
for _, scenario := range scenarios {
t.Run(scenario.endpoint.Name, func(t *testing.T) {
if err := scenario.endpoint.ValidateAndSetDefaults(); err != scenario.expectedErr {
t.Errorf("Expected error %v, got %v", scenario.expectedErr, err)
}
})
}
}
func TestEndpoint_buildHTTPRequest(t *testing.T) { func TestEndpoint_buildHTTPRequest(t *testing.T) {
condition := Condition("[STATUS] == 200") condition := Condition("[STATUS] == 200")
endpoint := Endpoint{ endpoint := Endpoint{
@@ -330,26 +593,6 @@ func TestIntegrationEvaluateHealth(t *testing.T) {
} }
} }
func TestIntegrationEvaluateHealthWithFailure(t *testing.T) {
condition := Condition("[STATUS] == 500")
endpoint := Endpoint{
Name: "website-health",
URL: "https://twin.sh/health",
Conditions: []Condition{condition},
}
endpoint.ValidateAndSetDefaults()
result := endpoint.EvaluateHealth()
if result.ConditionResults[0].Success {
t.Errorf("Condition '%s' should have been a failure", condition)
}
if !result.Connected {
t.Error("Because the connection has been established, result.Connected should've been true")
}
if result.Success {
t.Error("Because one of the conditions failed, result.Success should have been false")
}
}
func TestIntegrationEvaluateHealthWithInvalidCondition(t *testing.T) { func TestIntegrationEvaluateHealthWithInvalidCondition(t *testing.T) {
condition := Condition("[STATUS] invalid 200") condition := Condition("[STATUS] invalid 200")
endpoint := Endpoint{ endpoint := Endpoint{
@@ -370,32 +613,6 @@ func TestIntegrationEvaluateHealthWithInvalidCondition(t *testing.T) {
} }
} }
func TestIntegrationEvaluateHealthWithError(t *testing.T) {
condition := Condition("[STATUS] == 200")
endpoint := Endpoint{
Name: "invalid-host",
URL: "http://invalid/health",
Conditions: []Condition{condition},
UIConfig: &ui.Config{
HideHostname: true,
},
}
endpoint.ValidateAndSetDefaults()
result := endpoint.EvaluateHealth()
if result.Success {
t.Error("Because one of the conditions was invalid, result.Success should have been false")
}
if len(result.Errors) == 0 {
t.Error("There should've been an error")
}
if !strings.Contains(result.Errors[0], "<redacted>") {
t.Error("result.Errors[0] should've had the hostname redacted because ui.hide-hostname is set to true")
}
if result.Hostname != "" {
t.Error("result.Hostname should've been empty because ui.hide-hostname is set to true")
}
}
func TestIntegrationEvaluateHealthWithErrorAndHideURL(t *testing.T) { func TestIntegrationEvaluateHealthWithErrorAndHideURL(t *testing.T) {
endpoint := Endpoint{ endpoint := Endpoint{
Name: "invalid-url", Name: "invalid-url",
@@ -436,7 +653,7 @@ func TestIntegrationEvaluateHealthForDNS(t *testing.T) {
endpoint.ValidateAndSetDefaults() endpoint.ValidateAndSetDefaults()
result := endpoint.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)
} }
if !result.Connected { if !result.Connected {
t.Error("Because the connection has been established, result.Connected should've been true") t.Error("Because the connection has been established, result.Connected should've been true")
@@ -447,16 +664,15 @@ func TestIntegrationEvaluateHealthForDNS(t *testing.T) {
} }
func TestIntegrationEvaluateHealthForICMP(t *testing.T) { func TestIntegrationEvaluateHealthForICMP(t *testing.T) {
conditionSuccess := Condition("[CONNECTED] == true")
endpoint := Endpoint{ 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{"[CONNECTED] == true"},
} }
endpoint.ValidateAndSetDefaults() endpoint.ValidateAndSetDefaults()
result := endpoint.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", endpoint.Conditions[0])
} }
if !result.Connected { if !result.Connected {
t.Error("Because the connection has been established, result.Connected should've been true") t.Error("Because the connection has been established, result.Connected should've been true")
@@ -466,12 +682,20 @@ func TestIntegrationEvaluateHealthForICMP(t *testing.T) {
} }
} }
func TestEndpoint_DisplayName(t *testing.T) {
if endpoint := (Endpoint{Name: "n"}); endpoint.DisplayName() != "n" {
t.Error("endpoint.DisplayName() should've been 'n', but was", endpoint.DisplayName())
}
if endpoint := (Endpoint{Group: "g", Name: "n"}); endpoint.DisplayName() != "g/n" {
t.Error("endpoint.DisplayName() should've been 'g/n', but was", endpoint.DisplayName())
}
}
func TestEndpoint_getIP(t *testing.T) { func TestEndpoint_getIP(t *testing.T) {
conditionSuccess := Condition("[CONNECTED] == true")
endpoint := Endpoint{ endpoint := Endpoint{
Name: "invalid-url-test", Name: "invalid-url-test",
URL: "", URL: "",
Conditions: []Condition{conditionSuccess}, Conditions: []Condition{"[CONNECTED] == true"},
} }
result := &Result{} result := &Result{}
endpoint.getIP(result) endpoint.getIP(result)
@@ -480,7 +704,7 @@ func TestEndpoint_getIP(t *testing.T) {
} }
} }
func TestEndpoint_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")
@@ -503,3 +727,21 @@ func TestEndpoint_NeedsToReadBody(t *testing.T) {
t.Error("expected true, got false") t.Error("expected true, got false")
} }
} }
func TestEndpoint_needsToRetrieveDomainExpiration(t *testing.T) {
if (&Endpoint{Conditions: []Condition{"[STATUS] == 200"}}).needsToRetrieveDomainExpiration() {
t.Error("expected false, got true")
}
if !(&Endpoint{Conditions: []Condition{"[STATUS] == 200", "[DOMAIN_EXPIRATION] < 720h"}}).needsToRetrieveDomainExpiration() {
t.Error("expected true, got false")
}
}
func TestEndpoint_needsToRetrieveIP(t *testing.T) {
if (&Endpoint{Conditions: []Condition{"[STATUS] == 200"}}).needsToRetrieveIP() {
t.Error("expected false, got true")
}
if !(&Endpoint{Conditions: []Condition{"[STATUS] == 200", "[IP] == 127.0.0.1"}}).needsToRetrieveIP() {
t.Error("expected true, got false")
}
}
-11
View File
@@ -1,11 +0,0 @@
package core
// HealthStatus is the status of Gatus
type HealthStatus struct {
// Status is the state of Gatus (UP/DOWN)
Status string `json:"status"`
// Message is an accompanying description of why the status is as reported.
// If the Status is UP, no message will be provided
Message string `json:"message,omitempty"`
}
+3
View File
@@ -41,6 +41,9 @@ type Result struct {
// CertificateExpiration is the duration before the certificate expires // CertificateExpiration is the duration before the certificate expires
CertificateExpiration time.Duration `json:"-"` CertificateExpiration time.Duration `json:"-"`
// DomainExpiration is the duration before the domain expires
DomainExpiration time.Duration `json:"-"`
// body is the response body // body is the response body
// //
// Note that this variable is only used during the evaluation of an Endpoint's health. // Note that this variable is only used during the evaluation of an Endpoint's health.
+40
View File
@@ -1,13 +1,48 @@
package ui package ui
import "errors"
// Config is the UI configuration for core.Endpoint // 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"`
// HideURL whether to ensure the URL is not displayed in the results. Useful if the URL contains a token. // HideURL whether to ensure the URL is not displayed in the results. Useful if the URL contains a token.
HideURL bool `yaml:"hide-url"` HideURL bool `yaml:"hide-url"`
// DontResolveFailedConditions whether to resolve failed conditions in the Result for display in the UI // DontResolveFailedConditions whether to resolve failed conditions in the Result for display in the UI
DontResolveFailedConditions bool `yaml:"dont-resolve-failed-conditions"` DontResolveFailedConditions bool `yaml:"dont-resolve-failed-conditions"`
// Badge is the configuration for the badges generated
Badge *Badge `yaml:"badge"`
}
type Badge struct {
ResponseTime *ResponseTime `yaml:"response-time"`
}
type ResponseTime struct {
Thresholds []int `yaml:"thresholds"`
}
var (
ErrInvalidBadgeResponseTimeConfig = errors.New("invalid response time badge configuration: expected parameter 'response-time' to have 5 ascending numerical values")
)
func (config *Config) ValidateAndSetDefaults() error {
if config.Badge != nil {
if len(config.Badge.ResponseTime.Thresholds) != 5 {
return ErrInvalidBadgeResponseTimeConfig
}
for i := 4; i > 0; i-- {
if config.Badge.ResponseTime.Thresholds[i] < config.Badge.ResponseTime.Thresholds[i-1] {
return ErrInvalidBadgeResponseTimeConfig
}
}
} else {
config.Badge = GetDefaultConfig().Badge
}
return nil
} }
// GetDefaultConfig retrieves the default UI configuration // GetDefaultConfig retrieves the default UI configuration
@@ -16,5 +51,10 @@ func GetDefaultConfig() *Config {
HideHostname: false, HideHostname: false,
HideURL: false, HideURL: false,
DontResolveFailedConditions: false, DontResolveFailedConditions: false,
Badge: &Badge{
ResponseTime: &ResponseTime{
Thresholds: []int{50, 200, 300, 500, 750},
},
},
} }
} }
+4 -3
View File
@@ -1,11 +1,12 @@
module github.com/TwiN/gatus/v4 module github.com/TwiN/gatus/v4
go 1.18 go 1.19
require ( require (
github.com/TwiN/g8 v1.3.0 github.com/TwiN/g8 v1.4.0
github.com/TwiN/gocache/v2 v2.0.0 github.com/TwiN/gocache/v2 v2.1.1
github.com/TwiN/health v1.4.0 github.com/TwiN/health v1.4.0
github.com/TwiN/whois v1.0.0
github.com/coreos/go-oidc/v3 v3.1.0 github.com/coreos/go-oidc/v3 v3.1.0
github.com/go-ping/ping v0.0.0-20210911151512-381826476871 github.com/go-ping/ping v0.0.0-20210911151512-381826476871
github.com/google/uuid v1.3.0 github.com/google/uuid v1.3.0
+6 -4
View File
@@ -33,12 +33,14 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/TwiN/g8 v1.3.0 h1:mNv3R35GhDn1gEV0BKMl1oupZ1tDtOWPTHUKu+W/k3U= github.com/TwiN/g8 v1.4.0 h1:RUk5xTtxKCdMo0GGSbBVyjtAAfi2nqVbA9E0C4u5Cxo=
github.com/TwiN/g8 v1.3.0/go.mod h1:SiIdItS0agSUloFqdQQt/RObB2jGSq+nnE9WfFv3RIo= github.com/TwiN/g8 v1.4.0/go.mod h1:ECyGJsoIb99klUfvVQoS1StgRLte9yvvPigGrHdy284=
github.com/TwiN/gocache/v2 v2.0.0 h1:CPbDNKdSJpmBkh7aWcO7D3KK1yWaMlwX+3dsBPE8/so= github.com/TwiN/gocache/v2 v2.1.1 h1:W/GLImqa+pZVIH9pcWEn1cBgy1KU66fUcBjOnPhjuno=
github.com/TwiN/gocache/v2 v2.0.0/go.mod h1:j4MABVaia2Tp53ERWc/3l4YxkswtPjB2hQzmL/kD/VQ= github.com/TwiN/gocache/v2 v2.1.1/go.mod h1:SnUuBsrwGQeNcDG6vhkOMJnqErZM0JGjgIkuKryokYA=
github.com/TwiN/health v1.4.0 h1:Ts7lb4ihYDpVEbFSGAhSEZTSwuDOADnwJLFngFl4xzw= github.com/TwiN/health v1.4.0 h1:Ts7lb4ihYDpVEbFSGAhSEZTSwuDOADnwJLFngFl4xzw=
github.com/TwiN/health v1.4.0/go.mod h1:CSUh+ryfD2POS2vKtc/yO4IxgR58lKvQ0/8qnoPqPqs= github.com/TwiN/health v1.4.0/go.mod h1:CSUh+ryfD2POS2vKtc/yO4IxgR58lKvQ0/8qnoPqPqs=
github.com/TwiN/whois v1.0.0 h1:I+aQzXLPmhWovkFUzlPV2DdfLZUWDLrkMDlM6QwCv+Q=
github.com/TwiN/whois v1.0.0/go.mod h1:9WbCzYlR+r5eq9vbgJVh7A4H2uR2ct4wKEB0/QITJ/c=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
+45 -15
View File
@@ -19,7 +19,23 @@ func Eval(path string, b []byte) (string, int, error) {
} }
func walk(path string, object interface{}) (string, int, error) { func walk(path string, object interface{}) (string, int, error) {
keys := strings.Split(path, ".") var keys []string
startOfCurrentKey, bracketDepth := 0, 0
for i := range path {
if path[i] == '[' {
bracketDepth++
} else if path[i] == ']' {
bracketDepth--
}
// If we encounter a dot, we've reached the end of a key unless we're inside a bracket
if path[i] == '.' && bracketDepth == 0 {
keys = append(keys, path[startOfCurrentKey:i])
startOfCurrentKey = i + 1
}
}
if startOfCurrentKey <= len(path) {
keys = append(keys, path[startOfCurrentKey:])
}
currentKey := keys[0] currentKey := keys[0]
switch value := extractValue(currentKey, object).(type) { switch value := extractValue(currentKey, object).(type) {
case map[string]interface{}: case map[string]interface{}:
@@ -41,33 +57,47 @@ func walk(path string, object interface{}) (string, int, error) {
func extractValue(currentKey string, value interface{}) interface{} { func extractValue(currentKey string, value interface{}) interface{} {
// Check if the current key ends with [#] // Check if the current key ends with [#]
if strings.HasSuffix(currentKey, "]") && strings.Contains(currentKey, "[") { if strings.HasSuffix(currentKey, "]") && strings.Contains(currentKey, "[") {
tmp := strings.SplitN(currentKey, "[", 3) var isNestedArray bool
arrayIndex, err := strconv.Atoi(strings.Replace(tmp[1], "]", "", 1)) var index string
startOfBracket, endOfBracket, bracketDepth := 0, 0, 0
for i := range currentKey {
if currentKey[i] == '[' {
startOfBracket = i
bracketDepth++
} else if currentKey[i] == ']' && bracketDepth == 1 {
bracketDepth--
endOfBracket = i
index = currentKey[startOfBracket+1 : i]
if len(currentKey) > i+1 && currentKey[i+1] == '[' {
isNestedArray = true // there's more keys.
}
break
}
}
arrayIndex, err := strconv.Atoi(index)
if err != nil { if err != nil {
return nil return nil
} }
currentKey := tmp[0] currentKeyWithoutIndex := currentKey[:startOfBracket]
// if currentKey contains only an index (i.e. [0] or 0) // if currentKeyWithoutIndex contains only an index (i.e. [0] or 0)
if len(currentKey) == 0 { if len(currentKeyWithoutIndex) == 0 {
array := value.([]interface{}) array := value.([]interface{})
if len(array) > arrayIndex { if len(array) > arrayIndex {
if len(tmp) > 2 { if isNestedArray {
// Nested array? Go deeper. return extractValue(currentKey[endOfBracket+1:], array[arrayIndex])
return extractValue(fmt.Sprintf("%s[%s", currentKey, tmp[2]), array[arrayIndex])
} }
return array[arrayIndex] return array[arrayIndex]
} }
return nil return nil
} }
if value == nil || value.(map[string]interface{})[currentKey] == nil { if value == nil || value.(map[string]interface{})[currentKeyWithoutIndex] == nil {
return nil return nil
} }
// if currentKey contains both a key and an index (i.e. data[0]) // if currentKeyWithoutIndex contains both a key and an index (i.e. data[0])
array := value.(map[string]interface{})[currentKey].([]interface{}) array := value.(map[string]interface{})[currentKeyWithoutIndex].([]interface{})
if len(array) > arrayIndex { if len(array) > arrayIndex {
if len(tmp) > 2 { if isNestedArray {
// Nested array? Go deeper. return extractValue(currentKey[endOfBracket+1:], array[arrayIndex])
return extractValue(fmt.Sprintf("[%s", tmp[2]), array[arrayIndex])
} }
return array[arrayIndex] return array[arrayIndex]
} }
+11
View File
@@ -0,0 +1,11 @@
package jsonpath
import "testing"
func BenchmarkEval(b *testing.B) {
for i := 0; i < b.N; i++ {
Eval("ids[0]", []byte(`{"ids": [1, 2]}`))
Eval("long.simple.walk", []byte(`{"long": {"simple": {"walk": "value"}}}`))
Eval("data[0].apps[1].name", []byte(`{"data": [{"apps": [{"name":"app1"}, {"name":"app2"}, {"name":"app3"}]}]}`))
}
}
+16
View File
@@ -118,6 +118,22 @@ func TestEval(t *testing.T) {
ExpectedOutputLength: 5, ExpectedOutputLength: 5,
ExpectedError: false, ExpectedError: false,
}, },
{
Name: "map-of-arrays-of-maps",
Path: "data[0].apps[1].name",
Data: `{"data": [{"apps": [{"name":"app1"}, {"name":"app2"}, {"name":"app3"}]}]}`,
ExpectedOutput: "app2",
ExpectedOutputLength: 4,
ExpectedError: false,
},
{
Name: "map-of-arrays-of-maps-with-missing-element",
Path: "data[0].apps[1].name",
Data: `{"data": [{"apps": []}]}`,
ExpectedOutput: "",
ExpectedOutputLength: 0,
ExpectedError: true,
},
{ {
Name: "partially-invalid-path-issue122", Name: "partially-invalid-path-issue122",
Path: "data.name.invalid", Path: "data.name.invalid",
+1 -1
View File
@@ -36,7 +36,7 @@ func main() {
} }
func start(cfg *config.Config) { func start(cfg *config.Config) {
go controller.Handle(cfg.Security, cfg.Web, cfg.UI, cfg.Metrics) go controller.Handle(cfg)
watchdog.Monitor(cfg) watchdog.Monitor(cfg)
go listenToConfigurationFileChanges(cfg) go listenToConfigurationFileChanges(cfg)
} }
+6
View File
@@ -19,6 +19,12 @@ type Config struct {
// Type of store // Type of store
// If blank, uses the default in-memory store // If blank, uses the default in-memory store
Type Type `yaml:"type"` Type Type `yaml:"type"`
// Caching is whether to enable caching.
// This is used to drastically decrease read latency by pre-emptively caching writes
// as they happen, also known as the write-through caching strategy.
// Does not apply if Config.Type is not TypePostgres or TypeSQLite.
Caching bool `yaml:"caching,omitempty"`
} }
// ValidateAndSetDefaults validates the configuration and sets the default values (if applicable) // ValidateAndSetDefaults validates the configuration and sets the default values (if applicable)
+1 -10
View File
@@ -1,7 +1,6 @@
package memory package memory
import ( import (
"encoding/gob"
"sort" "sort"
"sync" "sync"
"time" "time"
@@ -13,14 +12,6 @@ import (
"github.com/TwiN/gocache/v2" "github.com/TwiN/gocache/v2"
) )
func init() {
gob.Register(&core.EndpointStatus{})
gob.Register(&core.HourlyUptimeStatistics{})
gob.Register(&core.Uptime{})
gob.Register(&core.Result{})
gob.Register(&core.Event{})
}
// Store that leverages gocache // Store that leverages gocache
type Store struct { type Store struct {
sync.RWMutex sync.RWMutex
@@ -32,7 +23,7 @@ type Store struct {
// //
// This store holds everything in memory, and if the file parameter is not blank, // This store holds everything in memory, and if the file parameter is not blank,
// supports eventual persistence. // supports eventual persistence.
func NewStore(file string) (*Store, error) { func NewStore() (*Store, error) {
store := &Store{ store := &Store{
cache: gocache.NewCache().WithMaxSize(gocache.NoMaxSize), cache: gocache.NewCache().WithMaxSize(gocache.NoMaxSize),
} }
+9 -17
View File
@@ -82,7 +82,7 @@ var (
// Note that are much more extensive tests in /storage/store/store_test.go. // Note that are much more extensive tests in /storage/store/store_test.go.
// This test is simply an extra sanity check // This test is simply an extra sanity check
func TestStore_SanityCheck(t *testing.T) { func TestStore_SanityCheck(t *testing.T) {
store, _ := NewStore("") store, _ := NewStore()
defer store.Close() defer store.Close()
store.Insert(&testEndpoint, &testSuccessfulResult) store.Insert(&testEndpoint, &testSuccessfulResult)
endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams()) endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams())
@@ -122,22 +122,14 @@ func TestStore_SanityCheck(t *testing.T) {
} }
func TestStore_Save(t *testing.T) { func TestStore_Save(t *testing.T) {
files := []string{ store, err := NewStore()
"", if err != nil {
t.TempDir() + "/test.db", t.Fatal("expected no error, got", err.Error())
} }
for _, file := range files { err = store.Save()
t.Run(file, func(t *testing.T) { if err != nil {
store, err := NewStore(file) t.Fatal("expected no error, got", err.Error())
if err != nil {
t.Fatal("expected no error, got", err.Error())
}
err = store.Save()
if err != nil {
t.Fatal("expected no error, got", err.Error())
}
store.Clear()
store.Close()
})
} }
store.Clear()
store.Close()
} }
+27 -24
View File
@@ -5,8 +5,8 @@ func (s *Store) createPostgresSchema() error {
CREATE TABLE IF NOT EXISTS endpoints ( CREATE TABLE IF NOT EXISTS endpoints (
endpoint_id BIGSERIAL PRIMARY KEY, endpoint_id BIGSERIAL PRIMARY KEY,
endpoint_key TEXT UNIQUE, endpoint_key TEXT UNIQUE,
endpoint_name TEXT, endpoint_name TEXT NOT NULL,
endpoint_group TEXT, endpoint_group TEXT NOT NULL,
UNIQUE(endpoint_name, endpoint_group) UNIQUE(endpoint_name, endpoint_group)
) )
`) `)
@@ -16,9 +16,9 @@ func (s *Store) createPostgresSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_events ( CREATE TABLE IF NOT EXISTS endpoint_events (
endpoint_event_id BIGSERIAL PRIMARY KEY, endpoint_event_id BIGSERIAL PRIMARY KEY,
endpoint_id INTEGER REFERENCES endpoints(endpoint_id) ON DELETE CASCADE, endpoint_id INTEGER NOT NULL REFERENCES endpoints(endpoint_id) ON DELETE CASCADE,
event_type TEXT, event_type TEXT NOT NULL,
event_timestamp TIMESTAMP event_timestamp TIMESTAMP NOT NULL
) )
`) `)
if err != nil { if err != nil {
@@ -27,17 +27,18 @@ func (s *Store) createPostgresSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_results ( CREATE TABLE IF NOT EXISTS endpoint_results (
endpoint_result_id BIGSERIAL PRIMARY KEY, endpoint_result_id BIGSERIAL PRIMARY KEY,
endpoint_id BIGINT REFERENCES endpoints(endpoint_id) ON DELETE CASCADE, endpoint_id BIGINT NOT NULL REFERENCES endpoints(endpoint_id) ON DELETE CASCADE,
success BOOLEAN, success BOOLEAN NOT NULL,
errors TEXT, errors TEXT NOT NULL,
connected BOOLEAN, connected BOOLEAN NOT NULL,
status BIGINT, status BIGINT NOT NULL,
dns_rcode TEXT, dns_rcode TEXT NOT NULL,
certificate_expiration BIGINT, certificate_expiration BIGINT NOT NULL,
hostname TEXT, domain_expiration BIGINT NOT NULL,
ip TEXT, hostname TEXT NOT NULL,
duration BIGINT, ip TEXT NOT NULL,
timestamp TIMESTAMP duration BIGINT NOT NULL,
timestamp TIMESTAMP NOT NULL
) )
`) `)
if err != nil { if err != nil {
@@ -46,9 +47,9 @@ func (s *Store) createPostgresSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_result_conditions ( CREATE TABLE IF NOT EXISTS endpoint_result_conditions (
endpoint_result_condition_id BIGSERIAL PRIMARY KEY, endpoint_result_condition_id BIGSERIAL PRIMARY KEY,
endpoint_result_id BIGINT REFERENCES endpoint_results(endpoint_result_id) ON DELETE CASCADE, endpoint_result_id BIGINT NOT NULL REFERENCES endpoint_results(endpoint_result_id) ON DELETE CASCADE,
condition TEXT, condition TEXT NOT NULL,
success BOOLEAN success BOOLEAN NOT NULL
) )
`) `)
if err != nil { if err != nil {
@@ -57,13 +58,15 @@ func (s *Store) createPostgresSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_uptimes ( CREATE TABLE IF NOT EXISTS endpoint_uptimes (
endpoint_uptime_id BIGSERIAL PRIMARY KEY, endpoint_uptime_id BIGSERIAL PRIMARY KEY,
endpoint_id BIGINT REFERENCES endpoints(endpoint_id) ON DELETE CASCADE, endpoint_id BIGINT NOT NULL REFERENCES endpoints(endpoint_id) ON DELETE CASCADE,
hour_unix_timestamp BIGINT, hour_unix_timestamp BIGINT NOT NULL,
total_executions BIGINT, total_executions BIGINT NOT NULL,
successful_executions BIGINT, successful_executions BIGINT NOT NULL,
total_response_time BIGINT, total_response_time BIGINT NOT NULL,
UNIQUE(endpoint_id, hour_unix_timestamp) UNIQUE(endpoint_id, hour_unix_timestamp)
) )
`) `)
// Silent table modifications
_, _ = s.db.Exec(`ALTER TABLE endpoint_results ADD IF NOT EXISTS domain_expiration BIGINT NOT NULL DEFAULT 0`)
return err return err
} }
+27 -24
View File
@@ -5,8 +5,8 @@ func (s *Store) createSQLiteSchema() error {
CREATE TABLE IF NOT EXISTS endpoints ( CREATE TABLE IF NOT EXISTS endpoints (
endpoint_id INTEGER PRIMARY KEY, endpoint_id INTEGER PRIMARY KEY,
endpoint_key TEXT UNIQUE, endpoint_key TEXT UNIQUE,
endpoint_name TEXT, endpoint_name TEXT NOT NULL,
endpoint_group TEXT, endpoint_group TEXT NOT NULL,
UNIQUE(endpoint_name, endpoint_group) UNIQUE(endpoint_name, endpoint_group)
) )
`) `)
@@ -16,9 +16,9 @@ func (s *Store) createSQLiteSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_events ( CREATE TABLE IF NOT EXISTS endpoint_events (
endpoint_event_id INTEGER PRIMARY KEY, endpoint_event_id INTEGER PRIMARY KEY,
endpoint_id INTEGER REFERENCES endpoints(endpoint_id) ON DELETE CASCADE, endpoint_id INTEGER NOT NULL REFERENCES endpoints(endpoint_id) ON DELETE CASCADE,
event_type TEXT, event_type TEXT NOT NULL,
event_timestamp TIMESTAMP event_timestamp TIMESTAMP NOT NULL
) )
`) `)
if err != nil { if err != nil {
@@ -27,17 +27,18 @@ func (s *Store) createSQLiteSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_results ( CREATE TABLE IF NOT EXISTS endpoint_results (
endpoint_result_id INTEGER PRIMARY KEY, endpoint_result_id INTEGER PRIMARY KEY,
endpoint_id INTEGER REFERENCES endpoints(endpoint_id) ON DELETE CASCADE, endpoint_id INTEGER NOT NULL REFERENCES endpoints(endpoint_id) ON DELETE CASCADE,
success INTEGER, success INTEGER NOT NULL,
errors TEXT, errors TEXT NOT NULL,
connected INTEGER, connected INTEGER NOT NULL,
status INTEGER, status INTEGER NOT NULL,
dns_rcode TEXT, dns_rcode TEXT NOT NULL,
certificate_expiration INTEGER, certificate_expiration INTEGER NOT NULL,
hostname TEXT, domain_expiration INTEGER NOT NULL,
ip TEXT, hostname TEXT NOT NULL,
duration INTEGER, ip TEXT NOT NULL,
timestamp TIMESTAMP duration INTEGER NOT NULL,
timestamp TIMESTAMP NOT NULL
) )
`) `)
if err != nil { if err != nil {
@@ -46,9 +47,9 @@ func (s *Store) createSQLiteSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_result_conditions ( CREATE TABLE IF NOT EXISTS endpoint_result_conditions (
endpoint_result_condition_id INTEGER PRIMARY KEY, endpoint_result_condition_id INTEGER PRIMARY KEY,
endpoint_result_id INTEGER REFERENCES endpoint_results(endpoint_result_id) ON DELETE CASCADE, endpoint_result_id INTEGER NOT NULL REFERENCES endpoint_results(endpoint_result_id) ON DELETE CASCADE,
condition TEXT, condition TEXT NOT NULL,
success INTEGER success INTEGER NOT NULL
) )
`) `)
if err != nil { if err != nil {
@@ -57,13 +58,15 @@ func (s *Store) createSQLiteSchema() error {
_, err = s.db.Exec(` _, err = s.db.Exec(`
CREATE TABLE IF NOT EXISTS endpoint_uptimes ( CREATE TABLE IF NOT EXISTS endpoint_uptimes (
endpoint_uptime_id INTEGER PRIMARY KEY, endpoint_uptime_id INTEGER PRIMARY KEY,
endpoint_id INTEGER REFERENCES endpoints(endpoint_id) ON DELETE CASCADE, endpoint_id INTEGER NOT NULL REFERENCES endpoints(endpoint_id) ON DELETE CASCADE,
hour_unix_timestamp INTEGER, hour_unix_timestamp INTEGER NOT NULL,
total_executions INTEGER, total_executions INTEGER NOT NULL,
successful_executions INTEGER, successful_executions INTEGER NOT NULL,
total_response_time INTEGER, total_response_time INTEGER NOT NULL,
UNIQUE(endpoint_id, hour_unix_timestamp) UNIQUE(endpoint_id, hour_unix_timestamp)
) )
`) `)
// Silent table modifications TODO: Remove this
_, _ = s.db.Exec(`ALTER TABLE endpoint_results ADD domain_expiration INTEGER NOT NULL DEFAULT 0`)
return err return err
} }
+83 -5
View File
@@ -13,6 +13,7 @@ import (
"github.com/TwiN/gatus/v4/storage/store/common" "github.com/TwiN/gatus/v4/storage/store/common"
"github.com/TwiN/gatus/v4/storage/store/common/paging" "github.com/TwiN/gatus/v4/storage/store/common/paging"
"github.com/TwiN/gatus/v4/util" "github.com/TwiN/gatus/v4/util"
"github.com/TwiN/gocache/v2"
_ "github.com/lib/pq" _ "github.com/lib/pq"
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
) )
@@ -32,6 +33,8 @@ const (
resultsCleanUpThreshold = common.MaximumNumberOfResults + 10 // Maximum number of results before triggering a clean up resultsCleanUpThreshold = common.MaximumNumberOfResults + 10 // Maximum number of results before triggering a clean up
uptimeRetention = 7 * 24 * time.Hour uptimeRetention = 7 * 24 * time.Hour
cacheTTL = 10 * time.Minute
) )
var ( var (
@@ -49,10 +52,14 @@ type Store struct {
driver, path string driver, path string
db *sql.DB db *sql.DB
// writeThroughCache is a cache used to drastically decrease read latency by pre-emptively
// caching writes as they happen. If nil, writes are not cached.
writeThroughCache *gocache.Cache
} }
// NewStore initializes the database and creates the schema if it doesn't already exist in the path specified // NewStore initializes the database and creates the schema if it doesn't already exist in the path specified
func NewStore(driver, path string) (*Store, error) { func NewStore(driver, path string, caching bool) (*Store, error) {
if len(driver) == 0 { if len(driver) == 0 {
return nil, ErrDatabaseDriverNotSpecified return nil, ErrDatabaseDriverNotSpecified
} }
@@ -79,6 +86,9 @@ func NewStore(driver, path string) (*Store, error) {
_ = store.db.Close() _ = store.db.Close()
return nil, err return nil, err
} }
if caching {
store.writeThroughCache = gocache.NewCache().WithMaxSize(10000)
}
return store, nil return store, nil
} }
@@ -323,6 +333,19 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
} }
} }
} }
if s.writeThroughCache != nil {
cacheKeysToRefresh := s.writeThroughCache.GetKeysByPattern(endpoint.Key()+"*", 0)
for _, cacheKey := range cacheKeysToRefresh {
s.writeThroughCache.Delete(cacheKey)
endpointKey, params, err := extractKeyAndParamsFromCacheKey(cacheKey)
if err != nil {
log.Printf("[sql][Insert] Silently deleting cache key %s instead of refreshing due to error: %s", cacheKey, err.Error())
continue
}
// Retrieve the endpoint status by key, which will in turn refresh the cache
_, _ = s.getEndpointStatusByKey(tx, endpointKey, params)
}
}
if err = tx.Commit(); err != nil { if err = tx.Commit(); err != nil {
_ = tx.Rollback() _ = tx.Rollback()
} }
@@ -350,6 +373,11 @@ func (s *Store) DeleteAllEndpointStatusesNotInKeys(keys []string) int {
log.Printf("[sql][DeleteAllEndpointStatusesNotInKeys] Failed to delete rows that do not belong to any of keys=%v: %s", keys, err.Error()) log.Printf("[sql][DeleteAllEndpointStatusesNotInKeys] Failed to delete rows that do not belong to any of keys=%v: %s", keys, err.Error())
return 0 return 0
} }
if s.writeThroughCache != nil {
// It's easier to just wipe out the entire cache than to try to find all keys that are not in the keys list
_ = s.writeThroughCache.DeleteKeysByPattern("*")
}
// Return number of rows deleted
rowsAffects, _ := result.RowsAffected() rowsAffects, _ := result.RowsAffected()
return int(rowsAffects) return int(rowsAffects)
} }
@@ -357,6 +385,9 @@ func (s *Store) DeleteAllEndpointStatusesNotInKeys(keys []string) int {
// Clear deletes everything from the store // Clear deletes everything from the store
func (s *Store) Clear() { func (s *Store) Clear() {
_, _ = s.db.Exec("DELETE FROM endpoints") _, _ = s.db.Exec("DELETE FROM endpoints")
if s.writeThroughCache != nil {
_ = s.writeThroughCache.DeleteKeysByPattern("*")
}
} }
// Save does nothing, because this store is immediately persistent. // Save does nothing, because this store is immediately persistent.
@@ -367,6 +398,10 @@ func (s *Store) Save() error {
// Close the database handle // Close the database handle
func (s *Store) Close() { func (s *Store) Close() {
_ = s.db.Close() _ = s.db.Close()
if s.writeThroughCache != nil {
// Clear the cache too. If the store's been closed, we don't want to keep the cache around.
_ = s.writeThroughCache.DeleteKeysByPattern("*")
}
} }
// insertEndpoint inserts an endpoint in the store and returns the generated id of said endpoint // insertEndpoint inserts an endpoint in the store and returns the generated id of said endpoint
@@ -404,8 +439,8 @@ func (s *Store) insertEndpointResult(tx *sql.Tx, endpointID int64, result *core.
var endpointResultID int64 var endpointResultID int64
err := tx.QueryRow( err := tx.QueryRow(
` `
INSERT INTO endpoint_results (endpoint_id, success, errors, connected, status, dns_rcode, certificate_expiration, hostname, ip, duration, timestamp) INSERT INTO endpoint_results (endpoint_id, success, errors, connected, status, dns_rcode, certificate_expiration, domain_expiration, hostname, ip, duration, timestamp)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING endpoint_result_id RETURNING endpoint_result_id
`, `,
endpointID, endpointID,
@@ -415,6 +450,7 @@ func (s *Store) insertEndpointResult(tx *sql.Tx, endpointID int64, result *core.
result.HTTPStatus, result.HTTPStatus,
result.DNSRCode, result.DNSRCode,
result.CertificateExpiration, result.CertificateExpiration,
result.DomainExpiration,
result.Hostname, result.Hostname,
result.IP, result.IP,
result.Duration, result.Duration,
@@ -479,6 +515,15 @@ func (s *Store) getAllEndpointKeys(tx *sql.Tx) (keys []string, err error) {
} }
func (s *Store) getEndpointStatusByKey(tx *sql.Tx, key string, parameters *paging.EndpointStatusParams) (*core.EndpointStatus, error) { func (s *Store) getEndpointStatusByKey(tx *sql.Tx, key string, parameters *paging.EndpointStatusParams) (*core.EndpointStatus, error) {
var cacheKey string
if s.writeThroughCache != nil {
cacheKey = generateCacheKey(key, parameters)
if cachedEndpointStatus, exists := s.writeThroughCache.Get(cacheKey); exists {
if castedCachedEndpointStatus, ok := cachedEndpointStatus.(*core.EndpointStatus); ok {
return castedCachedEndpointStatus, nil
}
}
}
endpointID, group, endpointName, err := s.getEndpointIDGroupAndNameByKey(tx, key) endpointID, group, endpointName, err := s.getEndpointIDGroupAndNameByKey(tx, key)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -494,6 +539,9 @@ func (s *Store) getEndpointStatusByKey(tx *sql.Tx, key string, parameters *pagin
log.Printf("[sql][getEndpointStatusByKey] Failed to retrieve results for key=%s: %s", key, err.Error()) log.Printf("[sql][getEndpointStatusByKey] Failed to retrieve results for key=%s: %s", key, err.Error())
} }
} }
if s.writeThroughCache != nil {
s.writeThroughCache.SetWithTTL(cacheKey, endpointStatus, cacheTTL)
}
return endpointStatus, nil return endpointStatus, nil
} }
@@ -543,7 +591,7 @@ func (s *Store) getEndpointEventsByEndpointID(tx *sql.Tx, endpointID int64, page
func (s *Store) getEndpointResultsByEndpointID(tx *sql.Tx, endpointID int64, page, pageSize int) (results []*core.Result, err error) { func (s *Store) getEndpointResultsByEndpointID(tx *sql.Tx, endpointID int64, page, pageSize int) (results []*core.Result, err error) {
rows, err := tx.Query( rows, err := tx.Query(
` `
SELECT endpoint_result_id, success, errors, connected, status, dns_rcode, certificate_expiration, hostname, ip, duration, timestamp SELECT endpoint_result_id, success, errors, connected, status, dns_rcode, certificate_expiration, domain_expiration, hostname, ip, duration, timestamp
FROM endpoint_results FROM endpoint_results
WHERE endpoint_id = $1 WHERE endpoint_id = $1
ORDER BY endpoint_result_id DESC -- Normally, we'd sort by timestamp, but sorting by endpoint_result_id is faster ORDER BY endpoint_result_id DESC -- Normally, we'd sort by timestamp, but sorting by endpoint_result_id is faster
@@ -561,7 +609,11 @@ func (s *Store) getEndpointResultsByEndpointID(tx *sql.Tx, endpointID int64, pag
result := &core.Result{} result := &core.Result{}
var id int64 var id int64
var joinedErrors string var joinedErrors string
_ = rows.Scan(&id, &result.Success, &joinedErrors, &result.Connected, &result.HTTPStatus, &result.DNSRCode, &result.CertificateExpiration, &result.Hostname, &result.IP, &result.Duration, &result.Timestamp) err = rows.Scan(&id, &result.Success, &joinedErrors, &result.Connected, &result.HTTPStatus, &result.DNSRCode, &result.CertificateExpiration, &result.DomainExpiration, &result.Hostname, &result.IP, &result.Duration, &result.Timestamp)
if err != nil {
log.Printf("[sql][getEndpointResultsByEndpointID] Silently failed to retrieve endpoint result for endpointID=%d: %s", endpointID, err.Error())
err = nil
}
if len(joinedErrors) != 0 { if len(joinedErrors) != 0 {
result.Errors = strings.Split(joinedErrors, arraySeparator) result.Errors = strings.Split(joinedErrors, arraySeparator)
} }
@@ -788,3 +840,29 @@ func (s *Store) deleteOldUptimeEntries(tx *sql.Tx, endpointID int64, maxAge time
_, err := tx.Exec("DELETE FROM endpoint_uptimes WHERE endpoint_id = $1 AND hour_unix_timestamp < $2", endpointID, maxAge.Unix()) _, err := tx.Exec("DELETE FROM endpoint_uptimes WHERE endpoint_id = $1 AND hour_unix_timestamp < $2", endpointID, maxAge.Unix())
return err return err
} }
func generateCacheKey(endpointKey string, p *paging.EndpointStatusParams) string {
return fmt.Sprintf("%s-%d-%d-%d-%d", endpointKey, p.EventsPage, p.EventsPageSize, p.ResultsPage, p.ResultsPageSize)
}
func extractKeyAndParamsFromCacheKey(cacheKey string) (string, *paging.EndpointStatusParams, error) {
parts := strings.Split(cacheKey, "-")
if len(parts) < 5 {
return "", nil, fmt.Errorf("invalid cache key: %s", cacheKey)
}
params := &paging.EndpointStatusParams{}
var err error
if params.EventsPage, err = strconv.Atoi(parts[len(parts)-4]); err != nil {
return "", nil, fmt.Errorf("invalid cache key: %w", err)
}
if params.EventsPageSize, err = strconv.Atoi(parts[len(parts)-3]); err != nil {
return "", nil, fmt.Errorf("invalid cache key: %w", err)
}
if params.ResultsPage, err = strconv.Atoi(parts[len(parts)-2]); err != nil {
return "", nil, fmt.Errorf("invalid cache key: %w", err)
}
if params.ResultsPageSize, err = strconv.Atoi(parts[len(parts)-1]); err != nil {
return "", nil, fmt.Errorf("invalid cache key: %w", err)
}
return strings.Join(parts[:len(parts)-4], "-"), params, nil
}
+99 -12
View File
@@ -81,13 +81,13 @@ var (
) )
func TestNewStore(t *testing.T) { func TestNewStore(t *testing.T) {
if _, err := NewStore("", "TestNewStore.db"); err != ErrDatabaseDriverNotSpecified { if _, err := NewStore("", "TestNewStore.db", false); err != ErrDatabaseDriverNotSpecified {
t.Error("expected error due to blank driver parameter") t.Error("expected error due to blank driver parameter")
} }
if _, err := NewStore("sqlite", ""); err != ErrPathNotSpecified { if _, err := NewStore("sqlite", "", false); err != ErrPathNotSpecified {
t.Error("expected error due to blank path parameter") t.Error("expected error due to blank path parameter")
} }
if store, err := NewStore("sqlite", t.TempDir()+"/TestNewStore.db"); err != nil { if store, err := NewStore("sqlite", t.TempDir()+"/TestNewStore.db", false); err != nil {
t.Error("shouldn't have returned any error, got", err.Error()) t.Error("shouldn't have returned any error, got", err.Error())
} else { } else {
_ = store.db.Close() _ = store.db.Close()
@@ -95,7 +95,7 @@ func TestNewStore(t *testing.T) {
} }
func TestStore_InsertCleansUpOldUptimeEntriesProperly(t *testing.T) { func TestStore_InsertCleansUpOldUptimeEntriesProperly(t *testing.T) {
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpOldUptimeEntriesProperly.db") store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpOldUptimeEntriesProperly.db", false)
defer store.Close() defer store.Close()
now := time.Now().Round(time.Minute) now := time.Now().Round(time.Minute)
now = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location()) now = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
@@ -152,7 +152,7 @@ func TestStore_InsertCleansUpOldUptimeEntriesProperly(t *testing.T) {
} }
func TestStore_InsertCleansUpEventsAndResultsProperly(t *testing.T) { func TestStore_InsertCleansUpEventsAndResultsProperly(t *testing.T) {
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpEventsAndResultsProperly.db") store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpEventsAndResultsProperly.db", false)
defer store.Close() defer store.Close()
for i := 0; i < resultsCleanUpThreshold+eventsCleanUpThreshold; i++ { for i := 0; i < resultsCleanUpThreshold+eventsCleanUpThreshold; i++ {
store.Insert(&testEndpoint, &testSuccessfulResult) store.Insert(&testEndpoint, &testSuccessfulResult)
@@ -170,7 +170,7 @@ func TestStore_InsertCleansUpEventsAndResultsProperly(t *testing.T) {
func TestStore_Persistence(t *testing.T) { func TestStore_Persistence(t *testing.T) {
path := t.TempDir() + "/TestStore_Persistence.db" path := t.TempDir() + "/TestStore_Persistence.db"
store, _ := NewStore("sqlite", path) store, _ := NewStore("sqlite", path, false)
store.Insert(&testEndpoint, &testSuccessfulResult) store.Insert(&testEndpoint, &testSuccessfulResult)
store.Insert(&testEndpoint, &testUnsuccessfulResult) store.Insert(&testEndpoint, &testUnsuccessfulResult)
if uptime, _ := store.GetUptimeByKey(testEndpoint.Key(), time.Now().Add(-time.Hour), time.Now()); uptime != 0.5 { if uptime, _ := store.GetUptimeByKey(testEndpoint.Key(), time.Now().Add(-time.Hour), time.Now()); uptime != 0.5 {
@@ -188,7 +188,7 @@ func TestStore_Persistence(t *testing.T) {
t.Fatal("sanity check failed") t.Fatal("sanity check failed")
} }
store.Close() store.Close()
store, _ = NewStore("sqlite", path) store, _ = NewStore("sqlite", path, false)
defer store.Close() defer store.Close()
ssFromNewStore, _ := store.GetEndpointStatus(testEndpoint.Group, testEndpoint.Name, paging.NewEndpointStatusParams().WithResults(1, common.MaximumNumberOfResults).WithEvents(1, common.MaximumNumberOfEvents)) ssFromNewStore, _ := store.GetEndpointStatus(testEndpoint.Group, testEndpoint.Name, paging.NewEndpointStatusParams().WithResults(1, common.MaximumNumberOfResults).WithEvents(1, common.MaximumNumberOfEvents))
if ssFromNewStore == nil || ssFromNewStore.Group != "group" || ssFromNewStore.Name != "name" || len(ssFromNewStore.Events) != 3 || len(ssFromNewStore.Results) != 2 { if ssFromNewStore == nil || ssFromNewStore.Group != "group" || ssFromNewStore.Name != "name" || len(ssFromNewStore.Events) != 3 || len(ssFromNewStore.Results) != 2 {
@@ -252,7 +252,7 @@ func TestStore_Persistence(t *testing.T) {
} }
func TestStore_Save(t *testing.T) { func TestStore_Save(t *testing.T) {
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_Save.db") store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_Save.db", false)
defer store.Close() defer store.Close()
if store.Save() != nil { if store.Save() != nil {
t.Error("Save shouldn't do anything for this store") t.Error("Save shouldn't do anything for this store")
@@ -262,7 +262,7 @@ func TestStore_Save(t *testing.T) {
// Note that are much more extensive tests in /storage/store/store_test.go. // Note that are much more extensive tests in /storage/store/store_test.go.
// This test is simply an extra sanity check // This test is simply an extra sanity check
func TestStore_SanityCheck(t *testing.T) { func TestStore_SanityCheck(t *testing.T) {
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_SanityCheck.db") store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_SanityCheck.db", false)
defer store.Close() defer store.Close()
store.Insert(&testEndpoint, &testSuccessfulResult) store.Insert(&testEndpoint, &testSuccessfulResult)
endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams()) endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams())
@@ -306,7 +306,7 @@ func TestStore_SanityCheck(t *testing.T) {
// TestStore_InvalidTransaction tests what happens if an invalid transaction is passed as parameter // TestStore_InvalidTransaction tests what happens if an invalid transaction is passed as parameter
func TestStore_InvalidTransaction(t *testing.T) { func TestStore_InvalidTransaction(t *testing.T) {
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InvalidTransaction.db") store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InvalidTransaction.db", false)
defer store.Close() defer store.Close()
tx, _ := store.db.Begin() tx, _ := store.db.Begin()
tx.Commit() tx.Commit()
@@ -364,7 +364,7 @@ func TestStore_InvalidTransaction(t *testing.T) {
} }
func TestStore_NoRows(t *testing.T) { func TestStore_NoRows(t *testing.T) {
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_NoRows.db") store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_NoRows.db", false)
defer store.Close() defer store.Close()
tx, _ := store.db.Begin() tx, _ := store.db.Begin()
defer tx.Rollback() defer tx.Rollback()
@@ -378,7 +378,7 @@ func TestStore_NoRows(t *testing.T) {
// This tests very unlikely cases where a table is deleted. // This tests very unlikely cases where a table is deleted.
func TestStore_BrokenSchema(t *testing.T) { func TestStore_BrokenSchema(t *testing.T) {
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_BrokenSchema.db") store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_BrokenSchema.db", false)
defer store.Close() defer store.Close()
if err := store.Insert(&testEndpoint, &testSuccessfulResult); err != nil { if err := store.Insert(&testEndpoint, &testSuccessfulResult); err != nil {
t.Fatal("expected no error, got", err.Error()) t.Fatal("expected no error, got", err.Error())
@@ -391,6 +391,7 @@ func TestStore_BrokenSchema(t *testing.T) {
} }
// Break // Break
_, _ = store.db.Exec("DROP TABLE endpoints") _, _ = store.db.Exec("DROP TABLE endpoints")
// And now we'll try to insert something in our broken schema
if err := store.Insert(&testEndpoint, &testSuccessfulResult); err == nil { if err := store.Insert(&testEndpoint, &testSuccessfulResult); err == nil {
t.Fatal("expected an error") t.Fatal("expected an error")
} }
@@ -477,3 +478,89 @@ func TestStore_BrokenSchema(t *testing.T) {
t.Fatal("expected an error") t.Fatal("expected an error")
} }
} }
func TestCacheKey(t *testing.T) {
scenarios := []struct {
endpointKey string
params paging.EndpointStatusParams
overrideCacheKey string
expectedCacheKey string
wantErr bool
}{
{
endpointKey: "simple",
params: paging.EndpointStatusParams{EventsPage: 1, EventsPageSize: 2, ResultsPage: 3, ResultsPageSize: 4},
expectedCacheKey: "simple-1-2-3-4",
wantErr: false,
},
{
endpointKey: "with-hyphen",
params: paging.EndpointStatusParams{EventsPage: 0, EventsPageSize: 0, ResultsPage: 1, ResultsPageSize: 20},
expectedCacheKey: "with-hyphen-0-0-1-20",
wantErr: false,
},
{
endpointKey: "with-multiple-hyphens",
params: paging.EndpointStatusParams{EventsPage: 0, EventsPageSize: 0, ResultsPage: 2, ResultsPageSize: 20},
expectedCacheKey: "with-multiple-hyphens-0-0-2-20",
wantErr: false,
},
{
overrideCacheKey: "invalid-a-2-3-4",
wantErr: true,
},
{
overrideCacheKey: "invalid-1-a-3-4",
wantErr: true,
},
{
overrideCacheKey: "invalid-1-2-a-4",
wantErr: true,
},
{
overrideCacheKey: "invalid-1-2-3-a",
wantErr: true,
},
{
overrideCacheKey: "notenoughhyphen1-2-3-4",
wantErr: true,
},
}
for _, scenario := range scenarios {
t.Run(scenario.expectedCacheKey+scenario.overrideCacheKey, func(t *testing.T) {
var cacheKey string
if len(scenario.overrideCacheKey) > 0 {
cacheKey = scenario.overrideCacheKey
} else {
cacheKey = generateCacheKey(scenario.endpointKey, &scenario.params)
if cacheKey != scenario.expectedCacheKey {
t.Errorf("expected %s, got %s", scenario.expectedCacheKey, cacheKey)
}
}
extractedEndpointKey, extractedParams, err := extractKeyAndParamsFromCacheKey(cacheKey)
if (err != nil) != scenario.wantErr {
t.Errorf("expected error %v, got %v", scenario.wantErr, err)
return
}
if err != nil {
// If there's an error, we don't need to check the extracted values
return
}
if extractedEndpointKey != scenario.endpointKey {
t.Errorf("expected endpointKey %s, got %s", scenario.endpointKey, extractedEndpointKey)
}
if extractedParams.EventsPage != scenario.params.EventsPage {
t.Errorf("expected EventsPage %d, got %d", scenario.params.EventsPage, extractedParams.EventsPage)
}
if extractedParams.EventsPageSize != scenario.params.EventsPageSize {
t.Errorf("expected EventsPageSize %d, got %d", scenario.params.EventsPageSize, extractedParams.EventsPageSize)
}
if extractedParams.ResultsPage != scenario.params.ResultsPage {
t.Errorf("expected ResultsPage %d, got %d", scenario.params.ResultsPage, extractedParams.ResultsPage)
}
if extractedParams.ResultsPageSize != scenario.params.ResultsPageSize {
t.Errorf("expected ResultsPageSize %d, got %d", scenario.params.ResultsPageSize, extractedParams.ResultsPageSize)
}
})
}
}
+3 -11
View File
@@ -12,7 +12,7 @@ import (
"github.com/TwiN/gatus/v4/storage/store/sql" "github.com/TwiN/gatus/v4/storage/store/sql"
) )
// Store is the interface that each stores should implement // Store is the interface that each store should implement
type Store interface { type Store interface {
// GetAllEndpointStatuses returns the JSON encoding of all monitored core.EndpointStatus // GetAllEndpointStatuses returns the JSON encoding of all monitored core.EndpointStatus
// with a subset of core.Result defined by the page and pageSize parameters // with a subset of core.Result defined by the page and pageSize parameters
@@ -103,22 +103,14 @@ func Initialize(cfg *storage.Config) error {
ctx, cancelFunc = context.WithCancel(context.Background()) ctx, cancelFunc = context.WithCancel(context.Background())
switch cfg.Type { switch cfg.Type {
case storage.TypeSQLite, storage.TypePostgres: case storage.TypeSQLite, storage.TypePostgres:
store, err = sql.NewStore(string(cfg.Type), cfg.Path) store, err = sql.NewStore(string(cfg.Type), cfg.Path, cfg.Caching)
if err != nil { if err != nil {
return err return err
} }
case storage.TypeMemory: case storage.TypeMemory:
fallthrough fallthrough
default: default:
if len(cfg.Path) > 0 { store, _ = memory.NewStore()
store, err = memory.NewStore(cfg.Path)
if err != nil {
return err
}
go autoSave(ctx, store, 7*time.Minute)
} else {
store, _ = memory.NewStore("")
}
} }
return nil return nil
} }
+6 -6
View File
@@ -12,11 +12,11 @@ import (
) )
func BenchmarkStore_GetAllEndpointStatuses(b *testing.B) { func BenchmarkStore_GetAllEndpointStatuses(b *testing.B) {
memoryStore, err := memory.NewStore("") memoryStore, err := memory.NewStore()
if err != nil { if err != nil {
b.Fatal("failed to create store:", err.Error()) b.Fatal("failed to create store:", err.Error())
} }
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetAllEndpointStatuses.db") sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetAllEndpointStatuses.db", false)
if err != nil { if err != nil {
b.Fatal("failed to create store:", err.Error()) b.Fatal("failed to create store:", err.Error())
} }
@@ -81,11 +81,11 @@ func BenchmarkStore_GetAllEndpointStatuses(b *testing.B) {
} }
func BenchmarkStore_Insert(b *testing.B) { func BenchmarkStore_Insert(b *testing.B) {
memoryStore, err := memory.NewStore("") memoryStore, err := memory.NewStore()
if err != nil { if err != nil {
b.Fatal("failed to create store:", err.Error()) b.Fatal("failed to create store:", err.Error())
} }
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_Insert.db") sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_Insert.db", false)
if err != nil { if err != nil {
b.Fatal("failed to create store:", err.Error()) b.Fatal("failed to create store:", err.Error())
} }
@@ -153,11 +153,11 @@ func BenchmarkStore_Insert(b *testing.B) {
} }
func BenchmarkStore_GetEndpointStatusByKey(b *testing.B) { func BenchmarkStore_GetEndpointStatusByKey(b *testing.B) {
memoryStore, err := memory.NewStore("") memoryStore, err := memory.NewStore()
if err != nil { if err != nil {
b.Fatal("failed to create store:", err.Error()) b.Fatal("failed to create store:", err.Error())
} }
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetEndpointStatusByKey.db") sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetEndpointStatusByKey.db", false)
if err != nil { if err != nil {
b.Fatal("failed to create store:", err.Error()) b.Fatal("failed to create store:", err.Error())
} }
+14 -6
View File
@@ -89,11 +89,15 @@ type Scenario struct {
} }
func initStoresAndBaseScenarios(t *testing.T, testName string) []*Scenario { func initStoresAndBaseScenarios(t *testing.T, testName string) []*Scenario {
memoryStore, err := memory.NewStore("") memoryStore, err := memory.NewStore()
if err != nil { if err != nil {
t.Fatal("failed to create store:", err.Error()) t.Fatal("failed to create store:", err.Error())
} }
sqliteStore, err := sql.NewStore("sqlite", t.TempDir()+"/"+testName+".db") sqliteStore, err := sql.NewStore("sqlite", t.TempDir()+"/"+testName+".db", false)
if err != nil {
t.Fatal("failed to create store:", err.Error())
}
sqliteStoreWithCaching, err := sql.NewStore("sqlite", t.TempDir()+"/"+testName+"-with-caching.db", true)
if err != nil { if err != nil {
t.Fatal("failed to create store:", err.Error()) t.Fatal("failed to create store:", err.Error())
} }
@@ -106,6 +110,10 @@ func initStoresAndBaseScenarios(t *testing.T, testName string) []*Scenario {
Name: "sqlite", Name: "sqlite",
Store: sqliteStore, Store: sqliteStore,
}, },
{
Name: "sqlite-with-caching",
Store: sqliteStoreWithCaching,
},
} }
} }
@@ -528,17 +536,17 @@ func TestStore_DeleteAllEndpointStatusesNotInKeys(t *testing.T) {
scenario.Store.Insert(&firstEndpoint, result) scenario.Store.Insert(&firstEndpoint, result)
scenario.Store.Insert(&secondEndpoint, result) scenario.Store.Insert(&secondEndpoint, result)
if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil { if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
t.Fatal("firstEndpoint should exist") t.Fatal("firstEndpoint should exist, got", ss)
} }
if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil { if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
t.Fatal("secondEndpoint should exist") t.Fatal("secondEndpoint should exist, got", ss)
} }
scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{firstEndpoint.Key()}) scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{firstEndpoint.Key()})
if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil { if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
t.Error("secondEndpoint should've been deleted") t.Error("secondEndpoint should still exist, got", ss)
} }
if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss != nil { if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss != nil {
t.Error("firstEndpoint should still exist") t.Error("firstEndpoint should have been deleted, got", ss)
} }
// Delete everything // Delete everything
scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{}) scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{})
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 TwiN
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-9
View File
@@ -1,9 +0,0 @@
MIT License
Copyright (c) 2021 TwiN
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+52 -3
View File
@@ -1,6 +1,6 @@
# g8 # g8
![build](https://github.com/TwiN/g8/workflows/build/badge.svg?branch=master) ![test](https://github.com/TwiN/g8/workflows/test/badge.svg?branch=master)
[![Go Report Card](https://goreportcard.com/badge/github.com/TwiN/g8)](https://goreportcard.com/report/github.com/TwiN/g8) [![Go Report Card](https://goreportcard.com/badge/github.com/TwiN/g8)](https://goreportcard.com/report/github.com/TwiN/g8)
[![codecov](https://codecov.io/gh/TwiN/g8/branch/master/graph/badge.svg)](https://codecov.io/gh/TwiN/g8) [![codecov](https://codecov.io/gh/TwiN/g8/branch/master/graph/badge.svg)](https://codecov.io/gh/TwiN/g8)
[![Go version](https://img.shields.io/github/go-mod/go-version/TwiN/g8.svg)](https://github.com/TwiN/g8) [![Go version](https://img.shields.io/github/go-mod/go-version/TwiN/g8.svg)](https://github.com/TwiN/g8)
@@ -177,13 +177,42 @@ have the `backup` permission:
router.Handle("/backup", gate.ProtectWithPermissions(&testHandler{}, []string{"read", "backup"})) router.Handle("/backup", gate.ProtectWithPermissions(&testHandler{}, []string{"read", "backup"}))
``` ```
If you're using an HTTP library that supports middlewares like [mux](https://github.com/gorilla/mux), you can protect
an entire group of handlers instead using `gate.Protect` or `gate.PermissionMiddleware()`:
```go
router := mux.NewRouter()
userRouter := router.PathPrefix("/").Subrouter()
userRouter.Use(gate.Protect)
userRouter.HandleFunc("/api/v1/users/me", getUserProfile).Methods("GET")
userRouter.HandleFunc("/api/v1/users/me/friends", getUserFriends).Methods("GET")
userRouter.HandleFunc("/api/v1/users/me/email", updateUserEmail).Methods("PATCH")
adminRouter := router.PathPrefix("/").Subrouter()
adminRouter.Use(gate.PermissionMiddleware("admin"))
adminRouter.HandleFunc("/api/v1/users/{id}/ban", banUserByID).Methods("POST")
adminRouter.HandleFunc("/api/v1/users/{id}/delete", deleteUserByID).Methods("DELETE")
```
## Rate limiting ## Rate limiting
To add a rate limit of 100 requests per second: To add a rate limit of 100 requests per second:
``` ```go
gate := g8.New().WithRateLimit(100) gate := g8.New().WithRateLimit(100)
``` ```
## Special use cases
## Accessing the token from the protected handlers
If you need to access the token from the handlers you are protecting with g8, you can retrieve it from the
request context by using the key `g8.TokenContextKey`:
```go
http.Handle("/handle", gate.ProtectFunc(func(w http.ResponseWriter, r *http.Request) {
token, _ := r.Context().Value(g8.TokenContextKey).(string)
// ...
}))
```
## Examples
### Protecting a handler using session cookie ### Protecting a handler using session cookie
If you want to only allow authenticated users to access a handler, you can use a custom token extractor function If you want to only allow authenticated users to access a handler, you can use a custom token extractor function
combined with a client provider. combined with a client provider.
@@ -236,3 +265,23 @@ http.Handle("/handle", gate.ProtectFunc(func(w http.ResponseWriter, r *http.Requ
// ... // ...
})) }))
``` ```
### Using a custom header
The logic is the same as the example above:
```go
customTokenExtractorFunc := func(request *http.Request) string {
return request.Header.Get("X-API-Token")
}
clientProvider := g8.NewClientProvider(func(token string) *g8.Client {
// We'll assume that the following function calls your database and returns a struct "User" that
// has the user's token as well as the permissions granted to said user
user := database.GetUserByToken(token)
if user != nil {
return g8.NewClient(user.Token).WithPermissions(user.Permissions)
}
return nil
})
authorizationService := g8.NewAuthorizationService().WithClientProvider(clientProvider)
gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc)
```
+55 -34
View File
@@ -66,15 +66,16 @@ func (gate *Gate) WithCustomUnauthorizedResponseBody(unauthorizedResponseBody []
// If a custom token extractor is not specified, the token will be extracted from the Authorization header. // If a custom token extractor is not specified, the token will be extracted from the Authorization header.
// //
// For instance, if you're using a session cookie, you can extract the token from the cookie like so: // For instance, if you're using a session cookie, you can extract the token from the cookie like so:
// authorizationService := g8.NewAuthorizationService() //
// customTokenExtractorFunc := func(request *http.Request) string { // authorizationService := g8.NewAuthorizationService()
// sessionCookie, err := request.Cookie("session") // customTokenExtractorFunc := func(request *http.Request) string {
// if err != nil { // sessionCookie, err := request.Cookie("session")
// return "" // if err != nil {
// } // return ""
// return sessionCookie.Value // }
// } // return sessionCookie.Value
// gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc) // }
// gate := g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc)
// //
// You would normally use this with a client provider that matches whatever need you have. // You would normally use this with a client provider that matches whatever need you have.
// For example, if you're using a session cookie, your client provider would retrieve the user from the session ID // For example, if you're using a session cookie, your client provider would retrieve the user from the session ID
@@ -90,8 +91,8 @@ func (gate *Gate) WithCustomTokenExtractor(customTokenExtractorFunc func(request
// WithRateLimit adds rate limiting to the Gate // WithRateLimit adds rate limiting to the Gate
// //
// If you just want to use a gate for rate limiting purposes: // If you just want to use a gate for rate limiting purposes:
// gate := g8.New().WithRateLimit(50)
// //
// gate := g8.New().WithRateLimit(50)
func (gate *Gate) WithRateLimit(maximumRequestsPerSecond int) *Gate { func (gate *Gate) WithRateLimit(maximumRequestsPerSecond int) *Gate {
gate.rateLimiter = NewRateLimiter(maximumRequestsPerSecond) gate.rateLimiter = NewRateLimiter(maximumRequestsPerSecond)
return gate return gate
@@ -102,12 +103,13 @@ func (gate *Gate) WithRateLimit(maximumRequestsPerSecond int) *Gate {
// or lack thereof. // or lack thereof.
// //
// Example: // Example:
// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token")) //
// router := http.NewServeMux() // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token"))
// // Without protection // router := http.NewServeMux()
// router.Handle("/handle", yourHandler) // // Without protection
// // With protection // router.Handle("/handle", yourHandler)
// router.Handle("/handle", gate.Protect(yourHandler)) // // With protection
// router.Handle("/handle", gate.Protect(yourHandler))
// //
// The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
func (gate *Gate) Protect(handler http.Handler) http.Handler { func (gate *Gate) Protect(handler http.Handler) http.Handler {
@@ -118,12 +120,13 @@ func (gate *Gate) Protect(handler http.Handler) http.Handler {
// as well as a slice of permissions that must be met. // as well as a slice of permissions that must be met.
// //
// Example: // Example:
// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("admin"))) //
// router := http.NewServeMux() // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("ADMIN")))
// // Without protection // router := http.NewServeMux()
// router.Handle("/handle", yourHandler) // // Without protection
// // With protection // router.Handle("/handle", yourHandler)
// router.Handle("/handle", gate.ProtectWithPermissions(yourHandler, []string{"admin"})) // // With protection
// router.Handle("/handle", gate.ProtectWithPermissions(yourHandler, []string{"admin"}))
// //
// The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
func (gate *Gate) ProtectWithPermissions(handler http.Handler, permissions []string) http.Handler { func (gate *Gate) ProtectWithPermissions(handler http.Handler, permissions []string) http.Handler {
@@ -147,12 +150,13 @@ func (gate *Gate) ProtectWithPermission(handler http.Handler, permission string)
// permissions or lack thereof. // permissions or lack thereof.
// //
// Example: // Example:
// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token")) //
// router := http.NewServeMux() // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithToken("token"))
// // Without protection // router := http.NewServeMux()
// router.HandleFunc("/handle", yourHandlerFunc) // // Without protection
// // With protection // router.HandleFunc("/handle", yourHandlerFunc)
// router.HandleFunc("/handle", gate.ProtectFunc(yourHandlerFunc)) // // With protection
// router.HandleFunc("/handle", gate.ProtectFunc(yourHandlerFunc))
// //
// The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
func (gate *Gate) ProtectFunc(handlerFunc http.HandlerFunc) http.HandlerFunc { func (gate *Gate) ProtectFunc(handlerFunc http.HandlerFunc) http.HandlerFunc {
@@ -163,12 +167,13 @@ func (gate *Gate) ProtectFunc(handlerFunc http.HandlerFunc) http.HandlerFunc {
// token as well as a slice of permissions that must be met. // token as well as a slice of permissions that must be met.
// //
// Example: // Example:
// gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("admin"))) //
// router := http.NewServeMux() // gate := g8.New().WithAuthorizationService(g8.NewAuthorizationService().WithClient(g8.NewClient("token").WithPermission("admin")))
// // Without protection // router := http.NewServeMux()
// router.HandleFunc("/handle", yourHandlerFunc) // // Without protection
// // With protection // router.HandleFunc("/handle", yourHandlerFunc)
// router.HandleFunc("/handle", gate.ProtectFuncWithPermissions(yourHandlerFunc, []string{"admin"})) // // With protection
// router.HandleFunc("/handle", gate.ProtectFuncWithPermissions(yourHandlerFunc, []string{"admin"}))
// //
// The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey // The token extracted from the request is passed to the handlerFunc request context under the key TokenContextKey
func (gate *Gate) ProtectFuncWithPermissions(handlerFunc http.HandlerFunc, permissions []string) http.HandlerFunc { func (gate *Gate) ProtectFuncWithPermissions(handlerFunc http.HandlerFunc, permissions []string) http.HandlerFunc {
@@ -215,3 +220,19 @@ func (gate *Gate) ExtractTokenFromRequest(request *http.Request) string {
} }
return strings.TrimPrefix(request.Header.Get(AuthorizationHeader), "Bearer ") return strings.TrimPrefix(request.Header.Get(AuthorizationHeader), "Bearer ")
} }
// PermissionMiddleware is a middleware that behaves like ProtectWithPermission, but it is meant to be used
// as a middleware for libraries that support such a feature.
//
// For instance, if you are using github.com/gorilla/mux, you can use PermissionMiddleware like so:
//
// router := mux.NewRouter()
// router.Use(gate.PermissionMiddleware("admin"))
// router.Handle("/admin/handle", adminHandler)
//
// If you do not want to protect a router with a specific permission, you can use Gate.Protect instead.
func (gate *Gate) PermissionMiddleware(permissions ...string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return gate.ProtectWithPermissions(next, permissions)
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2021 TwiN Copyright (c) 2022 TwiN
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+27 -26
View File
@@ -1,9 +1,9 @@
# gocache # gocache
![build](https://github.com/TwiN/gocache/workflows/build/badge.svg?branch=master) ![test](https://github.com/TwiN/gocache/workflows/test/badge.svg?branch=master)
[![Go Report Card](https://goreportcard.com/badge/github.com/TwiN/gocache)](https://goreportcard.com/report/github.com/TwiN/gocache) [![Go Report Card](https://goreportcard.com/badge/github.com/TwiN/gocache)](https://goreportcard.com/report/github.com/TwiN/gocache)
[![codecov](https://codecov.io/gh/TwiN/gocache/branch/master/graph/badge.svg)](https://codecov.io/gh/TwiN/gocache) [![codecov](https://codecov.io/gh/TwiN/gocache/branch/master/graph/badge.svg)](https://codecov.io/gh/TwiN/gocache)
[![Go version](https://img.shields.io/github/go-mod/go-version/TwiN/gocache.svg)](https://github.com/TwiN/gocache) [![Go version](https://img.shields.io/github/go-mod/go-version/TwiN/gocache.svg)](https://github.com/TwiN/gocache)
[![Go Reference](https://pkg.go.dev/badge/github.com/TwiN/gocache.svg)](https://pkg.go.dev/github.com/TwiN/gocache) [![Go Reference](https://pkg.go.dev/badge/github.com/TwiN/gocache.svg)](https://pkg.go.dev/github.com/TwiN/gocache/v2)
[![Follow TwiN](https://img.shields.io/github/followers/TwiN?label=Follow&style=social)](https://github.com/TwiN) [![Follow TwiN](https://img.shields.io/github/followers/TwiN?label=Follow&style=social)](https://github.com/TwiN)
gocache is an easy-to-use, high-performance, lightweight and thread-safe (goroutine-safe) in-memory key-value cache gocache is an easy-to-use, high-performance, lightweight and thread-safe (goroutine-safe) in-memory key-value cache
@@ -65,27 +65,28 @@ cache.StartJanitor()
``` ```
### Functions ### Functions
| Function | Description | | Function | Description |
| --------------------------------- | ----------- | |-----------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| WithMaxSize | Sets the max size of the cache. `gocache.NoMaxSize` means there is no limit. If not set, the default max size is `gocache.DefaultMaxSize`. | WithMaxSize | Sets the max size of the cache. `gocache.NoMaxSize` means there is no limit. If not set, the default max size is `gocache.DefaultMaxSize`. |
| WithMaxMemoryUsage | Sets the max memory usage of the cache. `gocache.NoMaxMemoryUsage` means there is no limit. The default behavior is to not evict based on memory usage. | WithMaxMemoryUsage | Sets the max memory usage of the cache. `gocache.NoMaxMemoryUsage` means there is no limit. The default behavior is to not evict based on memory usage. |
| WithEvictionPolicy | Sets the eviction algorithm to be used when the cache reaches the max size. If not set, the default eviction policy is `gocache.FirstInFirstOut` (FIFO). | WithEvictionPolicy | Sets the eviction algorithm to be used when the cache reaches the max size. If not set, the default eviction policy is `gocache.FirstInFirstOut` (FIFO). |
| WithForceNilInterfaceOnNilPointer | Configures whether values with a nil pointer passed to write functions should be forcefully set to nil. Defaults to true. | WithForceNilInterfaceOnNilPointer | Configures whether values with a nil pointer passed to write functions should be forcefully set to nil. Defaults to true. |
| StartJanitor | Starts the janitor, which is in charge of deleting expired cache entries in the background. | StartJanitor | Starts the janitor, which is in charge of deleting expired cache entries in the background. |
| StopJanitor | Stops the janitor. | StopJanitor | Stops the janitor. |
| Set | Same as `SetWithTTL`, but with no expiration (`gocache.NoExpiration`) | Set | Same as `SetWithTTL`, but with no expiration (`gocache.NoExpiration`) |
| SetAll | Same as `Set`, but in bulk | SetAll | Same as `Set`, but in bulk |
| SetWithTTL | Creates or updates a cache entry with the given key, value and expiration time. If the max size after the aforementioned operation is above the configured max size, the tail will be evicted. Depending on the eviction policy, the tail is defined as the oldest | SetWithTTL | Creates or updates a cache entry with the given key, value and expiration time. If the max size after the aforementioned operation is above the configured max size, the tail will be evicted. Depending on the eviction policy, the tail is defined as the oldest |
| Get | Gets a cache entry by its key. | Get | Gets a cache entry by its key. |
| GetByKeys | Gets a map of entries by their keys. The resulting map will contain all keys, even if some of the keys in the slice passed as parameter were not present in the cache. | GetByKeys | Gets a map of entries by their keys. The resulting map will contain all keys, even if some of the keys in the slice passed as parameter were not present in the cache. |
| GetAll | Gets all cache entries. | GetAll | Gets all cache entries. |
| GetKeysByPattern | Retrieves a slice of keys that matches a given pattern. | GetKeysByPattern | Retrieves a slice of keys that matches a given pattern. |
| Delete | Removes a key from the cache. | Delete | Removes a key from the cache. |
| DeleteAll | Removes multiple keys from the cache. | DeleteAll | Removes multiple keys from the cache. |
| Count | Gets the size of the cache. This includes cache keys which may have already expired, but have not been removed yet. | DeleteKeysByPattern | Removes all keys that that matches a given pattern. |
| Clear | Wipes the cache. | Count | Gets the size of the cache. This includes cache keys which may have already expired, but have not been removed yet. |
| TTL | Gets the time until a cache key expires. | Clear | Wipes the cache. |
| Expire | Sets the expiration time of an existing cache key. | TTL | Gets the time until a cache key expires. |
| Expire | Sets the expiration time of an existing cache key. |
For further documentation, please refer to [Go Reference](https://pkg.go.dev/github.com/TwiN/gocache) For further documentation, please refer to [Go Reference](https://pkg.go.dev/github.com/TwiN/gocache)
@@ -132,7 +133,7 @@ func main() {
cache.SetWithTTL("key-with-ttl", "value", 60*time.Minute) cache.SetWithTTL("key-with-ttl", "value", 60*time.Minute)
cache.SetAll(map[string]interface{}{"k1": "v1", "k2": "v2", "k3": "v3"}) cache.SetAll(map[string]interface{}{"k1": "v1", "k2": "v2", "k3": "v3"})
fmt.Println("[Count] Cache size:", cache.Count()) fmt.Println("[Count] Cache size:", cache.Count())
value, exists := cache.Get("key") value, exists := cache.Get("key")
fmt.Printf("[Get] key=key; value=%s; exists=%v\n", value, exists) fmt.Printf("[Get] key=key; value=%s; exists=%v\n", value, exists)
@@ -345,8 +346,8 @@ import (
var cache = gocache.NewCache() var cache = gocache.NewCache()
func main() { func main() {
data := retrieveCacheEntriesUsingWhateverMeanYouUsedToPersistIt() data := retrieveCacheEntriesUsingWhateverMeanYouUsedToPersistIt()
cache.SetAll(data) cache.SetAll(data)
// Start everything else on another goroutine to prevent blocking the main goroutine // Start everything else on another goroutine to prevent blocking the main goroutine
go Start() go Start()
// Wait for termination signal // Wait for termination signal
+9 -3
View File
@@ -311,8 +311,8 @@ func (cache *Cache) Get(key string) (interface{}, bool) {
cache.mutex.Lock() cache.mutex.Lock()
entry, ok := cache.get(key) entry, ok := cache.get(key)
if !ok { if !ok {
cache.mutex.Unlock()
cache.stats.Misses++ cache.stats.Misses++
cache.mutex.Unlock()
return nil, false return nil, false
} }
if entry.Expired() { if entry.Expired() {
@@ -388,8 +388,7 @@ func (cache *Cache) GetAll() map[string]interface{} {
// cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them // cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them
// cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them // cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them
// //
// Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry, the latter // Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU).
// only applying if the cache uses the LeastRecentlyUsed eviction policy.
// The reason for that behavior is that these two (active eviction and access) only applies when you access the value // The reason for that behavior is that these two (active eviction and access) only applies when you access the value
// of the cache entry, and this function only returns the keys. // of the cache entry, and this function only returns the keys.
func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string { func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string {
@@ -435,6 +434,13 @@ func (cache *Cache) DeleteAll(keys []string) int {
return numberOfKeysDeleted return numberOfKeysDeleted
} }
// DeleteKeysByPattern deletes all entries matching a given key pattern and returns the number of entries deleted.
//
// Note that DeleteKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU).
func (cache *Cache) DeleteKeysByPattern(pattern string) int {
return cache.DeleteAll(cache.GetKeysByPattern(pattern, 0))
}
// Count returns the total amount of entries in the cache, regardless of whether they're expired or not // Count returns the total amount of entries in the cache, regardless of whether they're expired or not
func (cache *Cache) Count() int { func (cache *Cache) Count() int {
cache.mutex.RLock() cache.mutex.RLock()
+2
View File
@@ -0,0 +1,2 @@
.idea
bin
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 TwiN
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+4
View File
@@ -0,0 +1,4 @@
.PHONY: build-binaries
build-binaries:
./scripts/build.sh
+65
View File
@@ -0,0 +1,65 @@
# whois
![test](https://github.com/TwiN/whois/workflows/test/badge.svg?branch=master)
Lightweight library for retrieving WHOIS information on a domain.
It automatically retrieves the appropriate WHOIS server based on the domain's TLD by first querying IANA.
## Usage
### As an executable
To install it:
```console
go install github.com/TwiN/whois/cmd/whois@latest
```
To run it:
```console
whois example.com
```
### As a library
```console
go get github.com/TwiN/whois
```
#### Query
If all you want is the text a WHOIS server would return you, you can use the `Query` method of the `whois.Client` type:
```go
package main
import "github.com/TwiN/whois"
func main() {
client := whois.NewClient()
output, err := client.Query("example.com")
if err != nil {
panic(err)
}
println(output)
}
```
#### QueryAndParse
If you want specific pieces of information, you can use the `QueryAndParse` method of the `whois.Client` type:
```go
package main
import "github.com/TwiN/whois"
func main() {
client := whois.NewClient()
response, err := client.QueryAndParse("example.com")
if err != nil {
panic(err)
}
println(response.ExpirationDate.String())
}
```
Note that because there is no standardized format for WHOIS responses, this parsing may not be successful for every single TLD.
Currently, the only fields parsed are:
- `ExpirationDate`: The time.Time at which the domain will expire
- `DomainStatuses`: The statuses that the domain currently has (e.g. `clientTransferProhibited`)
- `NameServers`: The nameservers currently tied to the domain
If you'd like one or more other fields to be parsed, please don't be shy and create an issue or a pull request.
+94
View File
@@ -0,0 +1,94 @@
package whois
import (
"io"
"net"
"strings"
"time"
)
const (
ianaWHOISServerAddress = "whois.iana.org:43"
)
type Client struct {
whoisServerAddress string
}
func NewClient() *Client {
return &Client{
whoisServerAddress: ianaWHOISServerAddress,
}
}
func (c Client) Query(domain string) (string, error) {
parts := strings.Split(domain, ".")
output, err := c.query(c.whoisServerAddress, parts[len(parts)-1])
if err != nil {
return "", err
}
if strings.Contains(output, "whois:") {
startIndex := strings.Index(output, "whois:") + 6
endIndex := strings.Index(output[startIndex:], "\n") + startIndex
whois := strings.TrimSpace(output[startIndex:endIndex])
if referOutput, err := c.query(whois+":43", domain); err == nil {
return referOutput, nil
}
return "", err
}
return output, nil
}
func (c Client) query(whoisServerAddress, domain string) (string, error) {
connection, err := net.DialTimeout("tcp", whoisServerAddress, 10*time.Second)
if err != nil {
return "", err
}
defer connection.Close()
connection.SetDeadline(time.Now().Add(5 * time.Second))
_, err = connection.Write([]byte(domain + "\r\n"))
if err != nil {
return "", err
}
output, err := io.ReadAll(connection)
if err != nil {
return "", err
}
return string(output), nil
}
type Response struct {
ExpirationDate time.Time
DomainStatuses []string
NameServers []string
}
// QueryAndParse tries to parse the response from the WHOIS server
// There is no standardized format for WHOIS responses, so this is an attempt at best.
//
// Being the selfish person that I am, I also only parse the fields that I need.
// If you need more fields, please open an issue or pull request.
func (c Client) QueryAndParse(domain string) (*Response, error) {
text, err := c.Query(domain)
if err != nil {
return nil, err
}
response := Response{}
for _, line := range strings.Split(text, "\n") {
line = strings.TrimSpace(line)
valueStartIndex := strings.Index(line, ":")
if valueStartIndex == -1 {
continue
}
key := strings.ToLower(strings.TrimSpace(line[:valueStartIndex]))
value := strings.TrimSpace(line[valueStartIndex+1:])
if response.ExpirationDate.Unix() != 0 && strings.Contains(key, "expir") && strings.Contains(key, "date") {
response.ExpirationDate, _ = time.Parse(time.RFC3339, strings.ToUpper(value))
} else if strings.Contains(key, "domain status") {
response.DomainStatuses = append(response.DomainStatuses, value)
} else if strings.Contains(key, "name server") {
response.NameServers = append(response.NameServers, value)
}
}
return &response, nil
}
+7 -4
View File
@@ -1,12 +1,15 @@
# github.com/TwiN/g8 v1.3.0 # github.com/TwiN/g8 v1.4.0
## explicit; go 1.17 ## explicit; go 1.19
github.com/TwiN/g8 github.com/TwiN/g8
# github.com/TwiN/gocache/v2 v2.0.0 # github.com/TwiN/gocache/v2 v2.1.1
## explicit; go 1.17 ## explicit; go 1.19
github.com/TwiN/gocache/v2 github.com/TwiN/gocache/v2
# github.com/TwiN/health v1.4.0 # github.com/TwiN/health v1.4.0
## explicit; go 1.18 ## explicit; go 1.18
github.com/TwiN/health github.com/TwiN/health
# github.com/TwiN/whois v1.0.0
## explicit; go 1.19
github.com/TwiN/whois
# github.com/beorn7/perks v1.0.1 # github.com/beorn7/perks v1.0.1
## explicit; go 1.11 ## explicit; go 1.11
github.com/beorn7/perks/quantile github.com/beorn7/perks/quantile
+14
View File
@@ -9,6 +9,7 @@ import (
"github.com/TwiN/gatus/v4/alerting/provider/custom" "github.com/TwiN/gatus/v4/alerting/provider/custom"
"github.com/TwiN/gatus/v4/alerting/provider/discord" "github.com/TwiN/gatus/v4/alerting/provider/discord"
"github.com/TwiN/gatus/v4/alerting/provider/email" "github.com/TwiN/gatus/v4/alerting/provider/email"
"github.com/TwiN/gatus/v4/alerting/provider/matrix"
"github.com/TwiN/gatus/v4/alerting/provider/mattermost" "github.com/TwiN/gatus/v4/alerting/provider/mattermost"
"github.com/TwiN/gatus/v4/alerting/provider/messagebird" "github.com/TwiN/gatus/v4/alerting/provider/messagebird"
"github.com/TwiN/gatus/v4/alerting/provider/pagerduty" "github.com/TwiN/gatus/v4/alerting/provider/pagerduty"
@@ -312,6 +313,19 @@ func TestHandleAlertingWithProviderThatReturnsAnError(t *testing.T) {
}, },
}, },
}, },
{
Name: "matrix",
AlertType: alert.TypeMatrix,
AlertingConfig: &alerting.Config{
Matrix: &matrix.AlertProvider{
MatrixProviderConfig: matrix.MatrixProviderConfig{
ServerURL: "https://example.com",
AccessToken: "1",
InternalRoomID: "!a:example.com",
},
},
},
},
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
+2711 -2512
View File
File diff suppressed because it is too large. Load diff
+4 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "gatus", "name": "gatus",
"version": "3.8.0", "version": "4.0.0",
"private": true, "private": true,
"scripts": { "scripts": {
"serve": "vue-cli-service serve --mode development", "serve": "vue-cli-service serve --mode development",
@@ -8,6 +8,8 @@
"lint": "vue-cli-service lint" "lint": "vue-cli-service lint"
}, },
"dependencies": { "dependencies": {
"@headlessui/vue": "^1.7.3",
"@heroicons/vue": "^2.0.12",
"core-js": "3.22.8", "core-js": "3.22.8",
"vue": "3.2.37", "vue": "3.2.37",
"vue-router": "4.0.16" "vue-router": "4.0.16"
@@ -23,7 +25,7 @@
"eslint": "7.32.0", "eslint": "7.32.0",
"eslint-plugin-vue": "7.20.0", "eslint-plugin-vue": "7.20.0",
"postcss": "8.4.14", "postcss": "8.4.14",
"tailwindcss": "3.1.2" "tailwindcss": "^3.1.8"
}, },
"eslintConfig": { "eslintConfig": {
"root": true, "root": true,
+6 -11
View File
@@ -7,10 +7,10 @@
<div class="text-3xl xl:text-5xl lg:text-4xl font-light">{{ header }}</div> <div class="text-3xl xl:text-5xl lg:text-4xl font-light">{{ header }}</div>
</div> </div>
<div class="w-1/4 flex justify-end"> <div class="w-1/4 flex justify-end">
<a :href="link" target="_blank" style="width:100px"> <component :is="link ? 'a' : 'div'" :href="link" target="_blank" style="width:100px">
<img v-if="logo" :src="logo" alt="Gatus" class="object-scale-down" style="max-width: 100px; min-width: 50px; min-height:50px;" /> <img v-if="logo" :src="logo" alt="Gatus" class="object-scale-down" style="max-width: 100px; min-width: 50px; min-height:50px;" />
<img v-else src="./assets/logo.svg" alt="Gatus" class="object-scale-down" style="max-width: 100px; min-width: 50px; min-height:50px;" /> <img v-else src="./assets/logo.svg" alt="Gatus" class="object-scale-down" style="max-width: 100px; min-width: 50px; min-height:50px;" />
</a> </component>
</div> </div>
</div> </div>
<div v-if="buttons" class="flex flex-wrap"> <div v-if="buttons" class="flex flex-wrap">
@@ -27,20 +27,15 @@
<h2 class="mt-4 text-center text-4xl font-extrabold text-gray-800 dark:text-gray-200"> <h2 class="mt-4 text-center text-4xl font-extrabold text-gray-800 dark:text-gray-200">
Gatus Gatus
</h2> </h2>
<div class="mt-8 py-7 px-4 rounded-sm sm:bg-gray-100 sm:border sm:border-gray-300 sm:shadow-2xl sm:px-10"> <div class="py-7 px-4 rounded-sm sm:px-10">
<div class="sm:mx-auto sm:w-full"> <div v-if="$route && $route.query.error" class="text-red-500 text-center mb-5">
<h2 class="mb-4 text-center text-xl font-bold text-gray-600 dark:text-gray-200 dark:sm:text-gray-600 "> <div class="text-sm">
Sign in
</h2>
</div>
<div v-if="$route && $route.query.error" class="text-red-500 text-center my-2">
<div class="text-xl">
<span class="text-red-500" v-if="$route.query.error === 'access_denied'">You do not have access to this status page</span> <span class="text-red-500" v-if="$route.query.error === 'access_denied'">You do not have access to this status page</span>
<span class="text-red-500" v-else>{{ $route.query.error }}</span> <span class="text-red-500" v-else>{{ $route.query.error }}</span>
</div> </div>
</div> </div>
<div> <div>
<a :href="`${SERVER_URL}/oidc/login`" class="max-w-lg mx-auto w-full flex justify-center py-3 px-4 border border-green-800 rounded-md shadow-lg text-sm text-white bg-green-700 hover:bg-green-800"> <a :href="`${SERVER_URL}/oidc/login`" class="max-w-lg mx-auto w-full flex justify-center py-3 px-4 border border-green-800 rounded-md shadow-lg text-sm text-white bg-green-700 bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800">
Login with OIDC Login with OIDC
</a> </a>
</div> </div>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

+1 -1
View File
@@ -8,7 +8,7 @@
<span v-if="data.results && data.results.length && data.results[data.results.length - 1].hostname" class='text-gray-500 font-light'> | {{ data.results[data.results.length - 1].hostname }}</span> <span v-if="data.results && data.results.length && data.results[data.results.length - 1].hostname" class='text-gray-500 font-light'> | {{ data.results[data.results.length - 1].hostname }}</span>
</div> </div>
<div class='w-1/4 text-right'> <div class='w-1/4 text-right'>
<span class='font-light overflow-x-hidden cursor-pointer select-none' v-if="data.results && data.results.length" @click="toggleShowAverageResponseTime" :title="showAverageResponseTime ? 'Average response time' : 'Minimum and maximum response time'"> <span class='font-light overflow-x-hidden cursor-pointer select-none hover:text-gray-500' v-if="data.results && data.results.length" @click="toggleShowAverageResponseTime" :title="showAverageResponseTime ? 'Average response time' : 'Minimum and maximum response time'">
<slot v-if="showAverageResponseTime"> <slot v-if="showAverageResponseTime">
~{{ averageResponseTime }}ms ~{{ averageResponseTime }}ms
</slot> </slot>
+15 -9
View File
@@ -2,13 +2,17 @@
<div :class="endpoints.length === 0 ? 'mt-3' : 'mt-4'"> <div :class="endpoints.length === 0 ? 'mt-3' : 'mt-4'">
<slot v-if="name !== 'undefined'"> <slot v-if="name !== 'undefined'">
<div class="endpoint-group pt-2 border dark:bg-gray-800 dark:border-gray-500" @click="toggleGroup"> <div class="endpoint-group pt-2 border dark:bg-gray-800 dark:border-gray-500" @click="toggleGroup">
<h5 class='font-mono text-gray-400 text-xl font-medium pb-2 px-3 dark:text-gray-200 dark:hover:text-gray-500 dark:border-gray-500'> <h5 class="font-mono text-gray-400 text-xl font-medium pb-2 px-3 dark:text-gray-200 dark:hover:text-gray-500 dark:border-gray-500">
<span v-if="healthy" class='text-green-600'>&#10003;</span> <span class="endpoint-group-arrow mr-2">
<span v-else class='text-yellow-400'>~</span>
{{ name }}
<span class='float-right endpoint-group-arrow'>
{{ collapsed ? '&#9660;' : '&#9650;' }} {{ collapsed ? '&#9660;' : '&#9650;' }}
</span> </span>
{{ name }}
<span v-if="healthy" class="float-right text-green-600 w-7 hover:scale-110" title="Operational">
<CheckCircleIcon />
</span>
<span v-else class="float-right text-yellow-500 text-sm w-7 hover:scale-110" title="Partial Outage">
<ExclamationCircleIcon />
</span>
</h5> </h5>
</div> </div>
</slot> </slot>
@@ -28,11 +32,14 @@
<script> <script>
import Endpoint from './Endpoint.vue'; import Endpoint from './Endpoint.vue';
import { CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/vue/20/solid'
export default { export default {
name: 'EndpointGroup', name: 'EndpointGroup',
components: { components: {
Endpoint Endpoint,
CheckCircleIcon,
ExclamationCircleIcon
}, },
props: { props: {
name: String, name: String,
@@ -44,9 +51,8 @@ export default {
healthCheck() { healthCheck() {
if (this.endpoints) { if (this.endpoints) {
for (let i in this.endpoints) { for (let i in this.endpoints) {
for (let j in this.endpoints[i].results) { if (this.endpoints[i].results && this.endpoints[i].results.length > 0) {
if (!this.endpoints[i].results[j].success) { if (!this.endpoints[i].results[this.endpoints[i].results.length-1].success) {
// Set the endpoint group to unhealthy (only if it's currently healthy)
if (this.healthy) { if (this.healthy) {
this.healthy = false; this.healthy = false;
} }
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more