Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7efe7429dd | ||
|
|
4393a49900 | ||
|
|
241956b28c | ||
|
|
a4bc3c4dfe | ||
|
|
7cf2b427c9 | ||
|
|
dc9cddfd77 | ||
|
|
f93cebe715 | ||
|
|
f54c45e20e | ||
|
|
cacfbc0185 | ||
|
|
922638e071 | ||
|
|
979d467e36 | ||
|
|
ceb2c7884f | ||
|
|
ae750aa367 |
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
@@ -28,6 +28,7 @@ jobs:
|
|||||||
# was configured by the "Set up Go" step (otherwise, it'd use sudo's "go" executable)
|
# was configured by the "Set up Go" step (otherwise, it'd use sudo's "go" executable)
|
||||||
run: sudo env "PATH=$PATH" "GOROOT=$GOROOT" go test ./... -race -coverprofile=coverage.txt -covermode=atomic
|
run: sudo env "PATH=$PATH" "GOROOT=$GOROOT" go test ./... -race -coverprofile=coverage.txt -covermode=atomic
|
||||||
- name: Codecov
|
- name: Codecov
|
||||||
uses: codecov/codecov-action@v4.0.1
|
uses: codecov/codecov-action@v4.3.0
|
||||||
with:
|
with:
|
||||||
files: ./coverage.txt
|
files: ./coverage.txt
|
||||||
|
token: ${{ secrets.CODECOV_TOKEN }}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
[](https://gatus.io)
|
[](https://gatus.io)
|
||||||
|
|
||||||

|

|
||||||
|
[](https://discord.gg/ka9RySaQ9K)
|
||||||
[](https://goreportcard.com/report/github.com/TwiN/gatus)
|
[](https://goreportcard.com/report/github.com/TwiN/gatus)
|
||||||
[](https://codecov.io/gh/TwiN/gatus)
|
[](https://codecov.io/gh/TwiN/gatus)
|
||||||
[](https://github.com/TwiN/gatus)
|
[](https://github.com/TwiN/gatus)
|
||||||
[](https://cloud.docker.com/repository/docker/twinproduction/gatus)
|
[](https://cloud.docker.com/repository/docker/twinproduction/gatus)
|
||||||
[](https://github.com/TwiN)
|
[](https://github.com/TwiN)
|
||||||
|
|
||||||
|
|
||||||
Gatus is a developer-oriented health dashboard that gives you the ability to monitor your services using HTTP, ICMP, TCP, and even DNS
|
Gatus is a developer-oriented health dashboard that gives you the ability to monitor your services using HTTP, ICMP, TCP, and even DNS
|
||||||
queries as well as evaluate the result of said queries by using a list of conditions on values like the status code,
|
queries as well as evaluate the result of said queries by using a list of conditions on values like the status code,
|
||||||
the response time, the certificate expiration, the body and many others. The icing on top is that each of these health
|
the response time, the certificate expiration, the body and many others. The icing on top is that each of these health
|
||||||
@@ -43,6 +45,8 @@ Have any feedback or questions? [Create a discussion](https://github.com/TwiN/ga
|
|||||||
- [Features](#features)
|
- [Features](#features)
|
||||||
- [Usage](#usage)
|
- [Usage](#usage)
|
||||||
- [Configuration](#configuration)
|
- [Configuration](#configuration)
|
||||||
|
- [Endpoints](#endpoints)
|
||||||
|
- [External Endpoints](#external-endpoints)
|
||||||
- [Conditions](#conditions)
|
- [Conditions](#conditions)
|
||||||
- [Placeholders](#placeholders)
|
- [Placeholders](#placeholders)
|
||||||
- [Functions](#functions)
|
- [Functions](#functions)
|
||||||
@@ -55,6 +59,7 @@ Have any feedback or questions? [Create a discussion](https://github.com/TwiN/ga
|
|||||||
- [Configuring GitLab alerts](#configuring-gitlab-alerts)
|
- [Configuring GitLab alerts](#configuring-gitlab-alerts)
|
||||||
- [Configuring Google Chat alerts](#configuring-google-chat-alerts)
|
- [Configuring Google Chat alerts](#configuring-google-chat-alerts)
|
||||||
- [Configuring Gotify alerts](#configuring-gotify-alerts)
|
- [Configuring Gotify alerts](#configuring-gotify-alerts)
|
||||||
|
- [Configuring JetBrains Space alerts](#configuring-jetbrains-space-alerts)
|
||||||
- [Configuring Matrix alerts](#configuring-matrix-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)
|
||||||
@@ -133,6 +138,7 @@ if no traffic makes it to your applications. This puts you in a situation where
|
|||||||
that will notify you about the degradation of your services rather than you reassuring them that you're working on
|
that will notify you about the degradation of your services rather than you reassuring them that you're working on
|
||||||
fixing the issue before they even know about it.
|
fixing the issue before they even know about it.
|
||||||
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
The main features of Gatus are:
|
The main features of Gatus are:
|
||||||
|
|
||||||
@@ -147,6 +153,7 @@ The main features of Gatus are:
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
@@ -204,11 +211,42 @@ If you want to test it locally, see [Docker](#docker).
|
|||||||
|
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
| Parameter | Description | Default |
|
||||||
|
|:-----------------------------|:-------------------------------------------------------------------------------------------------------------------------------------|:---------------------------|
|
||||||
|
| `debug` | Whether to enable debug logs. | `false` |
|
||||||
|
| `metrics` | Whether to expose metrics at `/metrics`. | `false` |
|
||||||
|
| `storage` | [Storage configuration](#storage). | `{}` |
|
||||||
|
| `alerting` | [Alerting configuration](#alerting). | `{}` |
|
||||||
|
| `endpoints` | [Endpoints configuration](#endpoints). | Required `[]` |
|
||||||
|
| `external-endpoints` | [External Endpoints configuration](#external-endpoints). | `[]` |
|
||||||
|
| `security` | [Security configuration](#security). | `{}` |
|
||||||
|
| `disable-monitoring-lock` | Whether to [disable the monitoring lock](#disable-monitoring-lock). | `false` |
|
||||||
|
| `skip-invalid-config-update` | Whether to ignore invalid configuration update. <br />See [Reloading configuration on the fly](#reloading-configuration-on-the-fly). | `false` |
|
||||||
|
| `web` | Web configuration. | `{}` |
|
||||||
|
| `web.address` | Address to listen on. | `0.0.0.0` |
|
||||||
|
| `web.port` | Port to listen on. | `8080` |
|
||||||
|
| `web.read-buffer-size` | Buffer size for reading requests from a connection. Also limit for the maximum header size. | `8192` |
|
||||||
|
| `web.tls.certificate-file` | Optional public certificate file for TLS in PEM format. | `` |
|
||||||
|
| `web.tls.private-key-file` | Optional private key file for TLS in PEM format. | `` |
|
||||||
|
| `ui` | UI configuration. | `{}` |
|
||||||
|
| `ui.title` | [Title of the document](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title). | `Health Dashboard ǀ Gatus` |
|
||||||
|
| `ui.description` | Meta description for the page. | `Gatus is an advanced...`. |
|
||||||
|
| `ui.header` | Header at the top of the dashboard. | `Health Status` |
|
||||||
|
| `ui.logo` | URL to the logo to display. | `""` |
|
||||||
|
| `ui.link` | Link to open when the logo is clicked. | `""` |
|
||||||
|
| `ui.buttons` | List of buttons to display below the header. | `[]` |
|
||||||
|
| `ui.buttons[].name` | Text to display on the button. | Required `""` |
|
||||||
|
| `ui.buttons[].link` | Link to open when the button is clicked. | Required `""` |
|
||||||
|
| `maintenance` | [Maintenance configuration](#maintenance). | `{}` |
|
||||||
|
|
||||||
|
|
||||||
|
### Endpoints
|
||||||
|
Endpoints are URLs, applications, or services that you want to monitor. Each endpoint has a list of conditions that are
|
||||||
|
evaluated on an interval that you define. If any condition fails, the endpoint is considered as unhealthy.
|
||||||
|
You can then configure alerts to be triggered when an endpoint is unhealthy once a certain threshold is reached.
|
||||||
|
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------|
|
|:------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------|
|
||||||
| `debug` | Whether to enable debug logs. | `false` |
|
|
||||||
| `metrics` | Whether to expose metrics at /metrics. | `false` |
|
|
||||||
| `storage` | [Storage configuration](#storage) | `{}` |
|
|
||||||
| `endpoints` | List of endpoints to monitor. | Required `[]` |
|
| `endpoints` | List of endpoints to monitor. | Required `[]` |
|
||||||
| `endpoints[].enabled` | Whether to monitor the endpoint. | `true` |
|
| `endpoints[].enabled` | Whether to monitor the endpoint. | `true` |
|
||||||
| `endpoints[].name` | Name of the endpoint. Can be anything. | Required `""` |
|
| `endpoints[].name` | Name of the endpoint. Can be anything. | Required `""` |
|
||||||
@@ -221,43 +259,60 @@ If you want to test it locally, see [Docker](#docker).
|
|||||||
| `endpoints[].body` | Request body. | `""` |
|
| `endpoints[].body` | Request body. | `""` |
|
||||||
| `endpoints[].headers` | Request headers. | `{}` |
|
| `endpoints[].headers` | Request headers. | `{}` |
|
||||||
| `endpoints[].dns` | Configuration for an endpoint of type DNS. <br />See [Monitoring an endpoint using DNS queries](#monitoring-an-endpoint-using-dns-queries). | `""` |
|
| `endpoints[].dns` | Configuration for an endpoint of type DNS. <br />See [Monitoring an endpoint using DNS queries](#monitoring-an-endpoint-using-dns-queries). | `""` |
|
||||||
| `endpoints[].dns.query-type` | Query type (e.g. MX) | `""` |
|
| `endpoints[].dns.query-type` | Query type (e.g. MX). | `""` |
|
||||||
| `endpoints[].dns.query-name` | Query name (e.g. example.com) | `""` |
|
| `endpoints[].dns.query-name` | Query name (e.g. example.com). | `""` |
|
||||||
| `endpoints[].ssh` | Configuration for an endpoint of type SSH. <br />See [Monitoring an endpoint using SSH](#monitoring-an-endpoint-using-ssh). | `""` |
|
| `endpoints[].ssh` | Configuration for an endpoint of type SSH. <br />See [Monitoring an endpoint using SSH](#monitoring-an-endpoint-using-ssh). | `""` |
|
||||||
| `endpoints[].ssh.username` | SSH username (e.g. example) | Required `""` |
|
| `endpoints[].ssh.username` | SSH username (e.g. example). | Required `""` |
|
||||||
| `endpoints[].ssh.password` | SSH password (e.g. password) | Required `""` |
|
| `endpoints[].ssh.password` | SSH password (e.g. password). | Required `""` |
|
||||||
| `endpoints[].alerts[].type` | Type of alert. <br />See [Alerting](#alerting) for all valid types. | Required `""` |
|
| `endpoints[].alerts` | List of all alerts for a given endpoint. <br />See [Alerting](#alerting). | `[]` |
|
||||||
| `endpoints[].alerts[].enabled` | Whether to enable the alert. | `true` |
|
|
||||||
| `endpoints[].alerts[].failure-threshold` | Number of failures in a row needed before triggering the alert. | `3` |
|
|
||||||
| `endpoints[].alerts[].success-threshold` | Number of successes in a row before an ongoing incident is marked as resolved. | `2` |
|
|
||||||
| `endpoints[].alerts[].send-on-resolved` | Whether to send a notification once a triggered alert is marked as resolved. | `false` |
|
|
||||||
| `endpoints[].alerts[].description` | Description of the alert. Will be included in the alert sent. | `""` |
|
|
||||||
| `endpoints[].client` | [Client configuration](#client-configuration). | `{}` |
|
| `endpoints[].client` | [Client configuration](#client-configuration). | `{}` |
|
||||||
| `endpoints[].ui` | UI configuration at the endpoint level. | `{}` |
|
| `endpoints[].ui` | UI configuration at the endpoint level. | `{}` |
|
||||||
| `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]` |
|
| `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). | `{}` |
|
|
||||||
| `security` | [Security configuration](#security). | `{}` |
|
|
||||||
| `disable-monitoring-lock` | Whether to [disable the monitoring lock](#disable-monitoring-lock). | `false` |
|
### External Endpoints
|
||||||
| `skip-invalid-config-update` | Whether to ignore invalid configuration update. <br />See [Reloading configuration on the fly](#reloading-configuration-on-the-fly). | `false` |
|
Unlike regular endpoints, external endpoints are not monitored by Gatus, but they are instead pushed programmatically.
|
||||||
| `web` | Web configuration. | `{}` |
|
This allows you to monitor anything you want, even when what you want to check lives in an environment that would not normally be accessible by Gatus.
|
||||||
| `web.address` | Address to listen on. | `0.0.0.0` |
|
|
||||||
| `web.port` | Port to listen on. | `8080` |
|
For instance:
|
||||||
| `web.read-buffer-size` | Buffer size for reading requests from a connection. Also limit for the maximum header size. | `8192` |
|
- You can create your own agent that lives in a private network and pushes the status of your services to a publicly-exposed Gatus instance
|
||||||
| `web.tls.certificate-file` | Optional public certificate file for TLS in PEM format. | `` |
|
- You can monitor services that are not supported by Gatus
|
||||||
| `web.tls.private-key-file` | Optional private key file for TLS in PEM format. | `` |
|
- You can implement your own monitoring system while using Gatus as the dashboard
|
||||||
| `ui` | UI configuration. | `{}` |
|
|
||||||
| `ui.title` | [Title of the document](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title). | `Health Dashboard ǀ Gatus` |
|
| Parameter | Description | Default |
|
||||||
| `ui.description` | Meta description for the page. | `Gatus is an advanced...`. |
|
|:-------------------------------|:-----------------------------------------------------------------------------------------------------------------------|:--------------|
|
||||||
| `ui.header` | Header at the top of the dashboard. | `Health Status` |
|
| `external-endpoints` | List of endpoints to monitor. | `[]` |
|
||||||
| `ui.logo` | URL to the logo to display. | `""` |
|
| `external-endpoints[].enabled` | Whether to monitor the endpoint. | `true` |
|
||||||
| `ui.link` | Link to open when the logo is clicked. | `""` |
|
| `external-endpoints[].name` | Name of the endpoint. Can be anything. | Required `""` |
|
||||||
| `ui.buttons` | List of buttons to display below the header. | `[]` |
|
| `external-endpoints[].group` | Group name. Used to group multiple endpoints together on the dashboard. <br />See [Endpoint groups](#endpoint-groups). | `""` |
|
||||||
| `ui.buttons[].name` | Text to display on the button. | Required `""` |
|
| `external-endpoints[].token` | Bearer token required to push status to. | Required `""` |
|
||||||
| `ui.buttons[].link` | Link to open when the button is clicked. | Required `""` |
|
| `external-endpoints[].alerts` | List of all alerts for a given endpoint. <br />See [Alerting](#alerting). | `[]` |
|
||||||
| `maintenance` | [Maintenance configuration](#maintenance). | `{}` |
|
|
||||||
|
Example:
|
||||||
|
```yaml
|
||||||
|
external-endpoints:
|
||||||
|
- name: ext-ep-test
|
||||||
|
group: core
|
||||||
|
token: "potato"
|
||||||
|
alerts:
|
||||||
|
- type: discord
|
||||||
|
description: "healthcheck failed"
|
||||||
|
send-on-resolved: true
|
||||||
|
```
|
||||||
|
|
||||||
|
To push the status of an external endpoint, the request would have to look like this:
|
||||||
|
```
|
||||||
|
POST /api/v1/endpoints/{key}/external?success={success}
|
||||||
|
```
|
||||||
|
Where:
|
||||||
|
- `{key}` has the pattern `<GROUP_NAME>_<ENDPOINT_NAME>` in which both variables have ` `, `/`, `_`, `,` and `.` replaced by `-`.
|
||||||
|
- Using the example configuration above, the key would be `core_ext-ep-test`.
|
||||||
|
- `{success}` is a boolean (`true` or `false`) value indicating whether the health check was successful or not.
|
||||||
|
|
||||||
|
You must also pass the token as a `Bearer` token in the `Authorization` header.
|
||||||
|
|
||||||
|
|
||||||
### Conditions
|
### Conditions
|
||||||
@@ -351,7 +406,7 @@ In order to support a wide range of environments, each monitored endpoint has a
|
|||||||
the client used to send the request.
|
the client used to send the request.
|
||||||
|
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
| :------------------------------------- | :-------------------------------------------------------------------------- | :-------------- |
|
|:---------------------------------------|:----------------------------------------------------------------------------|:----------------|
|
||||||
| `client.insecure` | Whether to skip verifying the server's certificate chain and host name. | `false` |
|
| `client.insecure` | Whether to skip verifying the server's certificate chain and host name. | `false` |
|
||||||
| `client.ignore-redirect` | Whether to ignore redirects (true) or follow them (false, default). | `false` |
|
| `client.ignore-redirect` | Whether to ignore redirects (true) or follow them (false, default). | `false` |
|
||||||
| `client.timeout` | Duration before timing out. | `10s` |
|
| `client.timeout` | Duration before timing out. | `10s` |
|
||||||
@@ -364,10 +419,14 @@ the client used to send the request.
|
|||||||
| `client.proxy-url` | The URL of the proxy to use for the client | `""` |
|
| `client.proxy-url` | The URL of the proxy to use for the client | `""` |
|
||||||
| `client.identity-aware-proxy` | Google Identity-Aware-Proxy client configuration. | `{}` |
|
| `client.identity-aware-proxy` | Google Identity-Aware-Proxy client configuration. | `{}` |
|
||||||
| `client.identity-aware-proxy.audience` | The Identity-Aware-Proxy audience. (client-id of the IAP oauth2 credential) | required `""` |
|
| `client.identity-aware-proxy.audience` | The Identity-Aware-Proxy audience. (client-id of the IAP oauth2 credential) | required `""` |
|
||||||
|
| `client.tls.certificate-file` | Path to a client certificate (in PEM format) for mTLS configurations. | `""` |
|
||||||
|
| `client.tls.private-key-file` | Path to a client private key (in PEM format) for mTLS configurations. | `""` |
|
||||||
|
| `client.tls.renegotiation` | Type of renegotiation support to provide. (`never`, `freely`, `once`). | `"never"` |
|
||||||
| `client.network` | The network to use for ICMP endpoint client (`ip`, `ip4` or `ip6`). | `"ip"` |
|
| `client.network` | The network to use for ICMP endpoint client (`ip`, `ip4` or `ip6`). | `"ip"` |
|
||||||
|
|
||||||
|
|
||||||
> 📝 Some of these parameters are ignored based on the type of endpoint. For instance, there's no certificate involved
|
> 📝 Some of these parameters are ignored based on the type of endpoint. For instance, there's no certificate involved
|
||||||
in ICMP requests (ping), therefore, setting `client.insecure` to `true` for an endpoint of that type will not do anything.
|
> in ICMP requests (ping), therefore, setting `client.insecure` to `true` for an endpoint of that type will not do anything.
|
||||||
|
|
||||||
This default configuration is as follows:
|
This default configuration is as follows:
|
||||||
|
|
||||||
@@ -437,45 +496,88 @@ endpoints:
|
|||||||
|
|
||||||
> 📝 Note that Gatus will use the [gcloud default credentials](https://cloud.google.com/docs/authentication/application-default-credentials) within its environment to generate the token.
|
> 📝 Note that Gatus will use the [gcloud default credentials](https://cloud.google.com/docs/authentication/application-default-credentials) within its environment to generate the token.
|
||||||
|
|
||||||
|
This example shows you how you cna use the `client.tls` configuration to perform an mTLS query to a backend API:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
endpoints:
|
||||||
|
- name: website
|
||||||
|
url: "https://your.mtls.protected.app/health"
|
||||||
|
client:
|
||||||
|
tls:
|
||||||
|
certificate-file: /path/to/user_cert.pem
|
||||||
|
private-key-file: /path/to/user_key.pem
|
||||||
|
renegotiation: once
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
```
|
||||||
|
|
||||||
|
> 📝 Note that if running in a container, you must volume mount the certificate and key into the container.
|
||||||
|
|
||||||
### 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.
|
||||||
|
|
||||||
> 📝 If an alerting provider is not properly configured, all alerts configured with the provider's type will be
|
Alerts are configured at the endpoint level like so:
|
||||||
ignored.
|
|
||||||
|
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------|:--------|
|
|:-----------------------------|:-------------------------------------------------------------------------------|:--------------|
|
||||||
| `alerting.custom` | Configuration for custom actions on failure or alerts. <br />See [Configuring Custom alerts](#configuring-custom-alerts). | `{}` |
|
| `alerts` | List of all alerts for a given endpoint. | `[]` |
|
||||||
| `alerting.discord` | Configuration for alerts of type `discord`. <br />See [Configuring Discord alerts](#configuring-discord-alerts). | `{}` |
|
| `alerts[].type` | Type of alert. <br />See table below for all valid types. | Required `""` |
|
||||||
| `alerting.email` | Configuration for alerts of type `email`. <br />See [Configuring Email alerts](#configuring-email-alerts). | `{}` |
|
| `alerts[].enabled` | Whether to enable the alert. | `true` |
|
||||||
| `alerting.github` | Configuration for alerts of type `github`. <br />See [Configuring GitHub alerts](#configuring-github-alerts). | `{}` |
|
| `alerts[].failure-threshold` | Number of failures in a row needed before triggering the alert. | `3` |
|
||||||
| `alerting.gitlab` | Configuration for alerts of type `gitlab`. <br />See [Configuring GitLab alerts](#configuring-gitlab-alerts). | `{}` |
|
| `alerts[].success-threshold` | Number of successes in a row before an ongoing incident is marked as resolved. | `2` |
|
||||||
| `alerting.googlechat` | Configuration for alerts of type `googlechat`. <br />See [Configuring Google Chat alerts](#configuring-google-chat-alerts). | `{}` |
|
| `alerts[].send-on-resolved` | Whether to send a notification once a triggered alert is marked as resolved. | `false` |
|
||||||
| `alerting.gotify` | Configuration for alerts of type `gotify`. <br />See [Configuring Gotify alerts](#configuring-gotify-alerts). | `{}` |
|
| `alerts[].description` | Description of the alert. Will be included in the alert sent. | `""` |
|
||||||
| `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). | `{}` |
|
Here's an example of what an alert configuration might look like at the endpoint level:
|
||||||
| `alerting.messagebird` | Configuration for alerts of type `messagebird`. <br />See [Configuring Messagebird alerts](#configuring-messagebird-alerts). | `{}` |
|
```yaml
|
||||||
| `alerting.ntfy` | Configuration for alerts of type `ntfy`. <br />See [Configuring Ntfy alerts](#configuring-ntfy-alerts). | `{}` |
|
endpoints:
|
||||||
| `alerting.opsgenie` | Configuration for alerts of type `opsgenie`. <br />See [Configuring Opsgenie alerts](#configuring-opsgenie-alerts). | `{}` |
|
- name: example
|
||||||
| `alerting.pagerduty` | Configuration for alerts of type `pagerduty`. <br />See [Configuring PagerDuty alerts](#configuring-pagerduty-alerts). | `{}` |
|
url: "https://example.org"
|
||||||
| `alerting.pushover` | Configuration for alerts of type `pushover`. <br />See [Configuring Pushover alerts](#configuring-pushover-alerts). | `{}` |
|
conditions:
|
||||||
| `alerting.slack` | Configuration for alerts of type `slack`. <br />See [Configuring Slack alerts](#configuring-slack-alerts). | `{}` |
|
- "[STATUS] == 200"
|
||||||
| `alerting.teams` | Configuration for alerts of type `teams`. <br />See [Configuring Teams alerts](#configuring-teams-alerts). | `{}` |
|
alerts:
|
||||||
| `alerting.telegram` | Configuration for alerts of type `telegram`. <br />See [Configuring Telegram alerts](#configuring-telegram-alerts). | `{}` |
|
- type: slack
|
||||||
| `alerting.twilio` | Settings for alerts of type `twilio`. <br />See [Configuring Twilio alerts](#configuring-twilio-alerts). | `{}` |
|
description: "healthcheck failed"
|
||||||
|
send-on-resolved: true
|
||||||
|
```
|
||||||
|
|
||||||
|
> 📝 If an alerting provider is not properly configured, all alerts configured with the provider's type will be
|
||||||
|
> ignored.
|
||||||
|
|
||||||
|
| Parameter | Description | Default |
|
||||||
|
|:--------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------|:--------|
|
||||||
|
| `alerting.custom` | Configuration for custom actions on failure or alerts. <br />See [Configuring Custom alerts](#configuring-custom-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.github` | Configuration for alerts of type `github`. <br />See [Configuring GitHub alerts](#configuring-github-alerts). | `{}` |
|
||||||
|
| `alerting.gitlab` | Configuration for alerts of type `gitlab`. <br />See [Configuring GitLab alerts](#configuring-gitlab-alerts). | `{}` |
|
||||||
|
| `alerting.googlechat` | Configuration for alerts of type `googlechat`. <br />See [Configuring Google Chat alerts](#configuring-google-chat-alerts). | `{}` |
|
||||||
|
| `alerting.gotify` | Configuration for alerts of type `gotify`. <br />See [Configuring Gotify alerts](#configuring-gotify-alerts). | `{}` |
|
||||||
|
| `alerting.jetbrainsspace` | Configuration for alerts of type `jetbrainsspace`. <br />See [Configuring JetBrains Space alerts](#configuring-jetbrains-space-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.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.pagerduty` | Configuration for alerts of type `pagerduty`. <br />See [Configuring PagerDuty alerts](#configuring-pagerduty-alerts). | `{}` |
|
||||||
|
| `alerting.pushover` | Configuration for alerts of type `pushover`. <br />See [Configuring Pushover alerts](#configuring-pushover-alerts). | `{}` |
|
||||||
|
| `alerting.slack` | Configuration for alerts of type `slack`. <br />See [Configuring Slack alerts](#configuring-slack-alerts). | `{}` |
|
||||||
|
| `alerting.teams` | Configuration for alerts of type `teams`. <br />See [Configuring Teams alerts](#configuring-teams-alerts). | `{}` |
|
||||||
|
| `alerting.telegram` | Configuration for alerts of type `telegram`. <br />See [Configuring Telegram alerts](#configuring-telegram-alerts). | `{}` |
|
||||||
|
| `alerting.twilio` | Settings for alerts of type `twilio`. <br />See [Configuring Twilio alerts](#configuring-twilio-alerts). | `{}` |
|
||||||
|
|
||||||
|
|
||||||
#### Configuring Discord alerts
|
#### Configuring Discord alerts
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:-------------------------------------------|:-------------------------------------------------------------------------------------------|:--------------|
|
|:-------------------------------------------|:-------------------------------------------------------------------------------------------|:------------------------------------|
|
||||||
| `alerting.discord` | Configuration for alerts of type `discord` | `{}` |
|
| `alerting.discord` | Configuration for alerts of type `discord` | `{}` |
|
||||||
| `alerting.discord.webhook-url` | Discord Webhook URL | Required `""` |
|
| `alerting.discord.webhook-url` | Discord Webhook URL | Required `""` |
|
||||||
| `alerting.discord.title` | Title of the notification | `":helmet_with_white_cross: Gatus"` |
|
| `alerting.discord.title` | Title of the notification | `":helmet_with_white_cross: Gatus"` |
|
||||||
| `alerting.discord.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A |
|
| `alerting.discord.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A |
|
||||||
| `alerting.discord.overrides` | List of overrides that may be prioritized over the default configuration | `[]` |
|
| `alerting.discord.overrides` | List of overrides that may be prioritized over the default configuration | `[]` |
|
||||||
| `alerting.discord.overrides[].group` | Endpoint group for which the configuration will be overridden by this configuration | `""` |
|
| `alerting.discord.overrides[].group` | Endpoint group for which the configuration will be overridden by this configuration | `""` |
|
||||||
| `alerting.discord.overrides[].webhook-url` | Discord Webhook URL | `""` |
|
| `alerting.discord.overrides[].webhook-url` | Discord Webhook URL | `""` |
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
alerting:
|
alerting:
|
||||||
@@ -595,17 +697,18 @@ endpoints:
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
#### Configuring GitLab alerts
|
#### Configuring GitLab alerts
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:------------------------------------|:----------------------------------------------------------------------------------------------------------------|:--------------|
|
|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------|:--------------|
|
||||||
| `alerting.gitlab` | Configuration for alerts of type `gitlab` | `{}` |
|
| `alerting.gitlab` | Configuration for alerts of type `gitlab` | `{}` |
|
||||||
| `alerting.gitlab.webhook-url` | GitLab alert webhook URL (e.g. `https://gitlab.com/hlidotbe/example/alerts/notify/gatus/xxxxxxxxxxxxxxxx.json`) | Required `""` |
|
| `alerting.gitlab.webhook-url` | GitLab alert webhook URL (e.g. `https://gitlab.com/yourusername/example/alerts/notify/gatus/xxxxxxxxxxxxxxxx.json`) | Required `""` |
|
||||||
| `alerting.gitlab.authorization-key` | GitLab alert authorization key. | Required `""` |
|
| `alerting.gitlab.authorization-key` | GitLab alert authorization key. | Required `""` |
|
||||||
| `alerting.gitlab.severity` | Override default severity (critical), can be one of `critical, high, medium, low, info, unknown` | `""` |
|
| `alerting.gitlab.severity` | Override default severity (critical), can be one of `critical, high, medium, low, info, unknown` | `""` |
|
||||||
| `alerting.gitlab.monitoring-tool` | Override the monitoring tool name (gatus) | `"gatus"` |
|
| `alerting.gitlab.monitoring-tool` | Override the monitoring tool name (gatus) | `"gatus"` |
|
||||||
| `alerting.gitlab.environment-name` | Set gitlab environment's name. Required to display alerts on a dashboard. | `""` |
|
| `alerting.gitlab.environment-name` | Set gitlab environment's name. Required to display alerts on a dashboard. | `""` |
|
||||||
| `alerting.gitlab.service` | Override endpoint displayname | `""` |
|
| `alerting.gitlab.service` | Override endpoint display name | `""` |
|
||||||
| `alerting.gitlab.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert). | N/A |
|
| `alerting.gitlab.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert). | N/A |
|
||||||
|
|
||||||
The GitLab alerting provider creates an alert prefixed with `alert(gatus):` and suffixed with the endpoint's display
|
The GitLab alerting provider creates an alert prefixed with `alert(gatus):` and suffixed with the endpoint's display
|
||||||
name for each alert. If `send-on-resolved` is set to `true` on the endpoint alert, the alert will be automatically
|
name for each alert. If `send-on-resolved` is set to `true` on the endpoint alert, the alert will be automatically
|
||||||
@@ -669,14 +772,14 @@ endpoints:
|
|||||||
|
|
||||||
|
|
||||||
#### Configuring Gotify alerts
|
#### Configuring Gotify alerts
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:----------------------------------------------|:--------------------------------------------------------------------------------------------|:-----------------------|
|
|:----------------------------------------------|:--------------------------------------------------------------------------------------------|:----------------------|
|
||||||
| `alerting.gotify` | Configuration for alerts of type `gotify` | `{}` |
|
| `alerting.gotify` | Configuration for alerts of type `gotify` | `{}` |
|
||||||
| `alerting.gotify.server-url` | Gotify server URL | Required `""` |
|
| `alerting.gotify.server-url` | Gotify server URL | Required `""` |
|
||||||
| `alerting.gotify.token` | Token that is used for authentication. | Required `""` |
|
| `alerting.gotify.token` | Token that is used for authentication. | Required `""` |
|
||||||
| `alerting.gotify.priority` | Priority of the alert according to Gotify standarts. | `5` |
|
| `alerting.gotify.priority` | Priority of the alert according to Gotify standards. | `5` |
|
||||||
| `alerting.gotify.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert). | N/A |
|
| `alerting.gotify.title` | Title of the notification | `"Gatus: <endpoint>"` |
|
||||||
| `alerting.gotify.title` | Title of the notification | `"Gatus: <endpoint>"` |
|
| `alerting.gotify.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert). | N/A |
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
alerting:
|
alerting:
|
||||||
@@ -703,6 +806,41 @@ Here's an example of what the notifications look like:
|
|||||||

|

|
||||||
|
|
||||||
|
|
||||||
|
#### Configuring JetBrains Space alerts
|
||||||
|
| Parameter | Description | Default |
|
||||||
|
|:---------------------------------------------------|:--------------------------------------------------------------------------------------------|:-----------------------|
|
||||||
|
| `alerting.jetbrainsspace` | Configuration for alerts of type `jetbrainsspace` | `{}` |
|
||||||
|
| `alerting.jetbrainsspace.project` | JetBrains Space project name | Required `""` |
|
||||||
|
| `alerting.jetbrainsspace.channel-id` | JetBrains Space Chat Channel ID | Required `""` |
|
||||||
|
| `alerting.jetbrainsspace.token` | Token that is used for authentication. | Required `""` |
|
||||||
|
| `alerting.jetbrainsspace.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A |
|
||||||
|
| `alerting.jetbrainsspace.overrides` | List of overrides that may be prioritized over the default configuration | `[]` |
|
||||||
|
| `alerting.jetbrainsspace.overrides[].group` | Endpoint group for which the configuration will be overridden by this configuration | `""` |
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
alerting:
|
||||||
|
jetbrainsspace:
|
||||||
|
project: myproject
|
||||||
|
channel-id: ABCDE12345
|
||||||
|
token: "**************"
|
||||||
|
|
||||||
|
endpoints:
|
||||||
|
- name: website
|
||||||
|
url: "https://twin.sh/health"
|
||||||
|
interval: 5m
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
alerts:
|
||||||
|
- type: jetbrainsspace
|
||||||
|
description: "healthcheck failed"
|
||||||
|
send-on-resolved: true
|
||||||
|
```
|
||||||
|
|
||||||
|
Here's an example of what the notifications look like:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
#### Configuring Matrix alerts
|
#### Configuring Matrix alerts
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:-----------------------------------------|:-------------------------------------------------------------------------------------------|:-----------------------------------|
|
|:-----------------------------------------|:-------------------------------------------------------------------------------------------|:-----------------------------------|
|
||||||
@@ -955,6 +1093,7 @@ endpoints:
|
|||||||
description: "healthcheck failed"
|
description: "healthcheck failed"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
#### Configuring Slack alerts
|
#### Configuring Slack alerts
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:------------------------------------------|:-------------------------------------------------------------------------------------------|:--------------|
|
|:------------------------------------------|:-------------------------------------------------------------------------------------------|:--------------|
|
||||||
@@ -1365,7 +1504,7 @@ security:
|
|||||||
```
|
```
|
||||||
|
|
||||||
> ⚠ Make sure to carefully select to cost of the bcrypt hash. The higher the cost, the longer it takes to compute the hash,
|
> ⚠ 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 2023-01-06, I suggest a cost of 9.
|
> and basic auth verifies the password against the hash on every request. As of 2023-01-06, I suggest a cost of 9.
|
||||||
|
|
||||||
|
|
||||||
#### OIDC
|
#### OIDC
|
||||||
@@ -1393,6 +1532,7 @@ security:
|
|||||||
|
|
||||||
Confused? Read [Securing Gatus with OIDC using Auth0](https://twin.sh/articles/56/securing-gatus-with-oidc-using-auth0).
|
Confused? Read [Securing Gatus with OIDC using Auth0](https://twin.sh/articles/56/securing-gatus-with-oidc-using-auth0).
|
||||||
|
|
||||||
|
|
||||||
### TLS Encryption
|
### TLS Encryption
|
||||||
Gatus supports basic encryption with TLS. To enable this, certificate files in PEM format have to be provided.
|
Gatus supports basic encryption with TLS. To enable this, certificate files in PEM format have to be provided.
|
||||||
|
|
||||||
@@ -1405,6 +1545,7 @@ web:
|
|||||||
private-key-file: "private.key"
|
private-key-file: "private.key"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Metrics
|
### Metrics
|
||||||
To enable metrics, you must set `metrics` to `true`. Doing so will expose Prometheus-friendly metrics at the `/metrics`
|
To enable metrics, you must set `metrics` to `true`. Doing so will expose Prometheus-friendly metrics at the `/metrics`
|
||||||
endpoint on the same port your application is configured to run on (`web.port`).
|
endpoint on the same port your application is configured to run on (`web.port`).
|
||||||
@@ -1507,7 +1648,7 @@ helm repo add minicloudlabs https://minicloudlabs.github.io/helm-charts
|
|||||||
```
|
```
|
||||||
|
|
||||||
To get more details, please check [chart's configuration](https://github.com/minicloudlabs/helm-charts/tree/main/charts/gatus#configuration)
|
To get more details, please check [chart's configuration](https://github.com/minicloudlabs/helm-charts/tree/main/charts/gatus#configuration)
|
||||||
and [helmfile example](https://github.com/minicloudlabs/helm-charts/tree/main/charts/gatus#helmfileyaml-example)
|
and [helm file example](https://github.com/minicloudlabs/helm-charts/tree/main/charts/gatus#helmfileyaml-example)
|
||||||
|
|
||||||
|
|
||||||
### Terraform
|
### Terraform
|
||||||
@@ -1613,8 +1754,9 @@ Placeholders `[STATUS]` and `[BODY]` as well as the fields `endpoints[].body`, `
|
|||||||
This works for applications such as databases (Postgres, MySQL, etc.) and caches (Redis, Memcached, etc.).
|
This works for applications such as databases (Postgres, MySQL, etc.) and caches (Redis, Memcached, etc.).
|
||||||
|
|
||||||
> 📝 `[CONNECTED] == true` does not guarantee that the endpoint itself is healthy - it only guarantees that there's
|
> 📝 `[CONNECTED] == true` does not guarantee that the endpoint itself is healthy - it only guarantees that there's
|
||||||
something at the given address listening to the given port, and that a connection to that address was successfully
|
> something at the given address listening to the given port, and that a connection to that address was successfully
|
||||||
established.
|
> established.
|
||||||
|
|
||||||
|
|
||||||
### Monitoring a UDP endpoint
|
### Monitoring a UDP endpoint
|
||||||
By prefixing `endpoints[].url` with `udp:\\`, you can monitor UDP endpoints at a very basic level:
|
By prefixing `endpoints[].url` with `udp:\\`, you can monitor UDP endpoints at a very basic level:
|
||||||
@@ -1632,6 +1774,7 @@ Placeholders `[STATUS]` and `[BODY]` as well as the fields `endpoints[].body`, `
|
|||||||
|
|
||||||
This works for UDP based application.
|
This works for UDP based application.
|
||||||
|
|
||||||
|
|
||||||
### Monitoring a SCTP endpoint
|
### Monitoring a SCTP endpoint
|
||||||
By prefixing `endpoints[].url` with `sctp:\\`, you can monitor Stream Control Transmission Protocol (SCTP) endpoints at a very basic level:
|
By prefixing `endpoints[].url` with `sctp:\\`, you can monitor Stream Control Transmission Protocol (SCTP) endpoints at a very basic level:
|
||||||
|
|
||||||
@@ -1648,6 +1791,7 @@ Placeholders `[STATUS]` and `[BODY]` as well as the fields `endpoints[].body`, `
|
|||||||
|
|
||||||
This works for SCTP based application.
|
This works for SCTP based application.
|
||||||
|
|
||||||
|
|
||||||
### Monitoring a WebSocket endpoint
|
### Monitoring a WebSocket endpoint
|
||||||
By prefixing `endpoints[].url` with `ws://` or `wss://`, you can monitor WebSocket endpoints at a very basic level:
|
By prefixing `endpoints[].url` with `ws://` or `wss://`, you can monitor WebSocket endpoints at a very basic level:
|
||||||
|
|
||||||
@@ -1664,6 +1808,7 @@ endpoints:
|
|||||||
The `[BODY]` placeholder contains the output of the query, and `[CONNECTED]`
|
The `[BODY]` placeholder contains the output of the query, and `[CONNECTED]`
|
||||||
shows whether the connection was successfully established.
|
shows whether the connection was successfully established.
|
||||||
|
|
||||||
|
|
||||||
### Monitoring an endpoint using ICMP
|
### Monitoring an endpoint using ICMP
|
||||||
By prefixing `endpoints[].url` with `icmp:\\`, you can monitor endpoints at a very basic level using ICMP, or more
|
By prefixing `endpoints[].url` with `icmp:\\`, you can monitor endpoints at a very basic level using ICMP, or more
|
||||||
commonly known as "ping" or "echo":
|
commonly known as "ping" or "echo":
|
||||||
@@ -1682,6 +1827,7 @@ You can specify a domain prefixed by `icmp://`, or an IP address prefixed by `ic
|
|||||||
If you run Gatus on Linux, please read the Linux section on https://github.com/prometheus-community/pro-bing#linux
|
If you run Gatus on Linux, please read the Linux section on https://github.com/prometheus-community/pro-bing#linux
|
||||||
if you encounter any problems.
|
if you encounter any problems.
|
||||||
|
|
||||||
|
|
||||||
### Monitoring an endpoint using DNS queries
|
### Monitoring an endpoint using DNS queries
|
||||||
Defining a `dns` configuration in an endpoint will automatically mark said endpoint as an endpoint of type DNS:
|
Defining a `dns` configuration in an endpoint will automatically mark said endpoint as an endpoint of type DNS:
|
||||||
```yaml
|
```yaml
|
||||||
@@ -1701,6 +1847,7 @@ There are two placeholders that can be used in the conditions for endpoints of t
|
|||||||
- The placeholder `[DNS_RCODE]` resolves to the name associated to the response code returned by the query, such as
|
- The placeholder `[DNS_RCODE]` resolves to the name associated to the response code returned by the query, such as
|
||||||
`NOERROR`, `FORMERR`, `SERVFAIL`, `NXDOMAIN`, etc.
|
`NOERROR`, `FORMERR`, `SERVFAIL`, `NXDOMAIN`, etc.
|
||||||
|
|
||||||
|
|
||||||
### Monitoring an endpoint using SSH
|
### Monitoring an endpoint using SSH
|
||||||
You can monitor endpoints using SSH by prefixing `endpoints[].url` with `ssh:\\`:
|
You can monitor endpoints using SSH by prefixing `endpoints[].url` with `ssh:\\`:
|
||||||
```yaml
|
```yaml
|
||||||
@@ -1724,6 +1871,7 @@ The following placeholders are supported for endpoints of type SSH:
|
|||||||
- `[CONNECTED]` resolves to `true` if the SSH connection was successful, `false` otherwise
|
- `[CONNECTED]` resolves to `true` if the SSH connection was successful, `false` otherwise
|
||||||
- `[STATUS]` resolves the exit code of the command executed on the remote server (e.g. `0` for success)
|
- `[STATUS]` resolves the exit code of the command executed on the remote server (e.g. `0` for success)
|
||||||
|
|
||||||
|
|
||||||
### Monitoring an endpoint using STARTTLS
|
### Monitoring an endpoint using STARTTLS
|
||||||
If you have an email server that you want to ensure there are no problems with, monitoring it through STARTTLS
|
If you have an email server that you want to ensure there are no problems with, monitoring it through STARTTLS
|
||||||
will serve as a good initial indicator:
|
will serve as a good initial indicator:
|
||||||
@@ -1739,6 +1887,7 @@ endpoints:
|
|||||||
- "[CERTIFICATE_EXPIRATION] > 48h"
|
- "[CERTIFICATE_EXPIRATION] > 48h"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Monitoring an endpoint using TLS
|
### Monitoring an endpoint using TLS
|
||||||
Monitoring endpoints using SSL/TLS encryption, such as LDAP over TLS, can help detect certificate expiration:
|
Monitoring endpoints using SSL/TLS encryption, such as LDAP over TLS, can help detect certificate expiration:
|
||||||
```yaml
|
```yaml
|
||||||
@@ -1768,9 +1917,9 @@ endpoints:
|
|||||||
```
|
```
|
||||||
|
|
||||||
> ⚠ 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)
|
> ⚠ 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`).
|
> 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
|
> 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`.
|
> using the `[DOMAIN_EXPIRATION]` placeholder on an endpoint with an interval of less than `5m`.
|
||||||
|
|
||||||
|
|
||||||
### disable-monitoring-lock
|
### disable-monitoring-lock
|
||||||
@@ -1917,6 +2066,21 @@ endpoints:
|
|||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|
||||||
|
### Proxy client configuration
|
||||||
|
|
||||||
|
You can configure a proxy for the client to use by setting the `proxy-url` parameter in the client configuration.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
endpoints:
|
||||||
|
- name: website
|
||||||
|
url: "https://twin.sh/health"
|
||||||
|
client:
|
||||||
|
proxy-url: http://proxy.example.com:8080
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
```
|
||||||
|
|
||||||
### Proxy client configuration
|
### Proxy client configuration
|
||||||
|
|
||||||
You can configure a proxy for the client to use by setting the `proxy-url` parameter in the client configuration.
|
You can configure a proxy for the client to use by setting the `proxy-url` parameter in the client configuration.
|
||||||
@@ -2073,5 +2237,6 @@ You can download Gatus as a binary using the following command:
|
|||||||
go install github.com/TwiN/gatus/v5@latest
|
go install github.com/TwiN/gatus/v5@latest
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### High level design overview
|
### High level design overview
|
||||||

|

|
||||||
@@ -71,7 +71,7 @@ func (alert *Alert) ValidateAndSetDefaults() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetDescription retrieves the description of the alert
|
// GetDescription retrieves the description of the alert
|
||||||
func (alert Alert) GetDescription() string {
|
func (alert *Alert) GetDescription() string {
|
||||||
if alert.Description == nil {
|
if alert.Description == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -80,7 +80,7 @@ func (alert Alert) GetDescription() string {
|
|||||||
|
|
||||||
// IsEnabled returns whether an alert is enabled or not
|
// IsEnabled returns whether an alert is enabled or not
|
||||||
// Returns true if not set
|
// Returns true if not set
|
||||||
func (alert Alert) IsEnabled() bool {
|
func (alert *Alert) IsEnabled() bool {
|
||||||
if alert.Enabled == nil {
|
if alert.Enabled == nil {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ func (alert Alert) IsEnabled() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// IsSendingOnResolved returns whether an alert is sending on resolve or not
|
// IsSendingOnResolved returns whether an alert is sending on resolve or not
|
||||||
func (alert Alert) IsSendingOnResolved() bool {
|
func (alert *Alert) IsSendingOnResolved() bool {
|
||||||
if alert.SendOnResolved == nil {
|
if alert.SendOnResolved == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package alert
|
package alert
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -38,7 +39,7 @@ func TestAlert_ValidateAndSetDefaults(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.name, func(t *testing.T) {
|
t.Run(scenario.name, func(t *testing.T) {
|
||||||
if err := scenario.alert.ValidateAndSetDefaults(); err != scenario.expectedError {
|
if err := scenario.alert.ValidateAndSetDefaults(); !errors.Is(err, scenario.expectedError) {
|
||||||
t.Errorf("expected error %v, got %v", scenario.expectedError, err)
|
t.Errorf("expected error %v, got %v", scenario.expectedError, err)
|
||||||
}
|
}
|
||||||
if scenario.alert.SuccessThreshold != scenario.expectedSuccessThreshold {
|
if scenario.alert.SuccessThreshold != scenario.expectedSuccessThreshold {
|
||||||
@@ -52,34 +53,34 @@ func TestAlert_ValidateAndSetDefaults(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAlert_IsEnabled(t *testing.T) {
|
func TestAlert_IsEnabled(t *testing.T) {
|
||||||
if !(Alert{Enabled: nil}).IsEnabled() {
|
if !(&Alert{Enabled: nil}).IsEnabled() {
|
||||||
t.Error("alert.IsEnabled() should've returned true, because Enabled was set to nil")
|
t.Error("alert.IsEnabled() should've returned true, because Enabled was set to nil")
|
||||||
}
|
}
|
||||||
if value := false; (Alert{Enabled: &value}).IsEnabled() {
|
if value := false; (&Alert{Enabled: &value}).IsEnabled() {
|
||||||
t.Error("alert.IsEnabled() should've returned false, because Enabled was set to false")
|
t.Error("alert.IsEnabled() should've returned false, because Enabled was set to false")
|
||||||
}
|
}
|
||||||
if value := true; !(Alert{Enabled: &value}).IsEnabled() {
|
if value := true; !(&Alert{Enabled: &value}).IsEnabled() {
|
||||||
t.Error("alert.IsEnabled() should've returned true, because Enabled was set to true")
|
t.Error("alert.IsEnabled() should've returned true, because Enabled was set to true")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlert_GetDescription(t *testing.T) {
|
func TestAlert_GetDescription(t *testing.T) {
|
||||||
if (Alert{Description: nil}).GetDescription() != "" {
|
if (&Alert{Description: nil}).GetDescription() != "" {
|
||||||
t.Error("alert.GetDescription() should've returned an empty string, because Description was set to nil")
|
t.Error("alert.GetDescription() should've returned an empty string, because Description was set to nil")
|
||||||
}
|
}
|
||||||
if value := "description"; (Alert{Description: &value}).GetDescription() != value {
|
if value := "description"; (&Alert{Description: &value}).GetDescription() != value {
|
||||||
t.Error("alert.GetDescription() should've returned false, because Description was set to 'description'")
|
t.Error("alert.GetDescription() should've returned false, because Description was set to 'description'")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAlert_IsSendingOnResolved(t *testing.T) {
|
func TestAlert_IsSendingOnResolved(t *testing.T) {
|
||||||
if (Alert{SendOnResolved: nil}).IsSendingOnResolved() {
|
if (&Alert{SendOnResolved: nil}).IsSendingOnResolved() {
|
||||||
t.Error("alert.IsSendingOnResolved() should've returned false, because SendOnResolved was set to nil")
|
t.Error("alert.IsSendingOnResolved() should've returned false, because SendOnResolved was set to nil")
|
||||||
}
|
}
|
||||||
if value := false; (Alert{SendOnResolved: &value}).IsSendingOnResolved() {
|
if value := false; (&Alert{SendOnResolved: &value}).IsSendingOnResolved() {
|
||||||
t.Error("alert.IsSendingOnResolved() should've returned false, because SendOnResolved was set to false")
|
t.Error("alert.IsSendingOnResolved() should've returned false, because SendOnResolved was set to false")
|
||||||
}
|
}
|
||||||
if value := true; !(Alert{SendOnResolved: &value}).IsSendingOnResolved() {
|
if value := true; !(&Alert{SendOnResolved: &value}).IsSendingOnResolved() {
|
||||||
t.Error("alert.IsSendingOnResolved() should've returned true, because SendOnResolved was set to true")
|
t.Error("alert.IsSendingOnResolved() should've returned true, because SendOnResolved was set to true")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,9 @@ const (
|
|||||||
// TypeGotify is the Type for the gotify alerting provider
|
// TypeGotify is the Type for the gotify alerting provider
|
||||||
TypeGotify Type = "gotify"
|
TypeGotify Type = "gotify"
|
||||||
|
|
||||||
|
// TypeJetBrainsSpace is the Type for the jetbrains alerting provider
|
||||||
|
TypeJetBrainsSpace Type = "jetbrainsspace"
|
||||||
|
|
||||||
// TypeMatrix is the Type for the matrix alerting provider
|
// TypeMatrix is the Type for the matrix alerting provider
|
||||||
TypeMatrix Type = "matrix"
|
TypeMatrix Type = "matrix"
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -15,6 +15,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v5/alerting/provider/gitlab"
|
"github.com/TwiN/gatus/v5/alerting/provider/gitlab"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/googlechat"
|
"github.com/TwiN/gatus/v5/alerting/provider/googlechat"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/gotify"
|
"github.com/TwiN/gatus/v5/alerting/provider/gotify"
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/provider/jetbrainsspace"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
||||||
@@ -54,6 +55,9 @@ type Config struct {
|
|||||||
// Gotify is the configuration for the gotify alerting provider
|
// Gotify is the configuration for the gotify alerting provider
|
||||||
Gotify *gotify.AlertProvider `yaml:"gotify,omitempty"`
|
Gotify *gotify.AlertProvider `yaml:"gotify,omitempty"`
|
||||||
|
|
||||||
|
// JetBrainsSpace is the configuration for the jetbrains space alerting provider
|
||||||
|
JetBrainsSpace *jetbrainsspace.AlertProvider `yaml:"jetbrainsspace,omitempty"`
|
||||||
|
|
||||||
// Matrix is the configuration for the matrix alerting provider
|
// Matrix is the configuration for the matrix alerting provider
|
||||||
Matrix *matrix.AlertProvider `yaml:"matrix,omitempty"`
|
Matrix *matrix.AlertProvider `yaml:"matrix,omitempty"`
|
||||||
|
|
||||||
@@ -102,7 +106,7 @@ func (config *Config) GetAlertingProviderByAlertType(alertType alert.Type) provi
|
|||||||
return fieldValue.Interface().(provider.AlertProvider)
|
return fieldValue.Interface().(provider.AlertProvider)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("[alerting][GetAlertingProviderByAlertType] No alerting provider found for alert type %s", alertType)
|
log.Printf("[alerting.GetAlertingProviderByAlertType] No alerting provider found for alert type %s", alertType)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ func (provider *AlertProvider) IsValid() bool {
|
|||||||
registeredGroups[override.Group] = true
|
registeredGroups[override.Group] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// if both AccessKeyID and SecretAccessKey are specified, we'll use these to authenticate,
|
// if both AccessKeyID and SecretAccessKey are specified, we'll use these to authenticate,
|
||||||
// otherwise if neither are specified, then we'll fall back on IAM authentication.
|
// otherwise if neither are specified, then we'll fall back on IAM authentication.
|
||||||
return len(provider.From) > 0 && len(provider.To) > 0 &&
|
return len(provider.From) > 0 && len(provider.To) > 0 &&
|
||||||
@@ -59,7 +58,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 {
|
||||||
sess, err := provider.CreateSesSession()
|
sess, err := provider.createSession()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -112,7 +111,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
|
|||||||
|
|
||||||
// buildMessageSubjectAndBody builds the message subject and body
|
// buildMessageSubjectAndBody builds the message subject and body
|
||||||
func (provider *AlertProvider) buildMessageSubjectAndBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) (string, string) {
|
func (provider *AlertProvider) buildMessageSubjectAndBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) (string, string) {
|
||||||
var subject, message, results string
|
var subject, message string
|
||||||
if resolved {
|
if resolved {
|
||||||
subject = fmt.Sprintf("[%s] Alert resolved", endpoint.DisplayName())
|
subject = fmt.Sprintf("[%s] Alert resolved", endpoint.DisplayName())
|
||||||
message = fmt.Sprintf("An alert for %s has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
message = fmt.Sprintf("An alert for %s has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
@@ -120,20 +119,24 @@ func (provider *AlertProvider) buildMessageSubjectAndBody(endpoint *core.Endpoin
|
|||||||
subject = fmt.Sprintf("[%s] Alert triggered", endpoint.DisplayName())
|
subject = fmt.Sprintf("[%s] Alert triggered", endpoint.DisplayName())
|
||||||
message = fmt.Sprintf("An alert for %s has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
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 formattedConditionResults string
|
||||||
var prefix string
|
if len(result.ConditionResults) > 0 {
|
||||||
if conditionResult.Success {
|
formattedConditionResults = "\n\nCondition results:\n"
|
||||||
prefix = "✅"
|
for _, conditionResult := range result.ConditionResults {
|
||||||
} else {
|
var prefix string
|
||||||
prefix = "❌"
|
if conditionResult.Success {
|
||||||
|
prefix = "✅"
|
||||||
|
} else {
|
||||||
|
prefix = "❌"
|
||||||
|
}
|
||||||
|
formattedConditionResults += 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\nAlert description: " + alertDescription
|
description = "\n\nAlert description: " + alertDescription
|
||||||
}
|
}
|
||||||
return subject, message + description + "\n\nCondition results:\n" + results
|
return subject, message + description + formattedConditionResults
|
||||||
}
|
}
|
||||||
|
|
||||||
// getToForGroup returns the appropriate email integration to for a given group
|
// getToForGroup returns the appropriate email integration to for a given group
|
||||||
@@ -153,14 +156,12 @@ func (provider *AlertProvider) GetDefaultAlert() *alert.Alert {
|
|||||||
return provider.DefaultAlert
|
return provider.DefaultAlert
|
||||||
}
|
}
|
||||||
|
|
||||||
func (provider AlertProvider) CreateSesSession() (*session.Session, error) {
|
func (provider *AlertProvider) createSession() (*session.Session, error) {
|
||||||
config := &aws.Config{
|
config := &aws.Config{
|
||||||
Region: aws.String(provider.Region),
|
Region: aws.String(provider.Region),
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(provider.AccessKeyID) > 0 && len(provider.SecretAccessKey) > 0 {
|
if len(provider.AccessKeyID) > 0 && len(provider.SecretAccessKey) > 0 {
|
||||||
config.Credentials = credentials.NewStaticCredentials(provider.AccessKeyID, provider.SecretAccessKey, "")
|
config.Credentials = credentials.NewStaticCredentials(provider.AccessKeyID, provider.SecretAccessKey, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
return session.NewSession(config)
|
return session.NewSession(config)
|
||||||
}
|
}
|
||||||
@@ -75,7 +75,7 @@ type Embed struct {
|
|||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
Color int `json:"color"`
|
Color int `json:"color"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Field struct {
|
type Field struct {
|
||||||
@@ -86,7 +86,7 @@ type Field struct {
|
|||||||
|
|
||||||
// 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) []byte {
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
|
||||||
var message, results string
|
var message string
|
||||||
var colorCode int
|
var colorCode int
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("An alert for **%s** has been resolved after passing successfully %d time(s) in a row", 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)
|
||||||
@@ -95,6 +95,7 @@ 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)
|
||||||
colorCode = 15158332
|
colorCode = 15158332
|
||||||
}
|
}
|
||||||
|
var formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
@@ -102,7 +103,7 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
} else {
|
} else {
|
||||||
prefix = ":x:"
|
prefix = ":x:"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
|
formattedConditionResults += 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 {
|
||||||
@@ -112,24 +113,25 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
if provider.Title != "" {
|
if provider.Title != "" {
|
||||||
title = provider.Title
|
title = provider.Title
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(Body{
|
body := Body{
|
||||||
Content: "",
|
Content: "",
|
||||||
Embeds: []Embed{
|
Embeds: []Embed{
|
||||||
{
|
{
|
||||||
Title: title,
|
Title: title,
|
||||||
Description: message + description,
|
Description: message + description,
|
||||||
Color: colorCode,
|
Color: colorCode,
|
||||||
Fields: []Field{
|
|
||||||
{
|
|
||||||
Name: "Condition results",
|
|
||||||
Value: results,
|
|
||||||
Inline: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
}
|
||||||
return body
|
if len(formattedConditionResults) > 0 {
|
||||||
|
body.Embeds[0].Fields = append(body.Embeds[0].Fields, Field{
|
||||||
|
Name: "Condition results",
|
||||||
|
Value: formattedConditionResults,
|
||||||
|
Inline: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
bodyAsJSON, _ := json.Marshal(body)
|
||||||
|
return bodyAsJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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,6 +155,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Name string
|
Name string
|
||||||
Provider AlertProvider
|
Provider AlertProvider
|
||||||
Alert alert.Alert
|
Alert alert.Alert
|
||||||
|
NoConditions bool
|
||||||
Resolved bool
|
Resolved bool
|
||||||
ExpectedBody string
|
ExpectedBody string
|
||||||
}{
|
}{
|
||||||
@@ -179,18 +180,30 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Resolved: false,
|
Resolved: false,
|
||||||
ExpectedBody: "{\"content\":\"\",\"embeds\":[{\"title\":\"provider-title\",\"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}]}]}",
|
ExpectedBody: "{\"content\":\"\",\"embeds\":[{\"title\":\"provider-title\",\"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: "triggered-with-no-conditions",
|
||||||
|
NoConditions: true,
|
||||||
|
Provider: AlertProvider{Title: title},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\"content\":\"\",\"embeds\":[{\"title\":\"provider-title\",\"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}]}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
var conditionResults []*core.ConditionResult
|
||||||
|
if !scenario.NoConditions {
|
||||||
|
conditionResults = []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
{Condition: "[BODY] != \"\"", Success: scenario.Resolved},
|
||||||
|
}
|
||||||
|
}
|
||||||
body := scenario.Provider.buildRequestBody(
|
body := scenario.Provider.buildRequestBody(
|
||||||
&core.Endpoint{Name: "endpoint-name"},
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
&scenario.Alert,
|
&scenario.Alert,
|
||||||
&core.Result{
|
&core.Result{
|
||||||
ConditionResults: []*core.ConditionResult{
|
ConditionResults: conditionResults,
|
||||||
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
|
||||||
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
|
||||||
{Condition: "[BODY] != \"\"", Success: scenario.Resolved},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
scenario.Resolved,
|
scenario.Resolved,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
|
|||||||
|
|
||||||
// buildMessageSubjectAndBody builds the message subject and body
|
// buildMessageSubjectAndBody builds the message subject and body
|
||||||
func (provider *AlertProvider) buildMessageSubjectAndBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) (string, string) {
|
func (provider *AlertProvider) buildMessageSubjectAndBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) (string, string) {
|
||||||
var subject, message, results string
|
var subject, message string
|
||||||
if resolved {
|
if resolved {
|
||||||
subject = fmt.Sprintf("[%s] Alert resolved", endpoint.DisplayName())
|
subject = fmt.Sprintf("[%s] Alert resolved", endpoint.DisplayName())
|
||||||
message = fmt.Sprintf("An alert for %s has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
message = fmt.Sprintf("An alert for %s has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
@@ -96,20 +96,24 @@ func (provider *AlertProvider) buildMessageSubjectAndBody(endpoint *core.Endpoin
|
|||||||
subject = fmt.Sprintf("[%s] Alert triggered", endpoint.DisplayName())
|
subject = fmt.Sprintf("[%s] Alert triggered", endpoint.DisplayName())
|
||||||
message = fmt.Sprintf("An alert for %s has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
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 formattedConditionResults string
|
||||||
var prefix string
|
if len(result.ConditionResults) > 0 {
|
||||||
if conditionResult.Success {
|
formattedConditionResults = "\n\nCondition results:\n"
|
||||||
prefix = "✅"
|
for _, conditionResult := range result.ConditionResults {
|
||||||
} else {
|
var prefix string
|
||||||
prefix = "❌"
|
if conditionResult.Success {
|
||||||
|
prefix = "✅"
|
||||||
|
} else {
|
||||||
|
prefix = "❌"
|
||||||
|
}
|
||||||
|
formattedConditionResults += 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\nAlert description: " + alertDescription
|
description = "\n\nAlert description: " + alertDescription
|
||||||
}
|
}
|
||||||
return subject, message + description + "\n\nCondition results:\n" + results
|
return subject, message + description + formattedConditionResults
|
||||||
}
|
}
|
||||||
|
|
||||||
// getToForGroup returns the appropriate email integration to for a given group
|
// getToForGroup returns the appropriate email integration to for a given group
|
||||||
|
|||||||
@@ -105,22 +105,25 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
|
|||||||
|
|
||||||
// buildIssueBody builds the body of the issue
|
// buildIssueBody builds the body of the issue
|
||||||
func (provider *AlertProvider) buildIssueBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result) string {
|
func (provider *AlertProvider) buildIssueBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result) string {
|
||||||
var results string
|
var formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
if len(result.ConditionResults) > 0 {
|
||||||
var prefix string
|
formattedConditionResults = "\n\n## Condition results\n"
|
||||||
if conditionResult.Success {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
prefix = ":white_check_mark:"
|
var prefix string
|
||||||
} else {
|
if conditionResult.Success {
|
||||||
prefix = ":x:"
|
prefix = ":white_check_mark:"
|
||||||
|
} else {
|
||||||
|
prefix = ":x:"
|
||||||
|
}
|
||||||
|
formattedConditionResults += 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
|
||||||
}
|
}
|
||||||
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)
|
||||||
return message + description + "\n\n## Condition results\n" + results
|
return message + description + formattedConditionResults
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Endpoint core.Endpoint
|
Endpoint core.Endpoint
|
||||||
Provider AlertProvider
|
Provider AlertProvider
|
||||||
Alert alert.Alert
|
Alert alert.Alert
|
||||||
|
NoConditions bool
|
||||||
ExpectedBody string
|
ExpectedBody string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
@@ -122,24 +123,34 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
ExpectedBody: "An alert for **endpoint-name** has been triggered due to having failed 3 time(s) in a row:\n> description-1\n\n## Condition results\n- :white_check_mark: - `[CONNECTED] == true`\n- :x: - `[STATUS] == 200`",
|
ExpectedBody: "An alert for **endpoint-name** has been triggered due to having failed 3 time(s) in a row:\n> description-1\n\n## Condition results\n- :white_check_mark: - `[CONNECTED] == true`\n- :x: - `[STATUS] == 200`",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: "no-description",
|
Name: "triggered-with-no-description",
|
||||||
Endpoint: core.Endpoint{Name: "endpoint-name", URL: "https://example.org"},
|
Endpoint: core.Endpoint{Name: "endpoint-name", URL: "https://example.org"},
|
||||||
Provider: AlertProvider{},
|
Provider: AlertProvider{},
|
||||||
Alert: alert.Alert{FailureThreshold: 10},
|
Alert: alert.Alert{FailureThreshold: 10},
|
||||||
ExpectedBody: "An alert for **endpoint-name** has been triggered due to having failed 10 time(s) in a row\n\n## Condition results\n- :white_check_mark: - `[CONNECTED] == true`\n- :x: - `[STATUS] == 200`",
|
ExpectedBody: "An alert for **endpoint-name** has been triggered due to having failed 10 time(s) in a row\n\n## Condition results\n- :white_check_mark: - `[CONNECTED] == true`\n- :x: - `[STATUS] == 200`",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-with-no-conditions",
|
||||||
|
NoConditions: true,
|
||||||
|
Endpoint: core.Endpoint{Name: "endpoint-name", URL: "https://example.org"},
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, FailureThreshold: 10},
|
||||||
|
ExpectedBody: "An alert for **endpoint-name** has been triggered due to having failed 10 time(s) in a row:\n> description-1",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
var conditionResults []*core.ConditionResult
|
||||||
|
if !scenario.NoConditions {
|
||||||
|
conditionResults = []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: true},
|
||||||
|
{Condition: "[STATUS] == 200", Success: false},
|
||||||
|
}
|
||||||
|
}
|
||||||
body := scenario.Provider.buildIssueBody(
|
body := scenario.Provider.buildIssueBody(
|
||||||
&scenario.Endpoint,
|
&scenario.Endpoint,
|
||||||
&scenario.Alert,
|
&scenario.Alert,
|
||||||
&core.Result{
|
&core.Result{ConditionResults: conditionResults},
|
||||||
ConditionResults: []*core.ConditionResult{
|
|
||||||
{Condition: "[CONNECTED] == true", Success: true},
|
|
||||||
{Condition: "[STATUS] == 200", Success: false},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
if strings.TrimSpace(body) != strings.TrimSpace(scenario.ExpectedBody) {
|
if strings.TrimSpace(body) != strings.TrimSpace(scenario.ExpectedBody) {
|
||||||
t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
|
t.Errorf("expected:\n%s\ngot:\n%s", scenario.ExpectedBody, body)
|
||||||
|
|||||||
@@ -25,10 +25,13 @@ type AlertProvider struct {
|
|||||||
|
|
||||||
// Severity can be one of: critical, high, medium, low, info, unknown. Defaults to critical
|
// Severity can be one of: critical, high, medium, low, info, unknown. Defaults to critical
|
||||||
Severity string `yaml:"severity,omitempty"`
|
Severity string `yaml:"severity,omitempty"`
|
||||||
|
|
||||||
// MonitoringTool overrides the name sent to gitlab. Defaults to gatus
|
// MonitoringTool overrides the name sent to gitlab. Defaults to gatus
|
||||||
MonitoringTool string `yaml:"monitoring-tool,omitempty"`
|
MonitoringTool string `yaml:"monitoring-tool,omitempty"`
|
||||||
|
|
||||||
// EnvironmentName is the name of the associated GitLab environment. Required to display alerts on a dashboard.
|
// EnvironmentName is the name of the associated GitLab environment. Required to display alerts on a dashboard.
|
||||||
EnvironmentName string `yaml:"environment-name,omitempty"`
|
EnvironmentName string `yaml:"environment-name,omitempty"`
|
||||||
|
|
||||||
// Service affected. Defaults to endpoint display name
|
// Service affected. Defaults to endpoint display name
|
||||||
Service string `yaml:"service,omitempty"`
|
Service string `yaml:"service,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -52,7 +55,6 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
|
|||||||
if len(alert.ResolveKey) == 0 {
|
if len(alert.ResolveKey) == 0 {
|
||||||
alert.ResolveKey = uuid.NewString()
|
alert.ResolveKey = uuid.NewString()
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer := bytes.NewBuffer(provider.buildAlertBody(endpoint, alert, result, resolved))
|
buffer := bytes.NewBuffer(provider.buildAlertBody(endpoint, alert, result, resolved))
|
||||||
request, err := http.NewRequest(http.MethodPost, provider.WebhookURL, buffer)
|
request, err := http.NewRequest(http.MethodPost, provider.WebhookURL, buffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -114,16 +116,18 @@ func (provider *AlertProvider) buildAlertBody(endpoint *core.Endpoint, alert *al
|
|||||||
if resolved {
|
if resolved {
|
||||||
body.EndTime = result.Timestamp.Format(time.RFC3339)
|
body.EndTime = result.Timestamp.Format(time.RFC3339)
|
||||||
}
|
}
|
||||||
|
var formattedConditionResults string
|
||||||
var results string
|
if len(result.ConditionResults) > 0 {
|
||||||
for _, conditionResult := range result.ConditionResults {
|
formattedConditionResults = "\n\n## Condition results\n"
|
||||||
var prefix string
|
for _, conditionResult := range result.ConditionResults {
|
||||||
if conditionResult.Success {
|
var prefix string
|
||||||
prefix = ":white_check_mark:"
|
if conditionResult.Success {
|
||||||
} else {
|
prefix = ":white_check_mark:"
|
||||||
prefix = ":x:"
|
} else {
|
||||||
|
prefix = ":x:"
|
||||||
|
}
|
||||||
|
formattedConditionResults += 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 {
|
||||||
@@ -135,10 +139,9 @@ func (provider *AlertProvider) buildAlertBody(endpoint *core.Endpoint, alert *al
|
|||||||
} else {
|
} 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)
|
message = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
}
|
}
|
||||||
body.Description = message + description + "\n\n## Condition results\n" + results
|
body.Description = message + description + formattedConditionResults
|
||||||
|
bodyAsJSON, _ := json.Marshal(body)
|
||||||
json, _ := json.Marshal(body)
|
return bodyAsJSON
|
||||||
return json
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -121,7 +121,7 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
color = "#DD0000"
|
color = "#DD0000"
|
||||||
message = fmt.Sprintf("<font color='%s'>An alert has been triggered due to having failed %d time(s) in a row</font>", color, alert.FailureThreshold)
|
message = fmt.Sprintf("<font color='%s'>An alert has been triggered due to having failed %d time(s) in a row</font>", color, alert.FailureThreshold)
|
||||||
}
|
}
|
||||||
var results string
|
var formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
@@ -129,7 +129,7 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
} else {
|
} else {
|
||||||
prefix = "❌"
|
prefix = "❌"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("%s %s<br>", prefix, conditionResult.Condition)
|
formattedConditionResults += fmt.Sprintf("%s %s<br>", prefix, conditionResult.Condition)
|
||||||
}
|
}
|
||||||
var description string
|
var description string
|
||||||
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
@@ -150,20 +150,22 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
Icon: "BOOKMARK",
|
Icon: "BOOKMARK",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
|
||||||
KeyValue: &KeyValue{
|
|
||||||
TopLabel: "Condition results",
|
|
||||||
Content: results,
|
|
||||||
ContentMultiline: "true",
|
|
||||||
Icon: "DESCRIPTION",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
if len(formattedConditionResults) > 0 {
|
||||||
|
payload.Cards[0].Sections[0].Widgets = append(payload.Cards[0].Sections[0].Widgets, Widgets{
|
||||||
|
KeyValue: &KeyValue{
|
||||||
|
TopLabel: "Condition results",
|
||||||
|
Content: formattedConditionResults,
|
||||||
|
ContentMultiline: "true",
|
||||||
|
Icon: "DESCRIPTION",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
if endpoint.Type() == core.EndpointTypeHTTP {
|
if endpoint.Type() == core.EndpointTypeHTTP {
|
||||||
// We only include a button targeting the URL if the endpoint is an HTTP endpoint
|
// We only include a button targeting the URL if the endpoint is an HTTP endpoint
|
||||||
// If the URL isn't prefixed with https://, Google Chat will just display a blank message aynways.
|
// If the URL isn't prefixed with https://, Google Chat will just display a blank message aynways.
|
||||||
@@ -179,8 +181,8 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(payload)
|
bodyAsJSON, _ := json.Marshal(payload)
|
||||||
return body
|
return bodyAsJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
||||||
|
|||||||
@@ -68,12 +68,13 @@ type Body struct {
|
|||||||
|
|
||||||
// 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) []byte {
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
|
||||||
var message, results string
|
var message 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)
|
||||||
} else {
|
} 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)
|
message = fmt.Sprintf("An alert for `%s` has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
}
|
}
|
||||||
|
var formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
@@ -81,22 +82,22 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
} else {
|
} else {
|
||||||
prefix = "✕"
|
prefix = "✕"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("\n%s - %s", prefix, conditionResult.Condition)
|
formattedConditionResults += fmt.Sprintf("\n%s - %s", prefix, conditionResult.Condition)
|
||||||
}
|
}
|
||||||
if len(alert.GetDescription()) > 0 {
|
if len(alert.GetDescription()) > 0 {
|
||||||
message += " with the following description: " + alert.GetDescription()
|
message += " with the following description: " + alert.GetDescription()
|
||||||
}
|
}
|
||||||
message += results
|
message += formattedConditionResults
|
||||||
title := "Gatus: " + endpoint.DisplayName()
|
title := "Gatus: " + endpoint.DisplayName()
|
||||||
if provider.Title != "" {
|
if provider.Title != "" {
|
||||||
title = provider.Title
|
title = provider.Title
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(Body{
|
bodyAsJSON, _ := json.Marshal(Body{
|
||||||
Message: message,
|
Message: message,
|
||||||
Title: title,
|
Title: title,
|
||||||
Priority: provider.Priority,
|
Priority: provider.Priority,
|
||||||
})
|
})
|
||||||
return body
|
return bodyAsJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package jetbrainsspace
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v5/client"
|
||||||
|
"github.com/TwiN/gatus/v5/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AlertProvider is the configuration necessary for sending an alert using JetBrains Space
|
||||||
|
type AlertProvider struct {
|
||||||
|
Project string `yaml:"project"` // JetBrains Space Project name
|
||||||
|
ChannelID string `yaml:"channel-id"` // JetBrains Space Chat Channel ID
|
||||||
|
Token string `yaml:"token"` // JetBrains Space Bearer Token
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
ChannelID string `yaml:"channel-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.ChannelID) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
registeredGroups[override.Group] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(provider.Project) > 0 && len(provider.ChannelID) > 0 && len(provider.Token) > 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))
|
||||||
|
url := fmt.Sprintf("https://%s.jetbrains.space/api/http/chats/messages/send-message", provider.Project)
|
||||||
|
request, err := http.NewRequest(http.MethodPost, url, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.Header.Set("Authorization", "Bearer "+provider.Token)
|
||||||
|
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 {
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
Content Content `json:"content"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Content struct {
|
||||||
|
ClassName string `json:"className"`
|
||||||
|
Style string `json:"style"`
|
||||||
|
Sections []Section `json:"sections,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Section struct {
|
||||||
|
ClassName string `json:"className"`
|
||||||
|
Elements []Element `json:"elements"`
|
||||||
|
Header string `json:"header"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Element struct {
|
||||||
|
ClassName string `json:"className"`
|
||||||
|
Accessory Accessory `json:"accessory"`
|
||||||
|
Style string `json:"style"`
|
||||||
|
Size string `json:"size"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Accessory struct {
|
||||||
|
ClassName string `json:"className"`
|
||||||
|
Icon Icon `json:"icon"`
|
||||||
|
Style string `json:"style"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Icon struct {
|
||||||
|
Icon string `json:"icon"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 := Body{
|
||||||
|
Channel: "id:" + provider.getChannelIDForGroup(endpoint.Group),
|
||||||
|
Content: Content{
|
||||||
|
ClassName: "ChatMessage.Block",
|
||||||
|
Sections: []Section{{
|
||||||
|
ClassName: "MessageSection",
|
||||||
|
Elements: []Element{},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if resolved {
|
||||||
|
body.Content.Style = "SUCCESS"
|
||||||
|
body.Content.Sections[0].Header = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
|
} else {
|
||||||
|
body.Content.Style = "WARNING"
|
||||||
|
body.Content.Sections[0].Header = 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 {
|
||||||
|
icon := "warning"
|
||||||
|
style := "WARNING"
|
||||||
|
if conditionResult.Success {
|
||||||
|
icon = "success"
|
||||||
|
style = "SUCCESS"
|
||||||
|
}
|
||||||
|
body.Content.Sections[0].Elements = append(body.Content.Sections[0].Elements, Element{
|
||||||
|
ClassName: "MessageText",
|
||||||
|
Accessory: Accessory{
|
||||||
|
ClassName: "MessageIcon",
|
||||||
|
Icon: Icon{Icon: icon},
|
||||||
|
Style: style,
|
||||||
|
},
|
||||||
|
Style: style,
|
||||||
|
Size: "REGULAR",
|
||||||
|
Content: conditionResult.Condition,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
bodyAsJSON, _ := json.Marshal(body)
|
||||||
|
return bodyAsJSON
|
||||||
|
}
|
||||||
|
|
||||||
|
// getChannelIDForGroup returns the appropriate channel ID to for a given group override
|
||||||
|
func (provider *AlertProvider) getChannelIDForGroup(group string) string {
|
||||||
|
if provider.Overrides != nil {
|
||||||
|
for _, override := range provider.Overrides {
|
||||||
|
if group == override.Group {
|
||||||
|
return override.ChannelID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return provider.ChannelID
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
func (provider *AlertProvider) GetDefaultAlert() *alert.Alert {
|
||||||
|
return provider.DefaultAlert
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
package jetbrainsspace
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v5/client"
|
||||||
|
"github.com/TwiN/gatus/v5/core"
|
||||||
|
"github.com/TwiN/gatus/v5/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAlertDefaultProvider_IsValid(t *testing.T) {
|
||||||
|
invalidProvider := AlertProvider{Project: ""}
|
||||||
|
if invalidProvider.IsValid() {
|
||||||
|
t.Error("provider shouldn't have been valid")
|
||||||
|
}
|
||||||
|
validProvider := AlertProvider{Project: "foo", ChannelID: "bar", Token: "baz"}
|
||||||
|
if !validProvider.IsValid() {
|
||||||
|
t.Error("provider should've been valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
||||||
|
providerWithInvalidOverrideGroup := AlertProvider{
|
||||||
|
Project: "foobar",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
ChannelID: "http://example.com",
|
||||||
|
Group: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if providerWithInvalidOverrideGroup.IsValid() {
|
||||||
|
t.Error("provider Group shouldn't have been valid")
|
||||||
|
}
|
||||||
|
providerWithInvalidOverrideTo := AlertProvider{
|
||||||
|
Project: "foobar",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
ChannelID: "",
|
||||||
|
Group: "group",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if providerWithInvalidOverrideTo.IsValid() {
|
||||||
|
t.Error("provider integration key shouldn't have been valid")
|
||||||
|
}
|
||||||
|
providerWithValidOverride := AlertProvider{
|
||||||
|
Project: "foo",
|
||||||
|
ChannelID: "bar",
|
||||||
|
Token: "baz",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
ChannelID: "foobar",
|
||||||
|
Group: "group",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
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
|
||||||
|
Endpoint core.Endpoint
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: `{"channel":"id:","content":{"className":"ChatMessage.Block","style":"WARNING","sections":[{"className":"MessageSection","elements":[{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"warning"},"style":"WARNING"},"style":"WARNING","size":"REGULAR","content":"[CONNECTED] == true"},{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"warning"},"style":"WARNING"},"style":"WARNING","size":"REGULAR","content":"[STATUS] == 200"}],"header":"An alert for *name* has been triggered due to having failed 3 time(s) in a row"}]}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-with-group",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name", Group: "group"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: `{"channel":"id:","content":{"className":"ChatMessage.Block","style":"WARNING","sections":[{"className":"MessageSection","elements":[{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"warning"},"style":"WARNING"},"style":"WARNING","size":"REGULAR","content":"[CONNECTED] == true"},{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"warning"},"style":"WARNING"},"style":"WARNING","size":"REGULAR","content":"[STATUS] == 200"}],"header":"An alert for *group/name* has been triggered due to having failed 3 time(s) in a row"}]}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: `{"channel":"id:","content":{"className":"ChatMessage.Block","style":"SUCCESS","sections":[{"className":"MessageSection","elements":[{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"success"},"style":"SUCCESS"},"style":"SUCCESS","size":"REGULAR","content":"[CONNECTED] == true"},{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"success"},"style":"SUCCESS"},"style":"SUCCESS","size":"REGULAR","content":"[STATUS] == 200"}],"header":"An alert for *name* has been resolved after passing successfully 5 time(s) in a row"}]}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-with-group",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name", Group: "group"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: `{"channel":"id:","content":{"className":"ChatMessage.Block","style":"SUCCESS","sections":[{"className":"MessageSection","elements":[{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"success"},"style":"SUCCESS"},"style":"SUCCESS","size":"REGULAR","content":"[CONNECTED] == true"},{"className":"MessageText","accessory":{"className":"MessageIcon","icon":{"icon":"success"},"style":"SUCCESS"},"style":"SUCCESS","size":"REGULAR","content":"[STATUS] == 200"}],"header":"An alert for *group/name* has been resolved after passing successfully 5 time(s) in a row"}]}}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
body := scenario.Provider.buildRequestBody(
|
||||||
|
&scenario.Endpoint,
|
||||||
|
&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_getChannelIDForGroup(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
InputGroup string
|
||||||
|
ExpectedOutput string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "provider-no-override-specify-no-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
ChannelID: "bar",
|
||||||
|
},
|
||||||
|
InputGroup: "",
|
||||||
|
ExpectedOutput: "bar",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-no-override-specify-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
ChannelID: "bar",
|
||||||
|
},
|
||||||
|
InputGroup: "group",
|
||||||
|
ExpectedOutput: "bar",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-with-override-specify-no-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
ChannelID: "bar",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
ChannelID: "foobar",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
InputGroup: "",
|
||||||
|
ExpectedOutput: "bar",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-with-override-specify-group-should-override",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
ChannelID: "bar",
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
ChannelID: "foobar",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
InputGroup: "group",
|
||||||
|
ExpectedOutput: "foobar",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.Name, func(t *testing.T) {
|
||||||
|
if got := tt.Provider.getChannelIDForGroup(tt.InputGroup); got != tt.ExpectedOutput {
|
||||||
|
t.Errorf("AlertProvider.getChannelIDForGroup() = %v, want %v", got, tt.ExpectedOutput)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@ import (
|
|||||||
|
|
||||||
// AlertProvider is the configuration necessary for sending an alert using Matrix
|
// AlertProvider is the configuration necessary for sending an alert using Matrix
|
||||||
type AlertProvider struct {
|
type AlertProvider struct {
|
||||||
MatrixProviderConfig `yaml:",inline"`
|
ProviderConfig `yaml:",inline"`
|
||||||
|
|
||||||
// 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"`
|
||||||
@@ -30,12 +30,12 @@ type AlertProvider struct {
|
|||||||
type Override struct {
|
type Override struct {
|
||||||
Group string `yaml:"group"`
|
Group string `yaml:"group"`
|
||||||
|
|
||||||
MatrixProviderConfig `yaml:",inline"`
|
ProviderConfig `yaml:",inline"`
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultHomeserverURL = "https://matrix-client.matrix.org"
|
const defaultServerURL = "https://matrix-client.matrix.org"
|
||||||
|
|
||||||
type MatrixProviderConfig struct {
|
type ProviderConfig struct {
|
||||||
// ServerURL is the custom homeserver to use (optional)
|
// ServerURL is the custom homeserver to use (optional)
|
||||||
ServerURL string `yaml:"server-url"`
|
ServerURL string `yaml:"server-url"`
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
|
|||||||
buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
|
buffer := bytes.NewBuffer(provider.buildRequestBody(endpoint, alert, result, resolved))
|
||||||
config := provider.getConfigForGroup(endpoint.Group)
|
config := provider.getConfigForGroup(endpoint.Group)
|
||||||
if config.ServerURL == "" {
|
if config.ServerURL == "" {
|
||||||
config.ServerURL = defaultHomeserverURL
|
config.ServerURL = defaultServerURL
|
||||||
}
|
}
|
||||||
// The Matrix endpoint requires a unique transaction ID for each event sent
|
// The Matrix endpoint requires a unique transaction ID for each event sent
|
||||||
txnId := randStringBytes(24)
|
txnId := randStringBytes(24)
|
||||||
@@ -115,12 +115,13 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
|
|
||||||
// buildPlaintextMessageBody builds the message body in plaintext to include in request
|
// 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 {
|
func buildPlaintextMessageBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message, results string
|
var message 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)
|
||||||
} else {
|
} 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)
|
message = fmt.Sprintf("An alert for `%s` has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
}
|
}
|
||||||
|
var formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
@@ -128,49 +129,54 @@ func buildPlaintextMessageBody(endpoint *core.Endpoint, alert *alert.Alert, resu
|
|||||||
} else {
|
} else {
|
||||||
prefix = "✕"
|
prefix = "✕"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("\n%s - %s", prefix, conditionResult.Condition)
|
formattedConditionResults += fmt.Sprintf("\n%s - %s", 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("%s%s\n%s", message, description, results)
|
return fmt.Sprintf("%s%s\n%s", message, description, formattedConditionResults)
|
||||||
}
|
}
|
||||||
|
|
||||||
// buildHTMLMessageBody builds the message body in HTML to include in request
|
// 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 {
|
func buildHTMLMessageBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
var message, results string
|
var message string
|
||||||
if resolved {
|
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)
|
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 {
|
} 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)
|
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 formattedConditionResults string
|
||||||
var prefix string
|
if len(result.ConditionResults) > 0 {
|
||||||
if conditionResult.Success {
|
formattedConditionResults = "\n<h5>Condition results</h5><ul>"
|
||||||
prefix = "✅"
|
for _, conditionResult := range result.ConditionResults {
|
||||||
} else {
|
var prefix string
|
||||||
prefix = "❌"
|
if conditionResult.Success {
|
||||||
|
prefix = "✅"
|
||||||
|
} else {
|
||||||
|
prefix = "❌"
|
||||||
|
}
|
||||||
|
formattedConditionResults += fmt.Sprintf("<li>%s - <code>%s</code></li>", prefix, conditionResult.Condition)
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("<li>%s - <code>%s</code></li>", prefix, conditionResult.Condition)
|
formattedConditionResults += "</ul>"
|
||||||
}
|
}
|
||||||
var description string
|
var description string
|
||||||
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
description = fmt.Sprintf("\n<blockquote>%s</blockquote>", alertDescription)
|
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)
|
return fmt.Sprintf("<h3>%s</h3>%s%s", message, description, formattedConditionResults)
|
||||||
}
|
}
|
||||||
|
|
||||||
// getConfigForGroup returns the appropriate configuration for a given group
|
// getConfigForGroup returns the appropriate configuration for a given group
|
||||||
func (provider *AlertProvider) getConfigForGroup(group string) MatrixProviderConfig {
|
func (provider *AlertProvider) getConfigForGroup(group string) ProviderConfig {
|
||||||
if provider.Overrides != nil {
|
if provider.Overrides != nil {
|
||||||
for _, override := range provider.Overrides {
|
for _, override := range provider.Overrides {
|
||||||
if group == override.Group {
|
if group == override.Group {
|
||||||
return override.MatrixProviderConfig
|
return override.ProviderConfig
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return provider.MatrixProviderConfig
|
return provider.ProviderConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func randStringBytes(n int) string {
|
func randStringBytes(n int) string {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
|
|
||||||
func TestAlertProvider_IsValid(t *testing.T) {
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
invalidProvider := AlertProvider{
|
invalidProvider := AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
AccessToken: "",
|
AccessToken: "",
|
||||||
InternalRoomID: "",
|
InternalRoomID: "",
|
||||||
},
|
},
|
||||||
@@ -22,7 +22,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
t.Error("provider shouldn't have been valid")
|
t.Error("provider shouldn't have been valid")
|
||||||
}
|
}
|
||||||
validProvider := AlertProvider{
|
validProvider := AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
},
|
},
|
||||||
@@ -31,7 +31,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
|
|||||||
t.Error("provider should've been valid")
|
t.Error("provider should've been valid")
|
||||||
}
|
}
|
||||||
validProviderWithHomeserver := AlertProvider{
|
validProviderWithHomeserver := AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -47,7 +47,7 @@ func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
|||||||
Overrides: []Override{
|
Overrides: []Override{
|
||||||
{
|
{
|
||||||
Group: "",
|
Group: "",
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
AccessToken: "",
|
AccessToken: "",
|
||||||
InternalRoomID: "",
|
InternalRoomID: "",
|
||||||
},
|
},
|
||||||
@@ -61,7 +61,7 @@ func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
|||||||
Overrides: []Override{
|
Overrides: []Override{
|
||||||
{
|
{
|
||||||
Group: "group",
|
Group: "group",
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
AccessToken: "",
|
AccessToken: "",
|
||||||
InternalRoomID: "",
|
InternalRoomID: "",
|
||||||
},
|
},
|
||||||
@@ -72,14 +72,14 @@ func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
|||||||
t.Error("provider integration key shouldn't have been valid")
|
t.Error("provider integration key shouldn't have been valid")
|
||||||
}
|
}
|
||||||
providerWithValidOverride := AlertProvider{
|
providerWithValidOverride := AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
},
|
},
|
||||||
Overrides: []Override{
|
Overrides: []Override{
|
||||||
{
|
{
|
||||||
Group: "group",
|
Group: "group",
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -232,12 +232,12 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
Name string
|
Name string
|
||||||
Provider AlertProvider
|
Provider AlertProvider
|
||||||
InputGroup string
|
InputGroup string
|
||||||
ExpectedOutput MatrixProviderConfig
|
ExpectedOutput ProviderConfig
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
Name: "provider-no-override-specify-no-group-should-default",
|
Name: "provider-no-override-specify-no-group-should-default",
|
||||||
Provider: AlertProvider{
|
Provider: AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -245,7 +245,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
Overrides: nil,
|
Overrides: nil,
|
||||||
},
|
},
|
||||||
InputGroup: "",
|
InputGroup: "",
|
||||||
ExpectedOutput: MatrixProviderConfig{
|
ExpectedOutput: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -254,7 +254,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
{
|
{
|
||||||
Name: "provider-no-override-specify-group-should-default",
|
Name: "provider-no-override-specify-group-should-default",
|
||||||
Provider: AlertProvider{
|
Provider: AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -262,7 +262,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
Overrides: nil,
|
Overrides: nil,
|
||||||
},
|
},
|
||||||
InputGroup: "group",
|
InputGroup: "group",
|
||||||
ExpectedOutput: MatrixProviderConfig{
|
ExpectedOutput: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -271,7 +271,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
{
|
{
|
||||||
Name: "provider-with-override-specify-no-group-should-default",
|
Name: "provider-with-override-specify-no-group-should-default",
|
||||||
Provider: AlertProvider{
|
Provider: AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -279,7 +279,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
Overrides: []Override{
|
Overrides: []Override{
|
||||||
{
|
{
|
||||||
Group: "group",
|
Group: "group",
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example01.com",
|
ServerURL: "https://example01.com",
|
||||||
AccessToken: "12",
|
AccessToken: "12",
|
||||||
InternalRoomID: "!a:example01.com",
|
InternalRoomID: "!a:example01.com",
|
||||||
@@ -288,7 +288,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
InputGroup: "",
|
InputGroup: "",
|
||||||
ExpectedOutput: MatrixProviderConfig{
|
ExpectedOutput: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -297,7 +297,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
{
|
{
|
||||||
Name: "provider-with-override-specify-group-should-override",
|
Name: "provider-with-override-specify-group-should-override",
|
||||||
Provider: AlertProvider{
|
Provider: AlertProvider{
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
@@ -305,7 +305,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
Overrides: []Override{
|
Overrides: []Override{
|
||||||
{
|
{
|
||||||
Group: "group",
|
Group: "group",
|
||||||
MatrixProviderConfig: MatrixProviderConfig{
|
ProviderConfig: ProviderConfig{
|
||||||
ServerURL: "https://example01.com",
|
ServerURL: "https://example01.com",
|
||||||
AccessToken: "12",
|
AccessToken: "12",
|
||||||
InternalRoomID: "!a:example01.com",
|
InternalRoomID: "!a:example01.com",
|
||||||
@@ -314,7 +314,7 @@ func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
InputGroup: "group",
|
InputGroup: "group",
|
||||||
ExpectedOutput: MatrixProviderConfig{
|
ExpectedOutput: ProviderConfig{
|
||||||
ServerURL: "https://example01.com",
|
ServerURL: "https://example01.com",
|
||||||
AccessToken: "12",
|
AccessToken: "12",
|
||||||
InternalRoomID: "!a:example01.com",
|
InternalRoomID: "!a:example01.com",
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ type Field struct {
|
|||||||
|
|
||||||
// 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) []byte {
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
|
||||||
var message, color, results 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)
|
||||||
color = "#36A64F"
|
color = "#36A64F"
|
||||||
@@ -101,20 +101,23 @@ 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"
|
||||||
}
|
}
|
||||||
for _, conditionResult := range result.ConditionResults {
|
var formattedConditionResults string
|
||||||
var prefix string
|
if len(result.ConditionResults) > 0 {
|
||||||
if conditionResult.Success {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
prefix = ":white_check_mark:"
|
var prefix string
|
||||||
} else {
|
if conditionResult.Success {
|
||||||
prefix = ":x:"
|
prefix = ":white_check_mark:"
|
||||||
|
} else {
|
||||||
|
prefix = ":x:"
|
||||||
|
}
|
||||||
|
formattedConditionResults += 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
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(Body{
|
body := Body{
|
||||||
Text: "",
|
Text: "",
|
||||||
Username: "gatus",
|
Username: "gatus",
|
||||||
IconURL: "https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png",
|
IconURL: "https://raw.githubusercontent.com/TwiN/gatus/master/.github/assets/logo.png",
|
||||||
@@ -125,17 +128,18 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
Text: message + description,
|
Text: message + description,
|
||||||
Short: false,
|
Short: false,
|
||||||
Color: color,
|
Color: color,
|
||||||
Fields: []Field{
|
|
||||||
{
|
|
||||||
Title: "Condition results",
|
|
||||||
Value: results,
|
|
||||||
Short: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
}
|
||||||
return body
|
if len(formattedConditionResults) > 0 {
|
||||||
|
body.Attachments[0].Fields = append(body.Attachments[0].Fields, Field{
|
||||||
|
Title: "Condition results",
|
||||||
|
Value: formattedConditionResults,
|
||||||
|
Short: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
bodyAsJSON, _ := json.Marshal(body)
|
||||||
|
return bodyAsJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
if providerWithInvalidOverrideWebHookUrl.IsValid() {
|
if providerWithInvalidOverrideWebHookUrl.IsValid() {
|
||||||
t.Error("provider WebHookURL shoudn't have been valid")
|
t.Error("provider WebHookURL shouldn't have been valid")
|
||||||
}
|
}
|
||||||
|
|
||||||
providerWithValidOverride := AlertProvider{
|
providerWithValidOverride := AlertProvider{
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ type Body struct {
|
|||||||
|
|
||||||
// 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) []byte {
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
|
||||||
var message, results, tag string
|
var message, formattedConditionResults, tag string
|
||||||
if resolved {
|
if resolved {
|
||||||
tag = "white_check_mark"
|
tag = "white_check_mark"
|
||||||
message = "An alert has been resolved after passing successfully " + strconv.Itoa(alert.SuccessThreshold) + " time(s) in a row"
|
message = "An alert has been resolved after passing successfully " + strconv.Itoa(alert.SuccessThreshold) + " time(s) in a row"
|
||||||
@@ -93,12 +93,12 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
} else {
|
} else {
|
||||||
prefix = "🔴"
|
prefix = "🔴"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("\n%s %s", prefix, conditionResult.Condition)
|
formattedConditionResults += fmt.Sprintf("\n%s %s", prefix, conditionResult.Condition)
|
||||||
}
|
}
|
||||||
if len(alert.GetDescription()) > 0 {
|
if len(alert.GetDescription()) > 0 {
|
||||||
message += " with the following description: " + alert.GetDescription()
|
message += " with the following description: " + alert.GetDescription()
|
||||||
}
|
}
|
||||||
message += results
|
message += formattedConditionResults
|
||||||
body, _ := json.Marshal(Body{
|
body, _ := json.Marshal(Body{
|
||||||
Topic: provider.Topic,
|
Topic: provider.Topic,
|
||||||
Title: "Gatus: " + endpoint.DisplayName(),
|
Title: "Gatus: " + endpoint.DisplayName(),
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ func (provider *AlertProvider) sendRequest(url, method string, payload interface
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
var message, description, results string
|
var message, description string
|
||||||
if resolved {
|
if resolved {
|
||||||
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription())
|
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription())
|
||||||
description = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
description = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
@@ -127,6 +127,7 @@ func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, a
|
|||||||
if endpoint.Group != "" {
|
if endpoint.Group != "" {
|
||||||
message = fmt.Sprintf("[%s] %s", endpoint.Group, message)
|
message = fmt.Sprintf("[%s] %s", endpoint.Group, message)
|
||||||
}
|
}
|
||||||
|
var formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
@@ -134,9 +135,9 @@ func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, a
|
|||||||
} else {
|
} else {
|
||||||
prefix = "▢"
|
prefix = "▢"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
|
formattedConditionResults += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
|
||||||
}
|
}
|
||||||
description = description + "\n" + results
|
description = description + "\n" + formattedConditionResults
|
||||||
key := buildKey(endpoint)
|
key := buildKey(endpoint)
|
||||||
details := map[string]string{
|
details := map[string]string{
|
||||||
"endpoint:url": endpoint.URL,
|
"endpoint:url": endpoint.URL,
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
|
|||||||
var payload pagerDutyResponsePayload
|
var payload pagerDutyResponsePayload
|
||||||
if err = json.Unmarshal(body, &payload); err != nil {
|
if err = json.Unmarshal(body, &payload); err != nil {
|
||||||
// Silently fail. We don't want to create tons of alerts just because we failed to parse the body.
|
// Silently fail. We don't want to create tons of alerts just because we failed to parse the body.
|
||||||
log.Printf("[pagerduty][Send] Ran into error unmarshaling pagerduty response: %s", err.Error())
|
log.Printf("[pagerduty.Send] Ran into error unmarshaling pagerduty response: %s", err.Error())
|
||||||
} else {
|
} else {
|
||||||
alert.ResolveKey = payload.DedupKey
|
alert.ResolveKey = payload.DedupKey
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v5/alerting/provider/github"
|
"github.com/TwiN/gatus/v5/alerting/provider/github"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/gitlab"
|
"github.com/TwiN/gatus/v5/alerting/provider/gitlab"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/googlechat"
|
"github.com/TwiN/gatus/v5/alerting/provider/googlechat"
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/provider/jetbrainsspace"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
||||||
@@ -23,7 +24,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v5/core"
|
"github.com/TwiN/gatus/v5/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AlertProvider is the interface that each providers should implement
|
// AlertProvider is the interface that each provider should implement
|
||||||
type AlertProvider interface {
|
type AlertProvider interface {
|
||||||
// IsValid returns whether the provider's configuration is valid
|
// IsValid returns whether the provider's configuration is valid
|
||||||
IsValid() bool
|
IsValid() bool
|
||||||
@@ -66,6 +67,7 @@ var (
|
|||||||
_ AlertProvider = (*github.AlertProvider)(nil)
|
_ AlertProvider = (*github.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*gitlab.AlertProvider)(nil)
|
_ AlertProvider = (*gitlab.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*googlechat.AlertProvider)(nil)
|
_ AlertProvider = (*googlechat.AlertProvider)(nil)
|
||||||
|
_ AlertProvider = (*jetbrainsspace.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*matrix.AlertProvider)(nil)
|
_ AlertProvider = (*matrix.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*mattermost.AlertProvider)(nil)
|
_ AlertProvider = (*mattermost.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*messagebird.AlertProvider)(nil)
|
_ AlertProvider = (*messagebird.AlertProvider)(nil)
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ type Attachment struct {
|
|||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
Short bool `json:"short"`
|
Short bool `json:"short"`
|
||||||
Color string `json:"color"`
|
Color string `json:"color"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Field struct {
|
type Field struct {
|
||||||
@@ -82,7 +82,7 @@ type Field struct {
|
|||||||
|
|
||||||
// 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) []byte {
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
|
||||||
var message, color, results 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)
|
||||||
color = "#36A64F"
|
color = "#36A64F"
|
||||||
@@ -90,6 +90,7 @@ 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 formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
@@ -97,13 +98,13 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
} else {
|
} else {
|
||||||
prefix = ":x:"
|
prefix = ":x:"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
|
formattedConditionResults += 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
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(Body{
|
body := Body{
|
||||||
Text: "",
|
Text: "",
|
||||||
Attachments: []Attachment{
|
Attachments: []Attachment{
|
||||||
{
|
{
|
||||||
@@ -111,17 +112,18 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
Text: message + description,
|
Text: message + description,
|
||||||
Short: false,
|
Short: false,
|
||||||
Color: color,
|
Color: color,
|
||||||
Fields: []Field{
|
|
||||||
{
|
|
||||||
Title: "Condition results",
|
|
||||||
Value: results,
|
|
||||||
Short: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
}
|
||||||
return body
|
if len(formattedConditionResults) > 0 {
|
||||||
|
body.Attachments[0].Fields = append(body.Attachments[0].Fields, Field{
|
||||||
|
Title: "Condition results",
|
||||||
|
Value: formattedConditionResults,
|
||||||
|
Short: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
bodyAsJSON, _ := json.Marshal(body)
|
||||||
|
return bodyAsJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
||||||
|
|||||||
@@ -144,6 +144,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Provider AlertProvider
|
Provider AlertProvider
|
||||||
Endpoint core.Endpoint
|
Endpoint core.Endpoint
|
||||||
Alert alert.Alert
|
Alert alert.Alert
|
||||||
|
NoConditions bool
|
||||||
Resolved bool
|
Resolved bool
|
||||||
ExpectedBody string
|
ExpectedBody string
|
||||||
}{
|
}{
|
||||||
@@ -163,6 +164,15 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Resolved: false,
|
Resolved: false,
|
||||||
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}]}]}",
|
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: "triggered-with-no-conditions",
|
||||||
|
NoConditions: true,
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Endpoint: core.Endpoint{Name: "name"},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
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\"}]}",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Name: "resolved",
|
Name: "resolved",
|
||||||
Provider: AlertProvider{},
|
Provider: AlertProvider{},
|
||||||
@@ -182,14 +192,18 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
var conditionResults []*core.ConditionResult
|
||||||
|
if !scenario.NoConditions {
|
||||||
|
conditionResults = []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
}
|
||||||
|
}
|
||||||
body := scenario.Provider.buildRequestBody(
|
body := scenario.Provider.buildRequestBody(
|
||||||
&scenario.Endpoint,
|
&scenario.Endpoint,
|
||||||
&scenario.Alert,
|
&scenario.Alert,
|
||||||
&core.Result{
|
&core.Result{
|
||||||
ConditionResults: []*core.ConditionResult{
|
ConditionResults: conditionResults,
|
||||||
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
|
||||||
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
scenario.Resolved,
|
scenario.Resolved,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ type Body struct {
|
|||||||
ThemeColor string `json:"themeColor"`
|
ThemeColor string `json:"themeColor"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
Sections []Section `json:"sections"`
|
Sections []Section `json:"sections,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Section struct {
|
type Section struct {
|
||||||
@@ -87,7 +87,7 @@ 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
|
var formattedConditionResults string
|
||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
@@ -95,26 +95,27 @@ func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *
|
|||||||
} else {
|
} else {
|
||||||
prefix = "❌"
|
prefix = "❌"
|
||||||
}
|
}
|
||||||
results += fmt.Sprintf("%s - `%s`<br/>", prefix, conditionResult.Condition)
|
formattedConditionResults += fmt.Sprintf("%s - `%s`<br/>", prefix, conditionResult.Condition)
|
||||||
}
|
}
|
||||||
var description string
|
var description string
|
||||||
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
description = ": " + alertDescription
|
description = ": " + alertDescription
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(Body{
|
body := Body{
|
||||||
Type: "MessageCard",
|
Type: "MessageCard",
|
||||||
Context: "http://schema.org/extensions",
|
Context: "http://schema.org/extensions",
|
||||||
ThemeColor: color,
|
ThemeColor: color,
|
||||||
Title: "🚨 Gatus",
|
Title: "🚨 Gatus",
|
||||||
Text: message + description,
|
Text: message + description,
|
||||||
Sections: []Section{
|
}
|
||||||
{
|
if len(formattedConditionResults) > 0 {
|
||||||
ActivityTitle: "Condition results",
|
body.Sections = append(body.Sections, Section{
|
||||||
Text: results,
|
ActivityTitle: "Condition results",
|
||||||
},
|
Text: formattedConditionResults,
|
||||||
},
|
})
|
||||||
})
|
}
|
||||||
return body
|
bodyAsJSON, _ := json.Marshal(body)
|
||||||
|
return bodyAsJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
// getWebhookURLForGroup returns the appropriate Webhook URL integration to for a given group
|
||||||
|
|||||||
@@ -143,6 +143,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Name string
|
Name string
|
||||||
Provider AlertProvider
|
Provider AlertProvider
|
||||||
Alert alert.Alert
|
Alert alert.Alert
|
||||||
|
NoConditions bool
|
||||||
Resolved bool
|
Resolved bool
|
||||||
ExpectedBody string
|
ExpectedBody string
|
||||||
}{
|
}{
|
||||||
@@ -160,18 +161,28 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Resolved: true,
|
Resolved: true,
|
||||||
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\"}]}",
|
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\"}]}",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-with-no-conditions",
|
||||||
|
NoConditions: true,
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
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\"}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
var conditionResults []*core.ConditionResult
|
||||||
|
if !scenario.NoConditions {
|
||||||
|
conditionResults = []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
}
|
||||||
|
}
|
||||||
body := scenario.Provider.buildRequestBody(
|
body := scenario.Provider.buildRequestBody(
|
||||||
&core.Endpoint{Name: "endpoint-name"},
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
&scenario.Alert,
|
&scenario.Alert,
|
||||||
&core.Result{
|
&core.Result{ConditionResults: conditionResults},
|
||||||
ConditionResults: []*core.ConditionResult{
|
|
||||||
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
|
||||||
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
scenario.Resolved,
|
scenario.Resolved,
|
||||||
)
|
)
|
||||||
if string(body) != scenario.ExpectedBody {
|
if string(body) != scenario.ExpectedBody {
|
||||||
|
|||||||
@@ -67,33 +67,37 @@ type Body struct {
|
|||||||
|
|
||||||
// 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) []byte {
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) []byte {
|
||||||
var message, results string
|
var message 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.SuccessThreshold)
|
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.SuccessThreshold)
|
||||||
} 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 {
|
var formattedConditionResults string
|
||||||
var prefix string
|
if len(result.ConditionResults) > 0 {
|
||||||
if conditionResult.Success {
|
formattedConditionResults = "\n*Condition results*\n"
|
||||||
prefix = "✅"
|
for _, conditionResult := range result.ConditionResults {
|
||||||
} else {
|
var prefix string
|
||||||
prefix = "❌"
|
if conditionResult.Success {
|
||||||
|
prefix = "✅"
|
||||||
|
} else {
|
||||||
|
prefix = "❌"
|
||||||
|
}
|
||||||
|
formattedConditionResults += 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%s", message, alert.GetDescription(), formattedConditionResults)
|
||||||
} else {
|
} else {
|
||||||
text = fmt.Sprintf("⛑ *Gatus* \n%s \n*Condition results*\n%s", message, results)
|
text = fmt.Sprintf("⛑ *Gatus* \n%s%s", message, formattedConditionResults)
|
||||||
}
|
}
|
||||||
body, _ := json.Marshal(Body{
|
bodyAsJSON, _ := json.Marshal(Body{
|
||||||
ChatID: provider.ID,
|
ChatID: provider.ID,
|
||||||
Text: text,
|
Text: text,
|
||||||
ParseMode: "MARKDOWN",
|
ParseMode: "MARKDOWN",
|
||||||
})
|
})
|
||||||
return body
|
return bodyAsJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultAlert returns the provider's default alert configuration
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
|||||||
@@ -116,6 +116,7 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Name string
|
Name string
|
||||||
Provider AlertProvider
|
Provider AlertProvider
|
||||||
Alert alert.Alert
|
Alert alert.Alert
|
||||||
|
NoConditions bool
|
||||||
Resolved bool
|
Resolved bool
|
||||||
ExpectedBody string
|
ExpectedBody string
|
||||||
}{
|
}{
|
||||||
@@ -133,18 +134,28 @@ func TestAlertProvider_buildRequestBody(t *testing.T) {
|
|||||||
Resolved: true,
|
Resolved: true,
|
||||||
ExpectedBody: "{\"chat_id\":\"123\",\"text\":\"⛑ *Gatus* \\nAn alert for *endpoint-name* has been resolved:\\n—\\n _healthcheck passing successfully 5 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 5 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\"}",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-with-no-conditions",
|
||||||
|
NoConditions: true,
|
||||||
|
Provider: AlertProvider{ID: "123"},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\"chat_id\":\"123\",\"text\":\"⛑ *Gatus* \\nAn alert for *endpoint-name* has been resolved:\\n—\\n _healthcheck passing successfully 5 time(s) in a row_\\n— \\n*Description* \\n_description-2_ \\n\",\"parse_mode\":\"MARKDOWN\"}",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run(scenario.Name, func(t *testing.T) {
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
var conditionResults []*core.ConditionResult
|
||||||
|
if !scenario.NoConditions {
|
||||||
|
conditionResults = []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
}
|
||||||
|
}
|
||||||
body := scenario.Provider.buildRequestBody(
|
body := scenario.Provider.buildRequestBody(
|
||||||
&core.Endpoint{Name: "endpoint-name"},
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
&scenario.Alert,
|
&scenario.Alert,
|
||||||
&core.Result{
|
&core.Result{ConditionResults: conditionResults},
|
||||||
ConditionResults: []*core.ConditionResult{
|
|
||||||
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
|
||||||
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
scenario.Resolved,
|
scenario.Resolved,
|
||||||
)
|
)
|
||||||
if string(body) != scenario.ExpectedBody {
|
if string(body) != scenario.ExpectedBody {
|
||||||
|
|||||||
@@ -76,6 +76,8 @@ func (a *API) createRouter(cfg *config.Config) *fiber.App {
|
|||||||
unprotectedAPIRouter.Get("/v1/endpoints/:key/uptimes/:duration/badge.svg", UptimeBadge)
|
unprotectedAPIRouter.Get("/v1/endpoints/:key/uptimes/:duration/badge.svg", UptimeBadge)
|
||||||
unprotectedAPIRouter.Get("/v1/endpoints/:key/response-times/:duration/badge.svg", ResponseTimeBadge(cfg))
|
unprotectedAPIRouter.Get("/v1/endpoints/:key/response-times/:duration/badge.svg", ResponseTimeBadge(cfg))
|
||||||
unprotectedAPIRouter.Get("/v1/endpoints/:key/response-times/:duration/chart.svg", ResponseTimeChart)
|
unprotectedAPIRouter.Get("/v1/endpoints/:key/response-times/:duration/chart.svg", ResponseTimeChart)
|
||||||
|
// This endpoint requires authz with bearer token, so technically it is protected
|
||||||
|
unprotectedAPIRouter.Post("/v1/endpoints/:key/external", CreateExternalEndpointResult(cfg))
|
||||||
// SPA
|
// SPA
|
||||||
app.Get("/", SinglePageApplication(cfg.UI))
|
app.Get("/", SinglePageApplication(cfg.UI))
|
||||||
app.Get("/endpoints/:name", SinglePageApplication(cfg.UI))
|
app.Get("/endpoints/:name", SinglePageApplication(cfg.UI))
|
||||||
|
|||||||
+17
-12
@@ -2,12 +2,14 @@ package api
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v5/config"
|
"github.com/TwiN/gatus/v5/config"
|
||||||
|
"github.com/TwiN/gatus/v5/core/ui"
|
||||||
"github.com/TwiN/gatus/v5/storage/store"
|
"github.com/TwiN/gatus/v5/storage/store"
|
||||||
"github.com/TwiN/gatus/v5/storage/store/common"
|
"github.com/TwiN/gatus/v5/storage/store/common"
|
||||||
"github.com/TwiN/gatus/v5/storage/store/common/paging"
|
"github.com/TwiN/gatus/v5/storage/store/common/paging"
|
||||||
@@ -52,9 +54,9 @@ func UptimeBadge(c *fiber.Ctx) error {
|
|||||||
key := c.Params("key")
|
key := c.Params("key")
|
||||||
uptime, err := store.Get().GetUptimeByKey(key, from, time.Now())
|
uptime, err := store.Get().GetUptimeByKey(key, from, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrEndpointNotFound {
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
return c.Status(404).SendString(err.Error())
|
return c.Status(404).SendString(err.Error())
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if errors.Is(err, common.ErrInvalidTimeRange) {
|
||||||
return c.Status(400).SendString(err.Error())
|
return c.Status(400).SendString(err.Error())
|
||||||
}
|
}
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
@@ -68,7 +70,7 @@ func UptimeBadge(c *fiber.Ctx) error {
|
|||||||
// 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(config *config.Config) fiber.Handler {
|
func ResponseTimeBadge(cfg *config.Config) fiber.Handler {
|
||||||
return func(c *fiber.Ctx) error {
|
return func(c *fiber.Ctx) error {
|
||||||
duration := c.Params("duration")
|
duration := c.Params("duration")
|
||||||
var from time.Time
|
var from time.Time
|
||||||
@@ -85,9 +87,9 @@ func ResponseTimeBadge(config *config.Config) fiber.Handler {
|
|||||||
key := c.Params("key")
|
key := c.Params("key")
|
||||||
averageResponseTime, err := store.Get().GetAverageResponseTimeByKey(key, from, time.Now())
|
averageResponseTime, err := store.Get().GetAverageResponseTimeByKey(key, from, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrEndpointNotFound {
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
return c.Status(404).SendString(err.Error())
|
return c.Status(404).SendString(err.Error())
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if errors.Is(err, common.ErrInvalidTimeRange) {
|
||||||
return c.Status(400).SendString(err.Error())
|
return c.Status(400).SendString(err.Error())
|
||||||
}
|
}
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
@@ -95,7 +97,7 @@ func ResponseTimeBadge(config *config.Config) fiber.Handler {
|
|||||||
c.Set("Content-Type", "image/svg+xml")
|
c.Set("Content-Type", "image/svg+xml")
|
||||||
c.Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
c.Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||||
c.Set("Expires", "0")
|
c.Set("Expires", "0")
|
||||||
return c.Status(200).Send(generateResponseTimeBadgeSVG(duration, averageResponseTime, key, config))
|
return c.Status(200).Send(generateResponseTimeBadgeSVG(duration, averageResponseTime, key, cfg))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,9 +107,9 @@ func HealthBadge(c *fiber.Ctx) error {
|
|||||||
pagingConfig := paging.NewEndpointStatusParams()
|
pagingConfig := paging.NewEndpointStatusParams()
|
||||||
status, err := store.Get().GetEndpointStatusByKey(key, pagingConfig.WithResults(1, 1))
|
status, err := store.Get().GetEndpointStatusByKey(key, pagingConfig.WithResults(1, 1))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrEndpointNotFound {
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
return c.Status(404).SendString(err.Error())
|
return c.Status(404).SendString(err.Error())
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if errors.Is(err, common.ErrInvalidTimeRange) {
|
||||||
return c.Status(400).SendString(err.Error())
|
return c.Status(400).SendString(err.Error())
|
||||||
}
|
}
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
@@ -131,9 +133,9 @@ func HealthBadgeShields(c *fiber.Ctx) error {
|
|||||||
pagingConfig := paging.NewEndpointStatusParams()
|
pagingConfig := paging.NewEndpointStatusParams()
|
||||||
status, err := store.Get().GetEndpointStatusByKey(key, pagingConfig.WithResults(1, 1))
|
status, err := store.Get().GetEndpointStatusByKey(key, pagingConfig.WithResults(1, 1))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrEndpointNotFound {
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
return c.Status(404).SendString(err.Error())
|
return c.Status(404).SendString(err.Error())
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if errors.Is(err, common.ErrInvalidTimeRange) {
|
||||||
return c.Status(400).SendString(err.Error())
|
return c.Status(400).SendString(err.Error())
|
||||||
}
|
}
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
@@ -271,10 +273,13 @@ func generateResponseTimeBadgeSVG(duration string, averageResponseTime int, key
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getBadgeColorFromResponseTime(responseTime int, key string, cfg *config.Config) string {
|
func getBadgeColorFromResponseTime(responseTime int, key string, cfg *config.Config) string {
|
||||||
endpoint := cfg.GetEndpointByKey(key)
|
thresholds := ui.GetDefaultConfig().Badge.ResponseTime.Thresholds
|
||||||
|
if endpoint := cfg.GetEndpointByKey(key); endpoint != nil {
|
||||||
|
thresholds = endpoint.UIConfig.Badge.ResponseTime.Thresholds
|
||||||
|
}
|
||||||
// the threshold config requires 5 values, so we can be sure it's set here
|
// the threshold config requires 5 values, so we can be sure it's set here
|
||||||
for i := 0; i < 5; i++ {
|
for i := 0; i < 5; i++ {
|
||||||
if responseTime <= endpoint.UIConfig.Badge.ResponseTime.Thresholds[i] {
|
if responseTime <= thresholds[i] {
|
||||||
return badgeColors[i]
|
return badgeColors[i]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-3
@@ -1,6 +1,7 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"math"
|
"math"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -42,9 +43,9 @@ func ResponseTimeChart(c *fiber.Ctx) error {
|
|||||||
}
|
}
|
||||||
hourlyAverageResponseTime, err := store.Get().GetHourlyAverageResponseTimeByKey(c.Params("key"), from, time.Now())
|
hourlyAverageResponseTime, err := store.Get().GetHourlyAverageResponseTimeByKey(c.Params("key"), from, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrEndpointNotFound {
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
return c.Status(404).SendString(err.Error())
|
return c.Status(404).SendString(err.Error())
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
} else if errors.Is(err, common.ErrInvalidTimeRange) {
|
||||||
return c.Status(400).SendString(err.Error())
|
return c.Status(400).SendString(err.Error())
|
||||||
}
|
}
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
@@ -111,7 +112,7 @@ func ResponseTimeChart(c *fiber.Ctx) error {
|
|||||||
c.Set("Expires", "0")
|
c.Set("Expires", "0")
|
||||||
c.Status(http.StatusOK)
|
c.Status(http.StatusOK)
|
||||||
if err := graph.Render(chart.SVG, c); err != nil {
|
if err := graph.Render(chart.SVG, c); err != nil {
|
||||||
log.Println("[api][ResponseTimeChart] Failed to render response time chart:", err.Error())
|
log.Println("[api.ResponseTimeChart] Failed to render response time chart:", err.Error())
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
+10
-9
@@ -2,6 +2,7 @@ package api
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
@@ -26,19 +27,19 @@ func EndpointStatuses(cfg *config.Config) fiber.Handler {
|
|||||||
if !exists {
|
if !exists {
|
||||||
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
|
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[api][EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
|
log.Printf("[api.EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
}
|
}
|
||||||
// ALPHA: Retrieve endpoint statuses from remote instances
|
// ALPHA: Retrieve endpoint statuses from remote instances
|
||||||
if endpointStatusesFromRemote, err := getEndpointStatusesFromRemoteInstances(cfg.Remote); err != nil {
|
if endpointStatusesFromRemote, err := getEndpointStatusesFromRemoteInstances(cfg.Remote); err != nil {
|
||||||
log.Printf("[handler][EndpointStatuses] Silently failed to retrieve endpoint statuses from remote: %s", err.Error())
|
log.Printf("[handler.EndpointStatuses] Silently failed to retrieve endpoint statuses from remote: %s", err.Error())
|
||||||
} else if endpointStatusesFromRemote != nil {
|
} else if endpointStatusesFromRemote != nil {
|
||||||
endpointStatuses = append(endpointStatuses, endpointStatusesFromRemote...)
|
endpointStatuses = append(endpointStatuses, endpointStatusesFromRemote...)
|
||||||
}
|
}
|
||||||
// Marshal endpoint statuses to JSON
|
// Marshal endpoint statuses to JSON
|
||||||
data, err = json.Marshal(endpointStatuses)
|
data, err = json.Marshal(endpointStatuses)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[api][EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
|
log.Printf("[api.EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
|
||||||
return c.Status(500).SendString("unable to marshal object to JSON")
|
return c.Status(500).SendString("unable to marshal object to JSON")
|
||||||
}
|
}
|
||||||
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
|
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
|
||||||
@@ -64,13 +65,13 @@ func getEndpointStatusesFromRemoteInstances(remoteConfig *remote.Config) ([]*cor
|
|||||||
body, err := io.ReadAll(response.Body)
|
body, err := io.ReadAll(response.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = response.Body.Close()
|
_ = response.Body.Close()
|
||||||
log.Printf("[handler][getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
|
log.Printf("[api.getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
var endpointStatuses []*core.EndpointStatus
|
var endpointStatuses []*core.EndpointStatus
|
||||||
if err = json.Unmarshal(body, &endpointStatuses); err != nil {
|
if err = json.Unmarshal(body, &endpointStatuses); err != nil {
|
||||||
_ = response.Body.Close()
|
_ = response.Body.Close()
|
||||||
log.Printf("[handler][getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
|
log.Printf("[api.getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
_ = response.Body.Close()
|
_ = response.Body.Close()
|
||||||
@@ -87,19 +88,19 @@ func EndpointStatus(c *fiber.Ctx) error {
|
|||||||
page, pageSize := extractPageAndPageSizeFromRequest(c)
|
page, pageSize := extractPageAndPageSizeFromRequest(c)
|
||||||
endpointStatus, err := store.Get().GetEndpointStatusByKey(c.Params("key"), paging.NewEndpointStatusParams().WithResults(page, pageSize).WithEvents(1, common.MaximumNumberOfEvents))
|
endpointStatus, err := store.Get().GetEndpointStatusByKey(c.Params("key"), paging.NewEndpointStatusParams().WithResults(page, pageSize).WithEvents(1, common.MaximumNumberOfEvents))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrEndpointNotFound {
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
return c.Status(404).SendString(err.Error())
|
return c.Status(404).SendString(err.Error())
|
||||||
}
|
}
|
||||||
log.Printf("[api][EndpointStatus] Failed to retrieve endpoint status: %s", err.Error())
|
log.Printf("[api.EndpointStatus] Failed to retrieve endpoint status: %s", err.Error())
|
||||||
return c.Status(500).SendString(err.Error())
|
return c.Status(500).SendString(err.Error())
|
||||||
}
|
}
|
||||||
if endpointStatus == nil { // XXX: is this check necessary?
|
if endpointStatus == nil { // XXX: is this check necessary?
|
||||||
log.Printf("[api][EndpointStatus] Endpoint with key=%s not found", c.Params("key"))
|
log.Printf("[api.EndpointStatus] Endpoint with key=%s not found", c.Params("key"))
|
||||||
return c.Status(404).SendString("not found")
|
return c.Status(404).SendString("not found")
|
||||||
}
|
}
|
||||||
output, err := json.Marshal(endpointStatus)
|
output, err := json.Marshal(endpointStatus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[api][EndpointStatus] Unable to marshal object to JSON: %s", err.Error())
|
log.Printf("[api.EndpointStatus] Unable to marshal object to JSON: %s", err.Error())
|
||||||
return c.Status(500).SendString("unable to marshal object to JSON")
|
return c.Status(500).SendString("unable to marshal object to JSON")
|
||||||
}
|
}
|
||||||
c.Set("Content-Type", "application/json")
|
c.Set("Content-Type", "application/json")
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v5/config"
|
||||||
|
"github.com/TwiN/gatus/v5/core"
|
||||||
|
"github.com/TwiN/gatus/v5/storage/store"
|
||||||
|
"github.com/TwiN/gatus/v5/storage/store/common"
|
||||||
|
"github.com/TwiN/gatus/v5/watchdog"
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CreateExternalEndpointResult(cfg *config.Config) fiber.Handler {
|
||||||
|
return func(c *fiber.Ctx) error {
|
||||||
|
// Check if the success query parameter is present
|
||||||
|
success, exists := c.Queries()["success"]
|
||||||
|
if !exists || (success != "true" && success != "false") {
|
||||||
|
return c.Status(400).SendString("missing or invalid success query parameter")
|
||||||
|
}
|
||||||
|
// Check if the authorization bearer token header is correct
|
||||||
|
authorizationHeader := string(c.Request().Header.Peek("Authorization"))
|
||||||
|
if !strings.HasPrefix(authorizationHeader, "Bearer ") {
|
||||||
|
return c.Status(401).SendString("invalid Authorization header")
|
||||||
|
}
|
||||||
|
token := strings.TrimSpace(strings.TrimPrefix(authorizationHeader, "Bearer "))
|
||||||
|
if len(token) == 0 {
|
||||||
|
return c.Status(401).SendString("bearer token must not be empty")
|
||||||
|
}
|
||||||
|
key := c.Params("key")
|
||||||
|
externalEndpoint := cfg.GetExternalEndpointByKey(key)
|
||||||
|
if externalEndpoint == nil {
|
||||||
|
log.Printf("[api.CreateExternalEndpointResult] External endpoint with key=%s not found", key)
|
||||||
|
return c.Status(404).SendString("not found")
|
||||||
|
}
|
||||||
|
if externalEndpoint.Token != token {
|
||||||
|
log.Printf("[api.CreateExternalEndpointResult] Invalid token for external endpoint with key=%s", key)
|
||||||
|
return c.Status(401).SendString("invalid token")
|
||||||
|
}
|
||||||
|
// Persist the result in the storage
|
||||||
|
result := &core.Result{
|
||||||
|
Timestamp: time.Now(),
|
||||||
|
Success: c.QueryBool("success"),
|
||||||
|
Errors: []string{},
|
||||||
|
}
|
||||||
|
convertedEndpoint := externalEndpoint.ToEndpoint()
|
||||||
|
if err := store.Get().Insert(convertedEndpoint, result); err != nil {
|
||||||
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
|
return c.Status(404).SendString(err.Error())
|
||||||
|
}
|
||||||
|
log.Printf("[api.CreateExternalEndpointResult] Failed to insert result in storage: %s", err.Error())
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
log.Printf("[api.CreateExternalEndpointResult] Successfully inserted result for external endpoint with key=%s and success=%s", c.Params("key"), success)
|
||||||
|
// Check if an alert should be triggered or resolved
|
||||||
|
if !cfg.Maintenance.IsUnderMaintenance() {
|
||||||
|
watchdog.HandleAlerting(convertedEndpoint, result, cfg.Alerting, cfg.Debug)
|
||||||
|
externalEndpoint.NumberOfSuccessesInARow = convertedEndpoint.NumberOfSuccessesInARow
|
||||||
|
externalEndpoint.NumberOfFailuresInARow = convertedEndpoint.NumberOfFailuresInARow
|
||||||
|
}
|
||||||
|
// Return the result
|
||||||
|
return c.Status(200).SendString("")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v5/alerting"
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/provider/discord"
|
||||||
|
"github.com/TwiN/gatus/v5/config"
|
||||||
|
"github.com/TwiN/gatus/v5/config/maintenance"
|
||||||
|
"github.com/TwiN/gatus/v5/core"
|
||||||
|
"github.com/TwiN/gatus/v5/storage/store"
|
||||||
|
"github.com/TwiN/gatus/v5/storage/store/common/paging"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateExternalEndpointResult(t *testing.T) {
|
||||||
|
defer store.Get().Clear()
|
||||||
|
defer cache.Clear()
|
||||||
|
cfg := &config.Config{
|
||||||
|
Alerting: &alerting.Config{
|
||||||
|
Discord: &discord.AlertProvider{},
|
||||||
|
},
|
||||||
|
ExternalEndpoints: []*core.ExternalEndpoint{
|
||||||
|
{
|
||||||
|
Name: "n",
|
||||||
|
Group: "g",
|
||||||
|
Token: "token",
|
||||||
|
Alerts: []*alert.Alert{
|
||||||
|
{
|
||||||
|
Type: alert.TypeDiscord,
|
||||||
|
FailureThreshold: 2,
|
||||||
|
SuccessThreshold: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Maintenance: &maintenance.Config{},
|
||||||
|
}
|
||||||
|
api := New(cfg)
|
||||||
|
router := api.Router()
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Path string
|
||||||
|
AuthorizationHeaderBearerToken string
|
||||||
|
ExpectedCode int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "no-token",
|
||||||
|
Path: "/api/v1/endpoints/g_n/external?success=true",
|
||||||
|
AuthorizationHeaderBearerToken: "",
|
||||||
|
ExpectedCode: 401,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "bad-token",
|
||||||
|
Path: "/api/v1/endpoints/g_n/external?success=true",
|
||||||
|
AuthorizationHeaderBearerToken: "Bearer bad-token",
|
||||||
|
ExpectedCode: 401,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "bad-key",
|
||||||
|
Path: "/api/v1/endpoints/bad_key/external?success=true",
|
||||||
|
AuthorizationHeaderBearerToken: "Bearer token",
|
||||||
|
ExpectedCode: 404,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "good-token-success-true",
|
||||||
|
Path: "/api/v1/endpoints/g_n/external?success=true",
|
||||||
|
AuthorizationHeaderBearerToken: "Bearer token",
|
||||||
|
ExpectedCode: 200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "good-token-success-false",
|
||||||
|
Path: "/api/v1/endpoints/g_n/external?success=false",
|
||||||
|
AuthorizationHeaderBearerToken: "Bearer token",
|
||||||
|
ExpectedCode: 200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "good-token-success-false-again",
|
||||||
|
Path: "/api/v1/endpoints/g_n/external?success=false",
|
||||||
|
AuthorizationHeaderBearerToken: "Bearer token",
|
||||||
|
ExpectedCode: 200,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest("POST", scenario.Path, http.NoBody)
|
||||||
|
if len(scenario.AuthorizationHeaderBearerToken) > 0 {
|
||||||
|
request.Header.Set("Authorization", scenario.AuthorizationHeaderBearerToken)
|
||||||
|
}
|
||||||
|
response, err := router.Test(request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != scenario.ExpectedCode {
|
||||||
|
t.Errorf("%s %s should have returned %d, but returned %d instead", request.Method, request.URL, scenario.ExpectedCode, response.StatusCode)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
t.Run("verify-end-results", func(t *testing.T) {
|
||||||
|
endpointStatus, err := store.Get().GetEndpointStatus("g", "n", paging.NewEndpointStatusParams().WithResults(1, 10))
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("failed to get endpoint status: %s", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if endpointStatus.Key != "g_n" {
|
||||||
|
t.Errorf("expected key to be g_n but got %s", endpointStatus.Key)
|
||||||
|
}
|
||||||
|
if len(endpointStatus.Results) != 3 {
|
||||||
|
t.Errorf("expected 3 results but got %d", len(endpointStatus.Results))
|
||||||
|
}
|
||||||
|
if !endpointStatus.Results[0].Success {
|
||||||
|
t.Errorf("expected first result to be successful")
|
||||||
|
}
|
||||||
|
if endpointStatus.Results[1].Success {
|
||||||
|
t.Errorf("expected second result to be unsuccessful")
|
||||||
|
}
|
||||||
|
if endpointStatus.Results[2].Success {
|
||||||
|
t.Errorf("expected third result to be unsuccessful")
|
||||||
|
}
|
||||||
|
externalEndpointFromConfig := cfg.GetExternalEndpointByKey("g_n")
|
||||||
|
if externalEndpointFromConfig.NumberOfFailuresInARow != 2 {
|
||||||
|
t.Errorf("expected 2 failures in a row but got %d", externalEndpointFromConfig.NumberOfFailuresInARow)
|
||||||
|
}
|
||||||
|
if externalEndpointFromConfig.NumberOfSuccessesInARow != 0 {
|
||||||
|
t.Errorf("expected 0 successes in a row but got %d", externalEndpointFromConfig.NumberOfSuccessesInARow)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
+2
-2
@@ -15,14 +15,14 @@ func SinglePageApplication(ui *ui.Config) fiber.Handler {
|
|||||||
t, err := template.ParseFS(static.FileSystem, static.IndexPath)
|
t, err := template.ParseFS(static.FileSystem, static.IndexPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
|
// This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
|
||||||
log.Println("[api][SinglePageApplication] Failed to parse template. This should never happen, because the template is validated on start. Error:", err.Error())
|
log.Println("[api.SinglePageApplication] Failed to parse template. This should never happen, because the template is validated on start. Error:", err.Error())
|
||||||
return c.Status(500).SendString("Failed to parse template. This should never happen, because the template is validated on start.")
|
return c.Status(500).SendString("Failed to parse template. This should never happen, because the template is validated on start.")
|
||||||
}
|
}
|
||||||
c.Set("Content-Type", "text/html")
|
c.Set("Content-Type", "text/html")
|
||||||
err = t.Execute(c, ui)
|
err = t.Execute(c, ui)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
|
// This should never happen, because ui.ValidateAndSetDefaults validates that the template works.
|
||||||
log.Println("[api][SinglePageApplication] Failed to execute template. This should never happen, because the template is validated on start. Error:", err.Error())
|
log.Println("[api.SinglePageApplication] Failed to execute template. This should never happen, because the template is validated on start. Error:", err.Error())
|
||||||
return c.Status(500).SendString("Failed to parse template. This should never happen, because the template is validated on start.")
|
return c.Status(500).SendString("Failed to parse template. This should never happen, because the template is validated on start.")
|
||||||
}
|
}
|
||||||
return c.SendStatus(200)
|
return c.SendStatus(200)
|
||||||
|
|||||||
+45
-1
@@ -2,6 +2,7 @@ package client
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -276,7 +277,7 @@ func TestHttpClientProvidesOAuth2BearerToken(t *testing.T) {
|
|||||||
// to us as `X-Org-Authorization` header, we check here if the value matches
|
// to us as `X-Org-Authorization` header, we check here if the value matches
|
||||||
// our expected token `secret-token`
|
// our expected token `secret-token`
|
||||||
if response.Header.Get("X-Org-Authorization") != "Bearer secret-token" {
|
if response.Header.Get("X-Org-Authorization") != "Bearer secret-token" {
|
||||||
t.Error("exptected `secret-token` as Bearer token in the mocked response header `X-Org-Authorization`, but got", response.Header.Get("X-Org-Authorization"))
|
t.Error("expected `secret-token` as Bearer token in the mocked response header `X-Org-Authorization`, but got", response.Header.Get("X-Org-Authorization"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,3 +291,46 @@ func TestQueryWebSocket(t *testing.T) {
|
|||||||
t.Error("expected an error due to the target not being websocket-friendly")
|
t.Error("expected an error due to the target not being websocket-friendly")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTlsRenegotiation(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
cfg TLSConfig
|
||||||
|
expectedConfig tls.RenegotiationSupport
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "default",
|
||||||
|
cfg: TLSConfig{CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/cert.key"},
|
||||||
|
expectedConfig: tls.RenegotiateNever,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "never",
|
||||||
|
cfg: TLSConfig{RenegotiationSupport: "never", CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/cert.key"},
|
||||||
|
expectedConfig: tls.RenegotiateNever,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "once",
|
||||||
|
cfg: TLSConfig{RenegotiationSupport: "once", CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/cert.key"},
|
||||||
|
expectedConfig: tls.RenegotiateOnceAsClient,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "freely",
|
||||||
|
cfg: TLSConfig{RenegotiationSupport: "freely", CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/cert.key"},
|
||||||
|
expectedConfig: tls.RenegotiateFreelyAsClient,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "not-valid-and-broken",
|
||||||
|
cfg: TLSConfig{RenegotiationSupport: "invalid", CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/cert.key"},
|
||||||
|
expectedConfig: tls.RenegotiateNever,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
tls := &tls.Config{}
|
||||||
|
tlsConfig := configureTLS(tls, test.cfg)
|
||||||
|
if tlsConfig.Renegotiation != test.expectedConfig {
|
||||||
|
t.Errorf("expected tls renegotiation to be %v, but got %v", test.expectedConfig, tls.Renegotiation)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+71
-10
@@ -26,6 +26,7 @@ var (
|
|||||||
ErrInvalidDNSResolverPort = errors.New("invalid DNS resolver port")
|
ErrInvalidDNSResolverPort = errors.New("invalid DNS resolver port")
|
||||||
ErrInvalidClientOAuth2Config = errors.New("invalid oauth2 configuration: must define all fields for client credentials flow (token-url, client-id, client-secret, scopes)")
|
ErrInvalidClientOAuth2Config = errors.New("invalid oauth2 configuration: must define all fields for client credentials flow (token-url, client-id, client-secret, scopes)")
|
||||||
ErrInvalidClientIAPConfig = errors.New("invalid Identity-Aware-Proxy configuration: must define all fields for Google Identity-Aware-Proxy programmatic authentication (audience)")
|
ErrInvalidClientIAPConfig = errors.New("invalid Identity-Aware-Proxy configuration: must define all fields for Google Identity-Aware-Proxy programmatic authentication (audience)")
|
||||||
|
ErrInvalidClientTLSConfig = errors.New("invalid TLS configuration: certificate-file and private-key-file must be specified")
|
||||||
|
|
||||||
defaultConfig = Config{
|
defaultConfig = Config{
|
||||||
Insecure: false,
|
Insecure: false,
|
||||||
@@ -72,6 +73,9 @@ type Config struct {
|
|||||||
|
|
||||||
// Network (ip, ip4 or ip6) for the ICMP client
|
// Network (ip, ip4 or ip6) for the ICMP client
|
||||||
Network string `yaml:"network"`
|
Network string `yaml:"network"`
|
||||||
|
|
||||||
|
// TLS configuration (optional)
|
||||||
|
TLS *TLSConfig `yaml:"tls,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DNSResolverConfig is the parsed configuration from the DNSResolver config string.
|
// DNSResolverConfig is the parsed configuration from the DNSResolver config string.
|
||||||
@@ -94,6 +98,17 @@ type IAPConfig struct {
|
|||||||
Audience string `yaml:"audience"` // e.g. "toto.apps.googleusercontent.com"
|
Audience string `yaml:"audience"` // e.g. "toto.apps.googleusercontent.com"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TLSConfig is the configuration for mTLS configurations
|
||||||
|
type TLSConfig struct {
|
||||||
|
// CertificateFile is the public certificate for TLS in PEM format.
|
||||||
|
CertificateFile string `yaml:"certificate-file,omitempty"`
|
||||||
|
|
||||||
|
// PrivateKeyFile is the private key file for TLS in PEM format.
|
||||||
|
PrivateKeyFile string `yaml:"private-key-file,omitempty"`
|
||||||
|
|
||||||
|
RenegotiationSupport string `yaml:"renegotiation,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// ValidateAndSetDefaults validates the client configuration and sets the default values if necessary
|
// ValidateAndSetDefaults validates the client configuration and sets the default values if necessary
|
||||||
func (c *Config) ValidateAndSetDefaults() error {
|
func (c *Config) ValidateAndSetDefaults() error {
|
||||||
if c.Timeout < time.Millisecond {
|
if c.Timeout < time.Millisecond {
|
||||||
@@ -111,6 +126,11 @@ func (c *Config) ValidateAndSetDefaults() error {
|
|||||||
if c.HasIAPConfig() && !c.IAPConfig.isValid() {
|
if c.HasIAPConfig() && !c.IAPConfig.isValid() {
|
||||||
return ErrInvalidClientIAPConfig
|
return ErrInvalidClientIAPConfig
|
||||||
}
|
}
|
||||||
|
if c.HasTlsConfig() {
|
||||||
|
if err := c.TLS.isValid(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,6 +176,11 @@ func (c *Config) HasIAPConfig() bool {
|
|||||||
return c.IAPConfig != nil
|
return c.IAPConfig != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HasTlsConfig returns true if the client has client certificate parameters
|
||||||
|
func (c *Config) HasTlsConfig() bool {
|
||||||
|
return c.TLS != nil && len(c.TLS.CertificateFile) > 0 && len(c.TLS.PrivateKeyFile) > 0
|
||||||
|
}
|
||||||
|
|
||||||
// isValid() returns true if the IAP configuration is valid
|
// isValid() returns true if the IAP configuration is valid
|
||||||
func (c *IAPConfig) isValid() bool {
|
func (c *IAPConfig) isValid() bool {
|
||||||
return len(c.Audience) > 0
|
return len(c.Audience) > 0
|
||||||
@@ -166,8 +191,26 @@ func (c *OAuth2Config) isValid() bool {
|
|||||||
return len(c.TokenURL) > 0 && len(c.ClientID) > 0 && len(c.ClientSecret) > 0 && len(c.Scopes) > 0
|
return len(c.TokenURL) > 0 && len(c.ClientID) > 0 && len(c.ClientSecret) > 0 && len(c.Scopes) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isValid() returns nil if the client tls certificates are valid, otherwise returns an error
|
||||||
|
func (t *TLSConfig) isValid() error {
|
||||||
|
if len(t.CertificateFile) > 0 && len(t.PrivateKeyFile) > 0 {
|
||||||
|
_, err := tls.LoadX509KeyPair(t.CertificateFile, t.PrivateKeyFile)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ErrInvalidClientTLSConfig
|
||||||
|
}
|
||||||
|
|
||||||
// GetHTTPClient return an HTTP client matching the Config's parameters.
|
// GetHTTPClient return an HTTP client matching the Config's parameters.
|
||||||
func (c *Config) getHTTPClient() *http.Client {
|
func (c *Config) getHTTPClient() *http.Client {
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
InsecureSkipVerify: c.Insecure,
|
||||||
|
}
|
||||||
|
if c.HasTlsConfig() && c.TLS.isValid() == nil {
|
||||||
|
tlsConfig = configureTLS(tlsConfig, *c.TLS)
|
||||||
|
}
|
||||||
if c.httpClient == nil {
|
if c.httpClient == nil {
|
||||||
c.httpClient = &http.Client{
|
c.httpClient = &http.Client{
|
||||||
Timeout: c.Timeout,
|
Timeout: c.Timeout,
|
||||||
@@ -175,9 +218,7 @@ func (c *Config) getHTTPClient() *http.Client {
|
|||||||
MaxIdleConns: 100,
|
MaxIdleConns: 100,
|
||||||
MaxIdleConnsPerHost: 20,
|
MaxIdleConnsPerHost: 20,
|
||||||
Proxy: http.ProxyFromEnvironment,
|
Proxy: http.ProxyFromEnvironment,
|
||||||
TLSClientConfig: &tls.Config{
|
TLSClientConfig: tlsConfig,
|
||||||
InsecureSkipVerify: c.Insecure,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
if c.IgnoreRedirect {
|
if c.IgnoreRedirect {
|
||||||
@@ -191,7 +232,7 @@ func (c *Config) getHTTPClient() *http.Client {
|
|||||||
if c.ProxyURL != "" {
|
if c.ProxyURL != "" {
|
||||||
proxyURL, err := url.Parse(c.ProxyURL)
|
proxyURL, err := url.Parse(c.ProxyURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("[client][getHTTPClient] THIS SHOULD NOT HAPPEN. Silently ignoring custom proxy due to error:", err.Error())
|
log.Println("[client.getHTTPClient] THIS SHOULD NOT HAPPEN. Silently ignoring custom proxy due to error:", err.Error())
|
||||||
} else {
|
} else {
|
||||||
c.httpClient.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyURL)
|
c.httpClient.Transport.(*http.Transport).Proxy = http.ProxyURL(proxyURL)
|
||||||
}
|
}
|
||||||
@@ -201,7 +242,7 @@ func (c *Config) getHTTPClient() *http.Client {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
// We're ignoring the error, because it should have been validated on startup ValidateAndSetDefaults.
|
// We're ignoring the error, because it should have been validated on startup ValidateAndSetDefaults.
|
||||||
// It shouldn't happen, but if it does, we'll log it... Better safe than sorry ;)
|
// It shouldn't happen, but if it does, we'll log it... Better safe than sorry ;)
|
||||||
log.Println("[client][getHTTPClient] THIS SHOULD NOT HAPPEN. Silently ignoring invalid DNS resolver due to error:", err.Error())
|
log.Println("[client.getHTTPClient] THIS SHOULD NOT HAPPEN. Silently ignoring invalid DNS resolver due to error:", err.Error())
|
||||||
} else {
|
} else {
|
||||||
dialer := &net.Dialer{
|
dialer := &net.Dialer{
|
||||||
Resolver: &net.Resolver{
|
Resolver: &net.Resolver{
|
||||||
@@ -218,7 +259,7 @@ func (c *Config) getHTTPClient() *http.Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if c.HasOAuth2Config() && c.HasIAPConfig() {
|
if c.HasOAuth2Config() && c.HasIAPConfig() {
|
||||||
log.Println("[client][getHTTPClient] Error: Both Identity-Aware-Proxy and Oauth2 configuration are present.")
|
log.Println("[client.getHTTPClient] Error: Both Identity-Aware-Proxy and Oauth2 configuration are present.")
|
||||||
} else if c.HasOAuth2Config() {
|
} else if c.HasOAuth2Config() {
|
||||||
c.httpClient = configureOAuth2(c.httpClient, *c.OAuth2Config)
|
c.httpClient = configureOAuth2(c.httpClient, *c.OAuth2Config)
|
||||||
} else if c.HasIAPConfig() {
|
} else if c.HasIAPConfig() {
|
||||||
@@ -233,18 +274,18 @@ func (c *Config) getHTTPClient() *http.Client {
|
|||||||
func validateIAPToken(ctx context.Context, c IAPConfig) bool {
|
func validateIAPToken(ctx context.Context, c IAPConfig) bool {
|
||||||
ts, err := idtoken.NewTokenSource(ctx, c.Audience)
|
ts, err := idtoken.NewTokenSource(ctx, c.Audience)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("[client][ValidateIAPToken] Claiming Identity token failed. error:", err.Error())
|
log.Println("[client.ValidateIAPToken] Claiming Identity token failed. error:", err.Error())
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
tok, err := ts.Token()
|
tok, err := ts.Token()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("[client][ValidateIAPToken] Get Identity-Aware-Proxy token failed. error:", err.Error())
|
log.Println("[client.ValidateIAPToken] Get Identity-Aware-Proxy token failed. error:", err.Error())
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
payload, err := idtoken.Validate(ctx, tok.AccessToken, c.Audience)
|
payload, err := idtoken.Validate(ctx, tok.AccessToken, c.Audience)
|
||||||
_ = payload
|
_ = payload
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("[client][ValidateIAPToken] Token Validation failed. error:", err.Error())
|
log.Println("[client.ValidateIAPToken] Token Validation failed. error:", err.Error())
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@@ -257,7 +298,7 @@ func configureIAP(httpClient *http.Client, c IAPConfig) *http.Client {
|
|||||||
if validateIAPToken(ctx, c) {
|
if validateIAPToken(ctx, c) {
|
||||||
ts, err := idtoken.NewTokenSource(ctx, c.Audience)
|
ts, err := idtoken.NewTokenSource(ctx, c.Audience)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("[client][ConfigureIAP] Claiming Token Source failed. error:", err.Error())
|
log.Println("[client.ConfigureIAP] Claiming Token Source failed. error:", err.Error())
|
||||||
return httpClient
|
return httpClient
|
||||||
}
|
}
|
||||||
client := oauth2.NewClient(ctx, ts)
|
client := oauth2.NewClient(ctx, ts)
|
||||||
@@ -281,3 +322,23 @@ func configureOAuth2(httpClient *http.Client, c OAuth2Config) *http.Client {
|
|||||||
client.Timeout = httpClient.Timeout
|
client.Timeout = httpClient.Timeout
|
||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// configureTLS returns a TLS Config that will enable mTLS
|
||||||
|
func configureTLS(tlsConfig *tls.Config, c TLSConfig) *tls.Config {
|
||||||
|
clientTLSCert, err := tls.LoadX509KeyPair(c.CertificateFile, c.PrivateKeyFile)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tlsConfig.Certificates = []tls.Certificate{clientTLSCert}
|
||||||
|
tlsConfig.Renegotiation = tls.RenegotiateNever
|
||||||
|
|
||||||
|
renegotionSupport := map[string]tls.RenegotiationSupport{
|
||||||
|
"once": tls.RenegotiateOnceAsClient,
|
||||||
|
"freely": tls.RenegotiateFreelyAsClient,
|
||||||
|
"never": tls.RenegotiateNever,
|
||||||
|
}
|
||||||
|
if val, ok := renegotionSupport[c.RenegotiationSupport]; ok {
|
||||||
|
tlsConfig.Renegotiation = val
|
||||||
|
}
|
||||||
|
return tlsConfig
|
||||||
|
}
|
||||||
@@ -106,3 +106,66 @@ func TestConfig_getHTTPClient_withCustomProxyURL(t *testing.T) {
|
|||||||
t.Errorf("expected Config.ProxyURL to set the HTTP client's proxy to %s", proxyURL)
|
t.Errorf("expected Config.ProxyURL to set the HTTP client's proxy to %s", proxyURL)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestConfig_TlsIsValid(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
cfg *Config
|
||||||
|
expectedErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "good-tls-config",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/cert.key"}},
|
||||||
|
expectedErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing-certificate-file",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "doesnotexist", PrivateKeyFile: "../testdata/cert.key"}},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad-certificate-file",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "../testdata/badcert.pem", PrivateKeyFile: "../testdata/cert.key"}},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "no-certificate-file",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "", PrivateKeyFile: "../testdata/cert.key"}},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing-private-key-file",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "doesnotexist"}},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "no-private-key-file",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "../testdata/cert.pem", PrivateKeyFile: ""}},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad-private-key-file",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "../testdata/cert.pem", PrivateKeyFile: "../testdata/badcert.key"}},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad-certificate-and-private-key-file",
|
||||||
|
cfg: &Config{TLS: &TLSConfig{CertificateFile: "../testdata/badcert.pem", PrivateKeyFile: "../testdata/badcert.key"}},
|
||||||
|
expectedErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
err := test.cfg.TLS.isValid()
|
||||||
|
if (err != nil) != test.expectedErr {
|
||||||
|
t.Errorf("expected the existence of an error to be %v, got %v", test.expectedErr, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !test.expectedErr {
|
||||||
|
if test.cfg.TLS.isValid() != nil {
|
||||||
|
t.Error("cfg.TLS.isValid() returned an error even though no error was expected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+47
-18
@@ -67,15 +67,18 @@ type Config struct {
|
|||||||
// Disabling this may lead to inaccurate response times
|
// Disabling this may lead to inaccurate response times
|
||||||
DisableMonitoringLock bool `yaml:"disable-monitoring-lock,omitempty"`
|
DisableMonitoringLock bool `yaml:"disable-monitoring-lock,omitempty"`
|
||||||
|
|
||||||
// Security Configuration for securing access to Gatus
|
// Security is the configuration for securing access to Gatus
|
||||||
Security *security.Config `yaml:"security,omitempty"`
|
Security *security.Config `yaml:"security,omitempty"`
|
||||||
|
|
||||||
// Alerting Configuration for alerting
|
// Alerting is the configuration for alerting providers
|
||||||
Alerting *alerting.Config `yaml:"alerting,omitempty"`
|
Alerting *alerting.Config `yaml:"alerting,omitempty"`
|
||||||
|
|
||||||
// Endpoints List of endpoints to monitor
|
// Endpoints is the list of endpoints to monitor
|
||||||
Endpoints []*core.Endpoint `yaml:"endpoints,omitempty"`
|
Endpoints []*core.Endpoint `yaml:"endpoints,omitempty"`
|
||||||
|
|
||||||
|
// ExternalEndpoints is the list of all external endpoints
|
||||||
|
ExternalEndpoints []*core.ExternalEndpoint `yaml:"external-endpoints,omitempty"`
|
||||||
|
|
||||||
// Storage is the configuration for how the data is stored
|
// Storage is the configuration for how the data is stored
|
||||||
Storage *storage.Config `yaml:"storage,omitempty"`
|
Storage *storage.Config `yaml:"storage,omitempty"`
|
||||||
|
|
||||||
@@ -100,7 +103,6 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (config *Config) GetEndpointByKey(key string) *core.Endpoint {
|
func (config *Config) GetEndpointByKey(key string) *core.Endpoint {
|
||||||
// TODO: Should probably add a mutex here to prevent concurrent access
|
|
||||||
for i := 0; i < len(config.Endpoints); i++ {
|
for i := 0; i < len(config.Endpoints); i++ {
|
||||||
ep := config.Endpoints[i]
|
ep := config.Endpoints[i]
|
||||||
if util.ConvertGroupAndEndpointNameToKey(ep.Group, ep.Name) == key {
|
if util.ConvertGroupAndEndpointNameToKey(ep.Group, ep.Name) == key {
|
||||||
@@ -110,9 +112,19 @@ func (config *Config) GetEndpointByKey(key string) *core.Endpoint {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (config *Config) GetExternalEndpointByKey(key string) *core.ExternalEndpoint {
|
||||||
|
for i := 0; i < len(config.ExternalEndpoints); i++ {
|
||||||
|
ee := config.ExternalEndpoints[i]
|
||||||
|
if util.ConvertGroupAndEndpointNameToKey(ee.Group, ee.Name) == key {
|
||||||
|
return ee
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// HasLoadedConfigurationBeenModified returns whether one of the file that the
|
// HasLoadedConfigurationBeenModified returns whether one of 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) HasLoadedConfigurationBeenModified() bool {
|
func (config *Config) HasLoadedConfigurationBeenModified() bool {
|
||||||
lastMod := config.lastFileModTime.Unix()
|
lastMod := config.lastFileModTime.Unix()
|
||||||
fileInfo, err := os.Stat(config.configPath)
|
fileInfo, err := os.Stat(config.configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -125,7 +137,7 @@ func (config Config) HasLoadedConfigurationBeenModified() bool {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
return err == errEarlyReturn
|
return errors.Is(err, errEarlyReturn)
|
||||||
}
|
}
|
||||||
return !fileInfo.ModTime().IsZero() && config.lastFileModTime.Unix() < fileInfo.ModTime().Unix()
|
return !fileInfo.ModTime().IsZero() && config.lastFileModTime.Unix() < fileInfo.ModTime().Unix()
|
||||||
}
|
}
|
||||||
@@ -135,7 +147,7 @@ func (config *Config) UpdateLastFileModTime() {
|
|||||||
config.lastFileModTime = time.Now()
|
config.lastFileModTime = time.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadConfiguration loads the full configuration composed from the main configuration file
|
// LoadConfiguration loads the full configuration composed of the main configuration file
|
||||||
// and all composed configuration files
|
// and all composed configuration files
|
||||||
func LoadConfiguration(configPath string) (*Config, error) {
|
func LoadConfiguration(configPath string) (*Config, error) {
|
||||||
var configBytes []byte
|
var configBytes []byte
|
||||||
@@ -161,13 +173,13 @@ func LoadConfiguration(configPath string) (*Config, error) {
|
|||||||
if fileInfo.IsDir() {
|
if fileInfo.IsDir() {
|
||||||
err := walkConfigDir(configPath, func(path string, d fs.DirEntry, err error) error {
|
err := walkConfigDir(configPath, func(path string, d fs.DirEntry, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[config][LoadConfiguration] Error walking path=%s: %s", path, err)
|
log.Printf("[config.LoadConfiguration] Error walking path=%s: %s", path, err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
log.Printf("[config][LoadConfiguration] Reading configuration from %s", path)
|
log.Printf("[config.LoadConfiguration] Reading configuration from %s", path)
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[config][LoadConfiguration] Error reading configuration from %s: %s", path, err)
|
log.Printf("[config.LoadConfiguration] Error reading configuration from %s: %s", path, err)
|
||||||
return fmt.Errorf("error reading configuration from file %s: %w", path, err)
|
return fmt.Errorf("error reading configuration from file %s: %w", path, err)
|
||||||
}
|
}
|
||||||
configBytes, err = deepmerge.YAML(configBytes, data)
|
configBytes, err = deepmerge.YAML(configBytes, data)
|
||||||
@@ -177,7 +189,7 @@ func LoadConfiguration(configPath string) (*Config, error) {
|
|||||||
return nil, fmt.Errorf("error reading configuration from directory %s: %w", usedConfigPath, err)
|
return nil, fmt.Errorf("error reading configuration from directory %s: %w", usedConfigPath, err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[config][LoadConfiguration] Reading configuration from configFile=%s", configPath)
|
log.Printf("[config.LoadConfiguration] Reading configuration from configFile=%s", configPath)
|
||||||
if data, err := os.ReadFile(usedConfigPath); err != nil {
|
if data, err := os.ReadFile(usedConfigPath); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
@@ -241,6 +253,9 @@ func parseAndValidateConfigBytes(yamlBytes []byte) (config *Config, err error) {
|
|||||||
if err := validateEndpointsConfig(config); err != nil {
|
if err := validateEndpointsConfig(config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := validateExternalEndpointsConfig(config); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if err := validateWebConfig(config); err != nil {
|
if err := validateWebConfig(config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -326,13 +341,26 @@ func validateWebConfig(config *Config) error {
|
|||||||
func validateEndpointsConfig(config *Config) error {
|
func validateEndpointsConfig(config *Config) error {
|
||||||
for _, endpoint := range config.Endpoints {
|
for _, endpoint := range config.Endpoints {
|
||||||
if config.Debug {
|
if config.Debug {
|
||||||
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 fmt.Errorf("invalid endpoint %s: %w", endpoint.DisplayName(), err)
|
return fmt.Errorf("invalid endpoint %s: %w", endpoint.DisplayName(), err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("[config][validateEndpointsConfig] Validated %d endpoints", len(config.Endpoints))
|
log.Printf("[config.validateEndpointsConfig] Validated %d endpoints", len(config.Endpoints))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateExternalEndpointsConfig(config *Config) error {
|
||||||
|
for _, externalEndpoint := range config.ExternalEndpoints {
|
||||||
|
if config.Debug {
|
||||||
|
log.Printf("[config.validateExternalEndpointsConfig] Validating external endpoint '%s'", externalEndpoint.Name)
|
||||||
|
}
|
||||||
|
if err := externalEndpoint.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return fmt.Errorf("invalid external endpoint %s: %w", externalEndpoint.DisplayName(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.Printf("[config.validateExternalEndpointsConfig] Validated %d external endpoints", len(config.ExternalEndpoints))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,7 +368,7 @@ func validateSecurityConfig(config *Config) error {
|
|||||||
if config.Security != nil {
|
if config.Security != nil {
|
||||||
if config.Security.IsValid() {
|
if config.Security.IsValid() {
|
||||||
if config.Debug {
|
if config.Debug {
|
||||||
log.Printf("[config][validateSecurityConfig] Basic security configuration has been validated")
|
log.Printf("[config.validateSecurityConfig] Basic security configuration has been validated")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// If there was an attempt to configure security, then it must mean that some confidential or private
|
// If there was an attempt to configure security, then it must mean that some confidential or private
|
||||||
@@ -357,7 +385,7 @@ func validateSecurityConfig(config *Config) error {
|
|||||||
// sets the default alert values when none are set.
|
// sets the default alert values when none are set.
|
||||||
func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.Endpoint, debug bool) {
|
func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.Endpoint, debug bool) {
|
||||||
if alertingConfig == nil {
|
if alertingConfig == nil {
|
||||||
log.Printf("[config][validateAlertingConfig] Alerting is not configured")
|
log.Printf("[config.validateAlertingConfig] Alerting is not configured")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
alertTypes := []alert.Type{
|
alertTypes := []alert.Type{
|
||||||
@@ -368,6 +396,7 @@ func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.E
|
|||||||
alert.TypeGitLab,
|
alert.TypeGitLab,
|
||||||
alert.TypeGoogleChat,
|
alert.TypeGoogleChat,
|
||||||
alert.TypeGotify,
|
alert.TypeGotify,
|
||||||
|
alert.TypeJetBrainsSpace,
|
||||||
alert.TypeEmail,
|
alert.TypeEmail,
|
||||||
alert.TypeMatrix,
|
alert.TypeMatrix,
|
||||||
alert.TypeMattermost,
|
alert.TypeMattermost,
|
||||||
@@ -392,7 +421,7 @@ func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.E
|
|||||||
for alertIndex, endpointAlert := range endpoint.Alerts {
|
for alertIndex, endpointAlert := range endpoint.Alerts {
|
||||||
if alertType == endpointAlert.Type {
|
if alertType == endpointAlert.Type {
|
||||||
if debug {
|
if debug {
|
||||||
log.Printf("[config][validateAlertingConfig] Parsing alert %d with provider's default alert for provider=%s in endpoint=%s", alertIndex, alertType, endpoint.Name)
|
log.Printf("[config.validateAlertingConfig] Parsing alert %d with provider's default alert for provider=%s in endpoint=%s", alertIndex, alertType, endpoint.Name)
|
||||||
}
|
}
|
||||||
provider.ParseWithDefaultAlert(alertProvider.GetDefaultAlert(), endpointAlert)
|
provider.ParseWithDefaultAlert(alertProvider.GetDefaultAlert(), endpointAlert)
|
||||||
}
|
}
|
||||||
@@ -401,7 +430,7 @@ func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.E
|
|||||||
}
|
}
|
||||||
validProviders = append(validProviders, alertType)
|
validProviders = append(validProviders, alertType)
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[config][validateAlertingConfig] Ignoring provider=%s because configuration is invalid", alertType)
|
log.Printf("[config.validateAlertingConfig] Ignoring provider=%s because configuration is invalid", alertType)
|
||||||
invalidProviders = append(invalidProviders, alertType)
|
invalidProviders = append(invalidProviders, alertType)
|
||||||
alertingConfig.SetAlertingProviderToNil(alertProvider)
|
alertingConfig.SetAlertingProviderToNil(alertProvider)
|
||||||
}
|
}
|
||||||
@@ -409,5 +438,5 @@ func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.E
|
|||||||
invalidProviders = append(invalidProviders, alertType)
|
invalidProviders = append(invalidProviders, alertType)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("[config][validateAlertingConfig] configuredProviders=%s; ignoredProviders=%s", validProviders, invalidProviders)
|
log.Printf("[config.validateAlertingConfig] configuredProviders=%s; ignoredProviders=%s", validProviders, invalidProviders)
|
||||||
}
|
}
|
||||||
+106
-22
@@ -16,6 +16,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v5/alerting/provider/email"
|
"github.com/TwiN/gatus/v5/alerting/provider/email"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/github"
|
"github.com/TwiN/gatus/v5/alerting/provider/github"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/googlechat"
|
"github.com/TwiN/gatus/v5/alerting/provider/googlechat"
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/provider/jetbrainsspace"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
||||||
@@ -303,11 +304,13 @@ func TestParseAndValidateConfigBytes(t *testing.T) {
|
|||||||
storage:
|
storage:
|
||||||
type: sqlite
|
type: sqlite
|
||||||
path: %s
|
path: %s
|
||||||
|
|
||||||
maintenance:
|
maintenance:
|
||||||
enabled: true
|
enabled: true
|
||||||
start: 00:00
|
start: 00:00
|
||||||
duration: 4h
|
duration: 4h
|
||||||
every: [Monday, Thursday]
|
every: [Monday, Thursday]
|
||||||
|
|
||||||
ui:
|
ui:
|
||||||
title: T
|
title: T
|
||||||
header: H
|
header: H
|
||||||
@@ -317,6 +320,16 @@ ui:
|
|||||||
link: "https://example.org"
|
link: "https://example.org"
|
||||||
- name: "Status page"
|
- name: "Status page"
|
||||||
link: "https://status.example.org"
|
link: "https://status.example.org"
|
||||||
|
|
||||||
|
external-endpoints:
|
||||||
|
- name: ext-ep-test
|
||||||
|
group: core
|
||||||
|
token: "potato"
|
||||||
|
alerts:
|
||||||
|
- type: discord
|
||||||
|
description: "healthcheck failed"
|
||||||
|
send-on-resolved: true
|
||||||
|
|
||||||
endpoints:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
url: https://twin.sh/health
|
url: https://twin.sh/health
|
||||||
@@ -357,10 +370,33 @@ endpoints:
|
|||||||
if mc := config.Maintenance; mc == nil || mc.Start != "00:00" || !mc.IsEnabled() || mc.Duration != 4*time.Hour || len(mc.Every) != 2 {
|
if mc := config.Maintenance; mc == nil || mc.Start != "00:00" || !mc.IsEnabled() || mc.Duration != 4*time.Hour || len(mc.Every) != 2 {
|
||||||
t.Error("Expected Config.Maintenance to be configured properly")
|
t.Error("Expected Config.Maintenance to be configured properly")
|
||||||
}
|
}
|
||||||
|
if len(config.ExternalEndpoints) != 1 {
|
||||||
|
t.Error("Should have returned one external endpoint")
|
||||||
|
}
|
||||||
|
if config.ExternalEndpoints[0].Name != "ext-ep-test" {
|
||||||
|
t.Errorf("Name should have been %s", "ext-ep-test")
|
||||||
|
}
|
||||||
|
if config.ExternalEndpoints[0].Group != "core" {
|
||||||
|
t.Errorf("Group should have been %s", "core")
|
||||||
|
}
|
||||||
|
if config.ExternalEndpoints[0].Token != "potato" {
|
||||||
|
t.Errorf("Token should have been %s", "potato")
|
||||||
|
}
|
||||||
|
if len(config.ExternalEndpoints[0].Alerts) != 1 {
|
||||||
|
t.Error("Should have returned one alert")
|
||||||
|
}
|
||||||
|
if config.ExternalEndpoints[0].Alerts[0].Type != alert.TypeDiscord {
|
||||||
|
t.Errorf("Type should have been %s", alert.TypeDiscord)
|
||||||
|
}
|
||||||
|
if config.ExternalEndpoints[0].Alerts[0].FailureThreshold != 3 {
|
||||||
|
t.Errorf("FailureThreshold should have been %d, got %d", 3, config.ExternalEndpoints[0].Alerts[0].FailureThreshold)
|
||||||
|
}
|
||||||
|
if config.ExternalEndpoints[0].Alerts[0].SuccessThreshold != 2 {
|
||||||
|
t.Errorf("SuccessThreshold should have been %d, got %d", 2, config.ExternalEndpoints[0].Alerts[0].SuccessThreshold)
|
||||||
|
}
|
||||||
if len(config.Endpoints) != 3 {
|
if len(config.Endpoints) != 3 {
|
||||||
t.Error("Should have returned two endpoints")
|
t.Error("Should have returned two endpoints")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
if config.Endpoints[0].URL != "https://twin.sh/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
t.Errorf("URL should have been %s", "https://twin.sh/health")
|
||||||
}
|
}
|
||||||
@@ -382,7 +418,6 @@ endpoints:
|
|||||||
if len(config.Endpoints[0].Conditions) != 1 {
|
if len(config.Endpoints[0].Conditions) != 1 {
|
||||||
t.Errorf("There should have been %d conditions", 1)
|
t.Errorf("There should have been %d conditions", 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Endpoints[1].URL != "https://api.github.com/healthz" {
|
if config.Endpoints[1].URL != "https://api.github.com/healthz" {
|
||||||
t.Errorf("URL should have been %s", "https://api.github.com/healthz")
|
t.Errorf("URL should have been %s", "https://api.github.com/healthz")
|
||||||
}
|
}
|
||||||
@@ -706,6 +741,10 @@ alerting:
|
|||||||
to: "+1-234-567-8901"
|
to: "+1-234-567-8901"
|
||||||
teams:
|
teams:
|
||||||
webhook-url: "http://example.com"
|
webhook-url: "http://example.com"
|
||||||
|
jetbrainsspace:
|
||||||
|
project: "foo"
|
||||||
|
channel-id: "bar"
|
||||||
|
token: "baz"
|
||||||
|
|
||||||
endpoints:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
@@ -728,6 +767,7 @@ endpoints:
|
|||||||
success-threshold: 15
|
success-threshold: 15
|
||||||
- type: teams
|
- type: teams
|
||||||
- type: pushover
|
- type: pushover
|
||||||
|
- type: jetbrainsspace
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
@@ -754,8 +794,8 @@ endpoints:
|
|||||||
if config.Endpoints[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if len(config.Endpoints[0].Alerts) != 9 {
|
if len(config.Endpoints[0].Alerts) != 10 {
|
||||||
t.Fatal("There should've been 9 alerts configured")
|
t.Fatal("There should've been 10 alerts configured")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Endpoints[0].Alerts[0].Type != alert.TypeSlack {
|
if config.Endpoints[0].Alerts[0].Type != alert.TypeSlack {
|
||||||
@@ -862,6 +902,12 @@ endpoints:
|
|||||||
if !config.Endpoints[0].Alerts[8].IsEnabled() {
|
if !config.Endpoints[0].Alerts[8].IsEnabled() {
|
||||||
t.Error("The alert should've been enabled")
|
t.Error("The alert should've been enabled")
|
||||||
}
|
}
|
||||||
|
if config.Endpoints[0].Alerts[9].Type != alert.TypeJetBrainsSpace {
|
||||||
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeJetBrainsSpace, config.Endpoints[0].Alerts[9].Type)
|
||||||
|
}
|
||||||
|
if !config.Endpoints[0].Alerts[9].IsEnabled() {
|
||||||
|
t.Error("The alert should've been enabled")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesWithAlertingAndDefaultAlert(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithAlertingAndDefaultAlert(t *testing.T) {
|
||||||
@@ -923,6 +969,14 @@ alerting:
|
|||||||
webhook-url: "http://example.com"
|
webhook-url: "http://example.com"
|
||||||
default-alert:
|
default-alert:
|
||||||
enabled: true
|
enabled: true
|
||||||
|
jetbrainsspace:
|
||||||
|
project: "foo"
|
||||||
|
channel-id: "bar"
|
||||||
|
token: "baz"
|
||||||
|
default-alert:
|
||||||
|
enabled: true
|
||||||
|
failure-threshold: 5
|
||||||
|
success-threshold: 3
|
||||||
|
|
||||||
endpoints:
|
endpoints:
|
||||||
- name: website
|
- name: website
|
||||||
@@ -938,6 +992,7 @@ endpoints:
|
|||||||
- type: twilio
|
- type: twilio
|
||||||
- type: teams
|
- type: teams
|
||||||
- type: pushover
|
- type: pushover
|
||||||
|
- type: jetbrainsspace
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
@@ -1049,6 +1104,21 @@ endpoints:
|
|||||||
if config.Alerting.Teams.GetDefaultAlert() == nil {
|
if config.Alerting.Teams.GetDefaultAlert() == nil {
|
||||||
t.Fatal("Teams.GetDefaultAlert() shouldn't have returned nil")
|
t.Fatal("Teams.GetDefaultAlert() shouldn't have returned nil")
|
||||||
}
|
}
|
||||||
|
if config.Alerting.JetBrainsSpace == nil || !config.Alerting.JetBrainsSpace.IsValid() {
|
||||||
|
t.Fatal("JetBrainsSpace alerting config should've been valid")
|
||||||
|
}
|
||||||
|
if config.Alerting.JetBrainsSpace.GetDefaultAlert() == nil {
|
||||||
|
t.Fatal("JetBrainsSpace.GetDefaultAlert() shouldn't have returned nil")
|
||||||
|
}
|
||||||
|
if config.Alerting.JetBrainsSpace.Project != "foo" {
|
||||||
|
t.Errorf("JetBrainsSpace webhook should've been %s, but was %s", "foo", config.Alerting.JetBrainsSpace.Project)
|
||||||
|
}
|
||||||
|
if config.Alerting.JetBrainsSpace.ChannelID != "bar" {
|
||||||
|
t.Errorf("JetBrainsSpace webhook should've been %s, but was %s", "bar", config.Alerting.JetBrainsSpace.ChannelID)
|
||||||
|
}
|
||||||
|
if config.Alerting.JetBrainsSpace.Token != "baz" {
|
||||||
|
t.Errorf("JetBrainsSpace webhook should've been %s, but was %s", "baz", config.Alerting.JetBrainsSpace.Token)
|
||||||
|
}
|
||||||
|
|
||||||
// Endpoints
|
// Endpoints
|
||||||
if len(config.Endpoints) != 1 {
|
if len(config.Endpoints) != 1 {
|
||||||
@@ -1060,8 +1130,8 @@ endpoints:
|
|||||||
if config.Endpoints[0].Interval != 60*time.Second {
|
if config.Endpoints[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
if len(config.Endpoints[0].Alerts) != 9 {
|
if len(config.Endpoints[0].Alerts) != 10 {
|
||||||
t.Fatal("There should've been 9 alerts configured")
|
t.Fatal("There should've been 10 alerts configured")
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Endpoints[0].Alerts[0].Type != alert.TypeSlack {
|
if config.Endpoints[0].Alerts[0].Type != alert.TypeSlack {
|
||||||
@@ -1178,6 +1248,18 @@ endpoints:
|
|||||||
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[8].SuccessThreshold)
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[8].SuccessThreshold)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if config.Endpoints[0].Alerts[9].Type != alert.TypeJetBrainsSpace {
|
||||||
|
t.Errorf("The type of the alert should've been %s, but it was %s", alert.TypeJetBrainsSpace, config.Endpoints[0].Alerts[9].Type)
|
||||||
|
}
|
||||||
|
if !config.Endpoints[0].Alerts[9].IsEnabled() {
|
||||||
|
t.Error("The alert should've been enabled")
|
||||||
|
}
|
||||||
|
if config.Endpoints[0].Alerts[9].FailureThreshold != 5 {
|
||||||
|
t.Errorf("The default failure threshold of the alert should've been %d, but it was %d", 3, config.Endpoints[0].Alerts[9].FailureThreshold)
|
||||||
|
}
|
||||||
|
if config.Endpoints[0].Alerts[9].SuccessThreshold != 3 {
|
||||||
|
t.Errorf("The default success threshold of the alert should've been %d, but it was %d", 2, config.Endpoints[0].Alerts[9].SuccessThreshold)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesWithAlertingAndDefaultAlertAndMultipleAlertsOfSameTypeWithOverriddenParameters(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithAlertingAndDefaultAlertAndMultipleAlertsOfSameTypeWithOverriddenParameters(t *testing.T) {
|
||||||
@@ -1570,22 +1652,23 @@ func TestParseAndValidateConfigBytesWithNoEndpoints(t *testing.T) {
|
|||||||
|
|
||||||
func TestGetAlertingProviderByAlertType(t *testing.T) {
|
func TestGetAlertingProviderByAlertType(t *testing.T) {
|
||||||
alertingConfig := &alerting.Config{
|
alertingConfig := &alerting.Config{
|
||||||
Custom: &custom.AlertProvider{},
|
Custom: &custom.AlertProvider{},
|
||||||
Discord: &discord.AlertProvider{},
|
Discord: &discord.AlertProvider{},
|
||||||
Email: &email.AlertProvider{},
|
Email: &email.AlertProvider{},
|
||||||
GitHub: &github.AlertProvider{},
|
GitHub: &github.AlertProvider{},
|
||||||
GoogleChat: &googlechat.AlertProvider{},
|
GoogleChat: &googlechat.AlertProvider{},
|
||||||
Matrix: &matrix.AlertProvider{},
|
JetBrainsSpace: &jetbrainsspace.AlertProvider{},
|
||||||
Mattermost: &mattermost.AlertProvider{},
|
Matrix: &matrix.AlertProvider{},
|
||||||
Messagebird: &messagebird.AlertProvider{},
|
Mattermost: &mattermost.AlertProvider{},
|
||||||
Ntfy: &ntfy.AlertProvider{},
|
Messagebird: &messagebird.AlertProvider{},
|
||||||
Opsgenie: &opsgenie.AlertProvider{},
|
Ntfy: &ntfy.AlertProvider{},
|
||||||
PagerDuty: &pagerduty.AlertProvider{},
|
Opsgenie: &opsgenie.AlertProvider{},
|
||||||
Pushover: &pushover.AlertProvider{},
|
PagerDuty: &pagerduty.AlertProvider{},
|
||||||
Slack: &slack.AlertProvider{},
|
Pushover: &pushover.AlertProvider{},
|
||||||
Telegram: &telegram.AlertProvider{},
|
Slack: &slack.AlertProvider{},
|
||||||
Twilio: &twilio.AlertProvider{},
|
Telegram: &telegram.AlertProvider{},
|
||||||
Teams: &teams.AlertProvider{},
|
Twilio: &twilio.AlertProvider{},
|
||||||
|
Teams: &teams.AlertProvider{},
|
||||||
}
|
}
|
||||||
scenarios := []struct {
|
scenarios := []struct {
|
||||||
alertType alert.Type
|
alertType alert.Type
|
||||||
@@ -1596,6 +1679,7 @@ func TestGetAlertingProviderByAlertType(t *testing.T) {
|
|||||||
{alertType: alert.TypeEmail, expected: alertingConfig.Email},
|
{alertType: alert.TypeEmail, expected: alertingConfig.Email},
|
||||||
{alertType: alert.TypeGitHub, expected: alertingConfig.GitHub},
|
{alertType: alert.TypeGitHub, expected: alertingConfig.GitHub},
|
||||||
{alertType: alert.TypeGoogleChat, expected: alertingConfig.GoogleChat},
|
{alertType: alert.TypeGoogleChat, expected: alertingConfig.GoogleChat},
|
||||||
|
{alertType: alert.TypeJetBrainsSpace, expected: alertingConfig.JetBrainsSpace},
|
||||||
{alertType: alert.TypeMatrix, expected: alertingConfig.Matrix},
|
{alertType: alert.TypeMatrix, expected: alertingConfig.Matrix},
|
||||||
{alertType: alert.TypeMattermost, expected: alertingConfig.Mattermost},
|
{alertType: alert.TypeMattermost, expected: alertingConfig.Mattermost},
|
||||||
{alertType: alert.TypeMessagebird, expected: alertingConfig.Messagebird},
|
{alertType: alert.TypeMessagebird, expected: alertingConfig.Messagebird},
|
||||||
|
|||||||
@@ -25,19 +25,19 @@ func Handle(cfg *config.Config) {
|
|||||||
if os.Getenv("ROUTER_TEST") == "true" {
|
if os.Getenv("ROUTER_TEST") == "true" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Println("[controller][Handle] Listening on " + cfg.Web.SocketAddress())
|
log.Println("[controller.Handle] Listening on " + cfg.Web.SocketAddress())
|
||||||
if cfg.Web.HasTLS() {
|
if cfg.Web.HasTLS() {
|
||||||
err := app.ListenTLS(cfg.Web.SocketAddress(), cfg.Web.TLS.CertificateFile, cfg.Web.TLS.PrivateKeyFile)
|
err := app.ListenTLS(cfg.Web.SocketAddress(), cfg.Web.TLS.CertificateFile, cfg.Web.TLS.PrivateKeyFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("[controller][Handle]", err)
|
log.Fatal("[controller.Handle]", err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
err := app.Listen(cfg.Web.SocketAddress())
|
err := app.Listen(cfg.Web.SocketAddress())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("[controller][Handle]", err)
|
log.Fatal("[controller.Handle]", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Println("[controller][Handle] Server has shut down successfully")
|
log.Println("[controller.Handle] Server has shut down successfully")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shutdown stops the server
|
// Shutdown stops the server
|
||||||
|
|||||||
+1
-1
@@ -150,7 +150,7 @@ func (c Condition) evaluate(result *Result, dontResolveFailedConditions bool) bo
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if !success {
|
if !success {
|
||||||
//log.Printf("[Condition][evaluate] Condition '%s' did not succeed because '%s' is false", condition, condition)
|
//log.Printf("[Condition.evaluate] Condition '%s' did not succeed because '%s' is false", condition, condition)
|
||||||
}
|
}
|
||||||
result.ConditionResults = append(result.ConditionResults, &ConditionResult{Condition: conditionToDisplay, Success: success})
|
result.ConditionResults = append(result.ConditionResults, &ConditionResult{Condition: conditionToDisplay, Success: success})
|
||||||
return success
|
return success
|
||||||
|
|||||||
@@ -259,6 +259,27 @@ func TestCondition_evaluate(t *testing.T) {
|
|||||||
ExpectedSuccess: true,
|
ExpectedSuccess: true,
|
||||||
ExpectedOutput: "[BODY][0].id == 1",
|
ExpectedOutput: "[BODY][0].id == 1",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "body-jsonpath-when-body-has-null-parameter",
|
||||||
|
Condition: Condition("[BODY].data == OK"),
|
||||||
|
Result: &Result{Body: []byte(`{"data": null}"`)},
|
||||||
|
ExpectedSuccess: false,
|
||||||
|
ExpectedOutput: "[BODY].data (INVALID) == OK",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "body-jsonpath-when-body-has-array-with-null",
|
||||||
|
Condition: Condition("[BODY].items[0] == OK"),
|
||||||
|
Result: &Result{Body: []byte(`{"items": [null, null]}"`)},
|
||||||
|
ExpectedSuccess: false,
|
||||||
|
ExpectedOutput: "[BODY].items[0] (INVALID) == OK",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "body-jsonpath-when-body-is-null",
|
||||||
|
Condition: Condition("[BODY].data == OK"),
|
||||||
|
Result: &Result{Body: []byte(`null`)},
|
||||||
|
ExpectedSuccess: false,
|
||||||
|
ExpectedOutput: "[BODY].data (INVALID) == OK",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Name: "body-jsonpath-when-body-is-array-but-actual-body-is-not",
|
Name: "body-jsonpath-when-body-is-array-but-actual-body-is-not",
|
||||||
Condition: Condition("[BODY][0].name == test"),
|
Condition: Condition("[BODY][0].name == test"),
|
||||||
|
|||||||
+3
-5
@@ -103,26 +103,24 @@ func TestIntegrationQuery(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEndpoint_ValidateAndSetDefaultsWithNoDNSQueryName(t *testing.T) {
|
func TestDNS_validateAndSetDefault(t *testing.T) {
|
||||||
defer func() { recover() }()
|
|
||||||
dns := &DNS{
|
dns := &DNS{
|
||||||
QueryType: "A",
|
QueryType: "A",
|
||||||
QueryName: "",
|
QueryName: "",
|
||||||
}
|
}
|
||||||
err := dns.validateAndSetDefault()
|
err := dns.validateAndSetDefault()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Should've returned an error because endpoint's dns didn't have a query name, which is a mandatory field for dns")
|
t.Error("Should've returned an error because endpoint's dns didn't have a query name, which is a mandatory field for dns")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEndpoint_ValidateAndSetDefaultsWithInvalidDNSQueryType(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithInvalidDNSQueryType(t *testing.T) {
|
||||||
defer func() { recover() }()
|
|
||||||
dns := &DNS{
|
dns := &DNS{
|
||||||
QueryType: "B",
|
QueryType: "B",
|
||||||
QueryName: "example.com",
|
QueryName: "example.com",
|
||||||
}
|
}
|
||||||
err := dns.validateAndSetDefault()
|
err := dns.validateAndSetDefault()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("Should've returned an error because endpoint's dns query type is invalid, it needs to be a valid query name like A, AAAA, CNAME...")
|
t.Error("Should've returned an error because endpoint's dns query type is invalid, it needs to be a valid query name like A, AAAA, CNAME...")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+26
-63
@@ -55,12 +55,6 @@ var (
|
|||||||
// ErrEndpointWithNoURL is the error with which Gatus will panic if an endpoint is configured with no url
|
// ErrEndpointWithNoURL is the error with which Gatus will panic if an endpoint is configured with no url
|
||||||
ErrEndpointWithNoURL = errors.New("you must specify an url for each endpoint")
|
ErrEndpointWithNoURL = errors.New("you must specify an url for each endpoint")
|
||||||
|
|
||||||
// ErrEndpointWithNoName is the error with which Gatus will panic if an endpoint is configured with no name
|
|
||||||
ErrEndpointWithNoName = errors.New("you must specify a name for each endpoint")
|
|
||||||
|
|
||||||
// ErrEndpointWithInvalidNameOrGroup is the error with which Gatus will panic if an endpoint has an invalid character where it shouldn't
|
|
||||||
ErrEndpointWithInvalidNameOrGroup = errors.New("endpoint name and group must not have \" or \\")
|
|
||||||
|
|
||||||
// ErrUnknownEndpointType is the error with which Gatus will panic if an endpoint has an unknown type
|
// ErrUnknownEndpointType is the error with which Gatus will panic if an endpoint has an unknown type
|
||||||
ErrUnknownEndpointType = errors.New("unknown endpoint type")
|
ErrUnknownEndpointType = errors.New("unknown endpoint type")
|
||||||
|
|
||||||
@@ -72,13 +66,9 @@ var (
|
|||||||
// This is because the free whois service we are using should not be abused, especially considering the fact that
|
// 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.
|
// 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)")
|
ErrInvalidEndpointIntervalForDomainExpirationPlaceholder = errors.New("the minimum interval for an endpoint with a condition using the " + DomainExpirationPlaceholder + " placeholder is 300s (5m)")
|
||||||
// ErrEndpointWithoutSSHUsername is the error with which Gatus will panic if an endpoint with SSH monitoring is configured without a user.
|
|
||||||
ErrEndpointWithoutSSHUsername = errors.New("you must specify a username for each endpoint with SSH")
|
|
||||||
// ErrEndpointWithoutSSHPassword is the error with which Gatus will panic if an endpoint with SSH monitoring is configured without a password.
|
|
||||||
ErrEndpointWithoutSSHPassword = errors.New("you must specify a password for each endpoint with SSH")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Endpoint is the configuration of a monitored
|
// Endpoint is the configuration of a service to be monitored
|
||||||
type Endpoint struct {
|
type Endpoint struct {
|
||||||
// Enabled defines whether to enable the monitoring of the endpoint
|
// Enabled defines whether to enable the monitoring of the endpoint
|
||||||
Enabled *bool `yaml:"enabled,omitempty"`
|
Enabled *bool `yaml:"enabled,omitempty"`
|
||||||
@@ -95,6 +85,9 @@ type Endpoint struct {
|
|||||||
// DNS is the configuration of DNS monitoring
|
// DNS is the configuration of DNS monitoring
|
||||||
DNS *DNS `yaml:"dns,omitempty"`
|
DNS *DNS `yaml:"dns,omitempty"`
|
||||||
|
|
||||||
|
// SSH is the configuration of SSH monitoring.
|
||||||
|
SSH *SSH `yaml:"ssh,omitempty"`
|
||||||
|
|
||||||
// Method of the request made to the url of the endpoint
|
// Method of the request made to the url of the endpoint
|
||||||
Method string `yaml:"method,omitempty"`
|
Method string `yaml:"method,omitempty"`
|
||||||
|
|
||||||
@@ -127,31 +120,10 @@ type Endpoint struct {
|
|||||||
|
|
||||||
// NumberOfSuccessesInARow is the number of successful evaluations in a row
|
// NumberOfSuccessesInARow is the number of successful evaluations in a row
|
||||||
NumberOfSuccessesInARow int `yaml:"-"`
|
NumberOfSuccessesInARow int `yaml:"-"`
|
||||||
|
|
||||||
// SSH is the configuration of SSH monitoring.
|
|
||||||
SSH *SSH `yaml:"ssh,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type SSH struct {
|
|
||||||
// Username is the username to use when connecting to the SSH server.
|
|
||||||
Username string `yaml:"username,omitempty"`
|
|
||||||
// Password is the password to use when connecting to the SSH server.
|
|
||||||
Password string `yaml:"password,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidateAndSetDefaults validates the endpoint
|
|
||||||
func (s *SSH) ValidateAndSetDefaults() error {
|
|
||||||
if s.Username == "" {
|
|
||||||
return ErrEndpointWithoutSSHUsername
|
|
||||||
}
|
|
||||||
if s.Password == "" {
|
|
||||||
return ErrEndpointWithoutSSHPassword
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsEnabled returns whether the endpoint is enabled or not
|
// IsEnabled returns whether the endpoint is enabled or not
|
||||||
func (endpoint Endpoint) IsEnabled() bool {
|
func (endpoint *Endpoint) IsEnabled() bool {
|
||||||
if endpoint.Enabled == nil {
|
if endpoint.Enabled == nil {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -159,7 +131,7 @@ func (endpoint Endpoint) IsEnabled() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Type returns the endpoint type
|
// Type returns the endpoint type
|
||||||
func (endpoint Endpoint) Type() EndpointType {
|
func (endpoint *Endpoint) Type() EndpointType {
|
||||||
switch {
|
switch {
|
||||||
case endpoint.DNS != nil:
|
case endpoint.DNS != nil:
|
||||||
return EndpointTypeDNS
|
return EndpointTypeDNS
|
||||||
@@ -188,7 +160,12 @@ func (endpoint Endpoint) Type() EndpointType {
|
|||||||
|
|
||||||
// ValidateAndSetDefaults validates the endpoint's configuration and sets the default value of args 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
|
if err := validateEndpointNameGroupAndAlerts(endpoint.Name, endpoint.Group, endpoint.Alerts); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(endpoint.URL) == 0 {
|
||||||
|
return ErrEndpointWithNoURL
|
||||||
|
}
|
||||||
if endpoint.ClientConfig == nil {
|
if endpoint.ClientConfig == nil {
|
||||||
endpoint.ClientConfig = client.GetDefaultConfig()
|
endpoint.ClientConfig = client.GetDefaultConfig()
|
||||||
} else {
|
} else {
|
||||||
@@ -221,20 +198,6 @@ func (endpoint *Endpoint) ValidateAndSetDefaults() error {
|
|||||||
if _, contentTypeHeaderExists := endpoint.Headers[ContentTypeHeader]; !contentTypeHeaderExists && endpoint.GraphQL {
|
if _, contentTypeHeaderExists := endpoint.Headers[ContentTypeHeader]; !contentTypeHeaderExists && endpoint.GraphQL {
|
||||||
endpoint.Headers[ContentTypeHeader] = "application/json"
|
endpoint.Headers[ContentTypeHeader] = "application/json"
|
||||||
}
|
}
|
||||||
for _, endpointAlert := range endpoint.Alerts {
|
|
||||||
if err := endpointAlert.ValidateAndSetDefaults(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(endpoint.Name) == 0 {
|
|
||||||
return ErrEndpointWithNoName
|
|
||||||
}
|
|
||||||
if strings.ContainsAny(endpoint.Name, "\"\\") || strings.ContainsAny(endpoint.Group, "\"\\") {
|
|
||||||
return ErrEndpointWithInvalidNameOrGroup
|
|
||||||
}
|
|
||||||
if len(endpoint.URL) == 0 {
|
|
||||||
return ErrEndpointWithNoURL
|
|
||||||
}
|
|
||||||
if len(endpoint.Conditions) == 0 {
|
if len(endpoint.Conditions) == 0 {
|
||||||
return ErrEndpointWithNoCondition
|
return ErrEndpointWithNoCondition
|
||||||
}
|
}
|
||||||
@@ -249,6 +212,9 @@ func (endpoint *Endpoint) ValidateAndSetDefaults() error {
|
|||||||
if endpoint.DNS != nil {
|
if endpoint.DNS != nil {
|
||||||
return endpoint.DNS.validateAndSetDefault()
|
return endpoint.DNS.validateAndSetDefault()
|
||||||
}
|
}
|
||||||
|
if endpoint.SSH != nil {
|
||||||
|
return endpoint.SSH.validate()
|
||||||
|
}
|
||||||
if endpoint.Type() == EndpointTypeUNKNOWN {
|
if endpoint.Type() == EndpointTypeUNKNOWN {
|
||||||
return ErrUnknownEndpointType
|
return ErrUnknownEndpointType
|
||||||
}
|
}
|
||||||
@@ -257,14 +223,11 @@ func (endpoint *Endpoint) ValidateAndSetDefaults() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if endpoint.SSH != nil {
|
|
||||||
return endpoint.SSH.ValidateAndSetDefaults()
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DisplayName returns an identifier made up of the Name and, if not empty, the Group.
|
// DisplayName returns an identifier made up of the Name and, if not empty, the Group.
|
||||||
func (endpoint Endpoint) DisplayName() string {
|
func (endpoint *Endpoint) DisplayName() string {
|
||||||
if len(endpoint.Group) > 0 {
|
if len(endpoint.Group) > 0 {
|
||||||
return endpoint.Group + "/" + endpoint.Name
|
return endpoint.Group + "/" + endpoint.Name
|
||||||
}
|
}
|
||||||
@@ -272,10 +235,19 @@ func (endpoint Endpoint) DisplayName() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Key returns the unique key for the Endpoint
|
// Key returns the unique key for the Endpoint
|
||||||
func (endpoint Endpoint) Key() string {
|
func (endpoint *Endpoint) Key() string {
|
||||||
return util.ConvertGroupAndEndpointNameToKey(endpoint.Group, endpoint.Name)
|
return util.ConvertGroupAndEndpointNameToKey(endpoint.Group, endpoint.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close HTTP connections between watchdog and endpoints to avoid dangling socket file descriptors
|
||||||
|
// on configuration reload.
|
||||||
|
// More context on https://github.com/TwiN/gatus/issues/536
|
||||||
|
func (endpoint *Endpoint) Close() {
|
||||||
|
if endpoint.Type() == EndpointTypeHTTP {
|
||||||
|
client.GetHTTPClient(endpoint.ClientConfig).CloseIdleConnections()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 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{}}
|
||||||
@@ -419,15 +391,6 @@ func (endpoint *Endpoint) call(result *Result) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close HTTP connections between watchdog and endpoints to avoid dangling socket file descriptors
|
|
||||||
// on configuration reload.
|
|
||||||
// More context on https://github.com/TwiN/gatus/issues/536
|
|
||||||
func (endpoint *Endpoint) Close() {
|
|
||||||
if endpoint.Type() == EndpointTypeHTTP {
|
|
||||||
client.GetHTTPClient(endpoint.ClientConfig).CloseIdleConnections()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (endpoint *Endpoint) buildHTTPRequest() *http.Request {
|
func (endpoint *Endpoint) buildHTTPRequest() *http.Request {
|
||||||
var bodyBuffer *bytes.Buffer
|
var bodyBuffer *bytes.Buffer
|
||||||
if endpoint.GraphQL {
|
if endpoint.GraphQL {
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/alert"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrEndpointWithNoName is the error with which Gatus will panic if an endpoint is configured with no name
|
||||||
|
ErrEndpointWithNoName = errors.New("you must specify a name for each endpoint")
|
||||||
|
|
||||||
|
// ErrEndpointWithInvalidNameOrGroup is the error with which Gatus will panic if an endpoint has an invalid character where it shouldn't
|
||||||
|
ErrEndpointWithInvalidNameOrGroup = errors.New("endpoint name and group must not have \" or \\")
|
||||||
|
)
|
||||||
|
|
||||||
|
// validateEndpointNameGroupAndAlerts validates the name, group and alerts of an endpoint
|
||||||
|
func validateEndpointNameGroupAndAlerts(name, group string, alerts []*alert.Alert) error {
|
||||||
|
if len(name) == 0 {
|
||||||
|
return ErrEndpointWithNoName
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(name, "\"\\") || strings.ContainsAny(group, "\"\\") {
|
||||||
|
return ErrEndpointWithInvalidNameOrGroup
|
||||||
|
}
|
||||||
|
for _, endpointAlert := range alerts {
|
||||||
|
if err := endpointAlert.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/alert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidateEndpointNameGroupAndAlerts(t *testing.T) {
|
||||||
|
scenarios := []struct {
|
||||||
|
name string
|
||||||
|
group string
|
||||||
|
alerts []*alert.Alert
|
||||||
|
expectedErr error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "n",
|
||||||
|
group: "g",
|
||||||
|
alerts: []*alert.Alert{{Type: "slack"}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "n",
|
||||||
|
alerts: []*alert.Alert{{Type: "slack"}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
group: "g",
|
||||||
|
alerts: []*alert.Alert{{Type: "slack"}},
|
||||||
|
expectedErr: ErrEndpointWithNoName,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "\"",
|
||||||
|
alerts: []*alert.Alert{{Type: "slack"}},
|
||||||
|
expectedErr: ErrEndpointWithInvalidNameOrGroup,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "n",
|
||||||
|
group: "\\",
|
||||||
|
alerts: []*alert.Alert{{Type: "slack"}},
|
||||||
|
expectedErr: ErrEndpointWithInvalidNameOrGroup,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.name, func(t *testing.T) {
|
||||||
|
err := validateEndpointNameGroupAndAlerts(scenario.name, scenario.group, scenario.alerts)
|
||||||
|
if !errors.Is(err, scenario.expectedErr) {
|
||||||
|
t.Errorf("expected error to be %v but got %v", scenario.expectedErr, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+52
-20
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -123,6 +124,7 @@ func TestEndpoint(t *testing.T) {
|
|||||||
Name: "website-health",
|
Name: "website-health",
|
||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []Condition{"[DOMAIN_EXPIRATION] > 100h"},
|
Conditions: []Condition{"[DOMAIN_EXPIRATION] > 100h"},
|
||||||
|
Interval: 5 * time.Minute,
|
||||||
},
|
},
|
||||||
ExpectedResult: &Result{
|
ExpectedResult: &Result{
|
||||||
Success: true,
|
Success: true,
|
||||||
@@ -195,7 +197,10 @@ func TestEndpoint(t *testing.T) {
|
|||||||
} else {
|
} else {
|
||||||
client.InjectHTTPClient(nil)
|
client.InjectHTTPClient(nil)
|
||||||
}
|
}
|
||||||
scenario.Endpoint.ValidateAndSetDefaults()
|
err := scenario.Endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Error("did not expect an error, got", err)
|
||||||
|
}
|
||||||
result := scenario.Endpoint.EvaluateHealth()
|
result := scenario.Endpoint.EvaluateHealth()
|
||||||
if result.Success != scenario.ExpectedResult.Success {
|
if result.Success != scenario.ExpectedResult.Success {
|
||||||
t.Errorf("Expected success to be %v, got %v", scenario.ExpectedResult.Success, result.Success)
|
t.Errorf("Expected success to be %v, got %v", scenario.ExpectedResult.Success, result.Success)
|
||||||
@@ -241,13 +246,13 @@ func TestEndpoint(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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")
|
||||||
}
|
}
|
||||||
if value := false; (Endpoint{Enabled: &value}).IsEnabled() {
|
if value := false; (&Endpoint{Enabled: &value}).IsEnabled() {
|
||||||
t.Error("endpoint.IsEnabled() should've returned false, because Enabled was set to false")
|
t.Error("endpoint.IsEnabled() should've returned false, because Enabled was set to false")
|
||||||
}
|
}
|
||||||
if value := true; !(Endpoint{Enabled: &value}).IsEnabled() {
|
if value := true; !(&Endpoint{Enabled: &value}).IsEnabled() {
|
||||||
t.Error("Endpoint.IsEnabled() should've returned true, because Enabled was set to true")
|
t.Error("Endpoint.IsEnabled() should've returned true, because Enabled was set to true")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -430,7 +435,10 @@ func TestEndpoint_ValidateAndSetDefaultsWithClientConfig(t *testing.T) {
|
|||||||
Timeout: 0,
|
Timeout: 0,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
if endpoint.ClientConfig == nil {
|
if endpoint.ClientConfig == nil {
|
||||||
t.Error("client configuration should've been set to the default configuration")
|
t.Error("client configuration should've been set to the default configuration")
|
||||||
} else {
|
} else {
|
||||||
@@ -466,7 +474,7 @@ func TestEndpoint_ValidateAndSetDefaultsWithDNS(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestEndpoint_ValidateAndSetDefaultsWithSSH(t *testing.T) {
|
func TestEndpoint_ValidateAndSetDefaultsWithSSH(t *testing.T) {
|
||||||
tests := []struct {
|
scenarios := []struct {
|
||||||
name string
|
name string
|
||||||
username string
|
username string
|
||||||
password string
|
password string
|
||||||
@@ -492,20 +500,20 @@ func TestEndpoint_ValidateAndSetDefaultsWithSSH(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, scenario := range scenarios {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(scenario.name, func(t *testing.T) {
|
||||||
endpoint := &Endpoint{
|
endpoint := &Endpoint{
|
||||||
Name: "ssh-test",
|
Name: "ssh-test",
|
||||||
URL: "https://example.com",
|
URL: "https://example.com",
|
||||||
SSH: &SSH{
|
SSH: &SSH{
|
||||||
Username: test.username,
|
Username: scenario.username,
|
||||||
Password: test.password,
|
Password: scenario.password,
|
||||||
},
|
},
|
||||||
Conditions: []Condition{Condition("[STATUS] == 0")},
|
Conditions: []Condition{Condition("[STATUS] == 0")},
|
||||||
}
|
}
|
||||||
err := endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
if err != test.expectedErr {
|
if !errors.Is(err, scenario.expectedErr) {
|
||||||
t.Errorf("expected error %v, got %v", test.expectedErr, err)
|
t.Errorf("expected error %v, got %v", scenario.expectedErr, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -575,7 +583,10 @@ func TestEndpoint_buildHTTPRequest(t *testing.T) {
|
|||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []Condition{condition},
|
Conditions: []Condition{condition},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
request := endpoint.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "GET" {
|
if request.Method != "GET" {
|
||||||
t.Error("request.Method should've been GET, but was", request.Method)
|
t.Error("request.Method should've been GET, but was", request.Method)
|
||||||
@@ -598,7 +609,10 @@ func TestEndpoint_buildHTTPRequestWithCustomUserAgent(t *testing.T) {
|
|||||||
"User-Agent": "Test/2.0",
|
"User-Agent": "Test/2.0",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
request := endpoint.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "GET" {
|
if request.Method != "GET" {
|
||||||
t.Error("request.Method should've been GET, but was", request.Method)
|
t.Error("request.Method should've been GET, but was", request.Method)
|
||||||
@@ -622,7 +636,10 @@ func TestEndpoint_buildHTTPRequestWithHostHeader(t *testing.T) {
|
|||||||
"Host": "example.com",
|
"Host": "example.com",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
request := endpoint.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "POST" {
|
if request.Method != "POST" {
|
||||||
t.Error("request.Method should've been POST, but was", request.Method)
|
t.Error("request.Method should've been POST, but was", request.Method)
|
||||||
@@ -649,7 +666,10 @@ func TestEndpoint_buildHTTPRequestWithGraphQLEnabled(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
request := endpoint.buildHTTPRequest()
|
request := endpoint.buildHTTPRequest()
|
||||||
if request.Method != "POST" {
|
if request.Method != "POST" {
|
||||||
t.Error("request.Method should've been POST, but was", request.Method)
|
t.Error("request.Method should've been POST, but was", request.Method)
|
||||||
@@ -671,7 +691,10 @@ func TestIntegrationEvaluateHealth(t *testing.T) {
|
|||||||
URL: "https://twin.sh/health",
|
URL: "https://twin.sh/health",
|
||||||
Conditions: []Condition{condition, bodyCondition},
|
Conditions: []Condition{condition, bodyCondition},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
result := endpoint.EvaluateHealth()
|
result := endpoint.EvaluateHealth()
|
||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
@@ -699,7 +722,10 @@ func TestIntegrationEvaluateHealthWithErrorAndHideURL(t *testing.T) {
|
|||||||
HideURL: true,
|
HideURL: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
result := endpoint.EvaluateHealth()
|
result := endpoint.EvaluateHealth()
|
||||||
if result.Success {
|
if result.Success {
|
||||||
t.Error("Because one of the conditions was invalid, result.Success should have been false")
|
t.Error("Because one of the conditions was invalid, result.Success should have been false")
|
||||||
@@ -724,7 +750,10 @@ func TestIntegrationEvaluateHealthForDNS(t *testing.T) {
|
|||||||
},
|
},
|
||||||
Conditions: []Condition{conditionSuccess, conditionBody},
|
Conditions: []Condition{conditionSuccess, conditionBody},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
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)
|
||||||
@@ -792,7 +821,10 @@ func TestIntegrationEvaluateHealthForICMP(t *testing.T) {
|
|||||||
URL: "icmp://127.0.0.1",
|
URL: "icmp://127.0.0.1",
|
||||||
Conditions: []Condition{"[CONNECTED] == true"},
|
Conditions: []Condition{"[CONNECTED] == true"},
|
||||||
}
|
}
|
||||||
endpoint.ValidateAndSetDefaults()
|
err := endpoint.ValidateAndSetDefaults()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("did not expect an error, got", err)
|
||||||
|
}
|
||||||
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", endpoint.Conditions[0])
|
t.Errorf("Conditions '%s' should have been a success", endpoint.Conditions[0])
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v5/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrExternalEndpointWithNoToken is the error with which Gatus will panic if an external endpoint is configured without a token.
|
||||||
|
ErrExternalEndpointWithNoToken = errors.New("you must specify a token for each external endpoint")
|
||||||
|
)
|
||||||
|
|
||||||
|
// ExternalEndpoint is an endpoint whose result is pushed from outside Gatus, which means that
|
||||||
|
// said endpoints are not monitored by Gatus itself; Gatus only displays their results and takes
|
||||||
|
// care of alerting
|
||||||
|
type ExternalEndpoint struct {
|
||||||
|
// Enabled defines whether to enable the monitoring of the endpoint
|
||||||
|
Enabled *bool `yaml:"enabled,omitempty"`
|
||||||
|
|
||||||
|
// Name of the endpoint. Can be anything.
|
||||||
|
Name string `yaml:"name"`
|
||||||
|
|
||||||
|
// Group the endpoint is a part of. Used for grouping multiple endpoints together on the front end.
|
||||||
|
Group string `yaml:"group,omitempty"`
|
||||||
|
|
||||||
|
// Token is the bearer token that must be provided through the Authorization header to push results to the endpoint
|
||||||
|
Token string `yaml:"token,omitempty"`
|
||||||
|
|
||||||
|
// Alerts is the alerting configuration for the endpoint in case of failure
|
||||||
|
Alerts []*alert.Alert `yaml:"alerts,omitempty"`
|
||||||
|
|
||||||
|
// NumberOfFailuresInARow is the number of unsuccessful evaluations in a row
|
||||||
|
NumberOfFailuresInARow int `yaml:"-"`
|
||||||
|
|
||||||
|
// NumberOfSuccessesInARow is the number of successful evaluations in a row
|
||||||
|
NumberOfSuccessesInARow int `yaml:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAndSetDefaults validates the ExternalEndpoint and sets the default values
|
||||||
|
func (externalEndpoint *ExternalEndpoint) ValidateAndSetDefaults() error {
|
||||||
|
if err := validateEndpointNameGroupAndAlerts(externalEndpoint.Name, externalEndpoint.Group, externalEndpoint.Alerts); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(externalEndpoint.Token) == 0 {
|
||||||
|
return ErrExternalEndpointWithNoToken
|
||||||
|
}
|
||||||
|
for _, externalEndpointAlert := range externalEndpoint.Alerts {
|
||||||
|
if err := externalEndpointAlert.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsEnabled returns whether the endpoint is enabled or not
|
||||||
|
func (externalEndpoint *ExternalEndpoint) IsEnabled() bool {
|
||||||
|
if externalEndpoint.Enabled == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return *externalEndpoint.Enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
// DisplayName returns an identifier made up of the Name and, if not empty, the Group.
|
||||||
|
func (externalEndpoint *ExternalEndpoint) DisplayName() string {
|
||||||
|
if len(externalEndpoint.Group) > 0 {
|
||||||
|
return externalEndpoint.Group + "/" + externalEndpoint.Name
|
||||||
|
}
|
||||||
|
return externalEndpoint.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key returns the unique key for the Endpoint
|
||||||
|
func (externalEndpoint *ExternalEndpoint) Key() string {
|
||||||
|
return util.ConvertGroupAndEndpointNameToKey(externalEndpoint.Group, externalEndpoint.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToEndpoint converts the ExternalEndpoint to an Endpoint
|
||||||
|
func (externalEndpoint *ExternalEndpoint) ToEndpoint() *Endpoint {
|
||||||
|
endpoint := &Endpoint{
|
||||||
|
Enabled: externalEndpoint.Enabled,
|
||||||
|
Name: externalEndpoint.Name,
|
||||||
|
Group: externalEndpoint.Group,
|
||||||
|
Alerts: externalEndpoint.Alerts,
|
||||||
|
NumberOfFailuresInARow: externalEndpoint.NumberOfFailuresInARow,
|
||||||
|
NumberOfSuccessesInARow: externalEndpoint.NumberOfSuccessesInARow,
|
||||||
|
}
|
||||||
|
return endpoint
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExternalEndpoint_ToEndpoint(t *testing.T) {
|
||||||
|
externalEndpoint := &ExternalEndpoint{
|
||||||
|
Name: "name",
|
||||||
|
Group: "group",
|
||||||
|
}
|
||||||
|
convertedEndpoint := externalEndpoint.ToEndpoint()
|
||||||
|
if externalEndpoint.Name != convertedEndpoint.Name {
|
||||||
|
t.Errorf("expected %s, got %s", externalEndpoint.Name, convertedEndpoint.Name)
|
||||||
|
}
|
||||||
|
if externalEndpoint.Group != convertedEndpoint.Group {
|
||||||
|
t.Errorf("expected %s, got %s", externalEndpoint.Group, convertedEndpoint.Group)
|
||||||
|
}
|
||||||
|
if externalEndpoint.Key() != convertedEndpoint.Key() {
|
||||||
|
t.Errorf("expected %s, got %s", externalEndpoint.Key(), convertedEndpoint.Key())
|
||||||
|
}
|
||||||
|
if externalEndpoint.DisplayName() != convertedEndpoint.DisplayName() {
|
||||||
|
t.Errorf("expected %s, got %s", externalEndpoint.DisplayName(), convertedEndpoint.DisplayName())
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -7,7 +7,7 @@ import (
|
|||||||
// Result of the evaluation of a Endpoint
|
// Result of the evaluation of a Endpoint
|
||||||
type Result struct {
|
type Result struct {
|
||||||
// HTTPStatus is the HTTP response status code
|
// HTTPStatus is the HTTP response status code
|
||||||
HTTPStatus int `json:"status"`
|
HTTPStatus int `json:"status,omitempty"`
|
||||||
|
|
||||||
// DNSRCode is the response code of a DNS query in a human-readable format
|
// DNSRCode is the response code of a DNS query in a human-readable format
|
||||||
//
|
//
|
||||||
@@ -30,7 +30,7 @@ type Result struct {
|
|||||||
Errors []string `json:"errors,omitempty"`
|
Errors []string `json:"errors,omitempty"`
|
||||||
|
|
||||||
// ConditionResults results of the Endpoint's conditions
|
// ConditionResults results of the Endpoint's conditions
|
||||||
ConditionResults []*ConditionResult `json:"conditionResults"`
|
ConditionResults []*ConditionResult `json:"conditionResults,omitempty"`
|
||||||
|
|
||||||
// Success whether the result signifies a success or not
|
// Success whether the result signifies a success or not
|
||||||
Success bool `json:"success"`
|
Success bool `json:"success"`
|
||||||
|
|||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrEndpointWithoutSSHUsername is the error with which Gatus will panic if an endpoint with SSH monitoring is configured without a user.
|
||||||
|
ErrEndpointWithoutSSHUsername = errors.New("you must specify a username for each SSH endpoint")
|
||||||
|
|
||||||
|
// ErrEndpointWithoutSSHPassword is the error with which Gatus will panic if an endpoint with SSH monitoring is configured without a password.
|
||||||
|
ErrEndpointWithoutSSHPassword = errors.New("you must specify a password for each SSH endpoint")
|
||||||
|
)
|
||||||
|
|
||||||
|
type SSH struct {
|
||||||
|
Username string `yaml:"username,omitempty"`
|
||||||
|
Password string `yaml:"password,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate validates the endpoint
|
||||||
|
func (s *SSH) validate() error {
|
||||||
|
if len(s.Username) == 0 {
|
||||||
|
return ErrEndpointWithoutSSHUsername
|
||||||
|
}
|
||||||
|
if len(s.Password) == 0 {
|
||||||
|
return ErrEndpointWithoutSSHPassword
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSSH_validate(t *testing.T) {
|
||||||
|
ssh := &SSH{}
|
||||||
|
if err := ssh.validate(); err == nil {
|
||||||
|
t.Error("expected an error")
|
||||||
|
} else if !errors.Is(err, ErrEndpointWithoutSSHUsername) {
|
||||||
|
t.Errorf("expected error to be '%v', got '%v'", ErrEndpointWithoutSSHUsername, err)
|
||||||
|
}
|
||||||
|
ssh.Username = "username"
|
||||||
|
if err := ssh.validate(); err == nil {
|
||||||
|
t.Error("expected an error")
|
||||||
|
} else if !errors.Is(err, ErrEndpointWithoutSSHPassword) {
|
||||||
|
t.Errorf("expected error to be '%v', got '%v'", ErrEndpointWithoutSSHPassword, err)
|
||||||
|
}
|
||||||
|
ssh.Password = "password"
|
||||||
|
if err := ssh.validate(); err != nil {
|
||||||
|
t.Errorf("expected no error, got '%v'", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ var (
|
|||||||
ErrInvalidBadgeResponseTimeConfig = errors.New("invalid response time badge configuration: expected parameter 'response-time' to have 5 ascending numerical values")
|
ErrInvalidBadgeResponseTimeConfig = errors.New("invalid response time badge configuration: expected parameter 'response-time' to have 5 ascending numerical values")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ValidateAndSetDefaults validates the UI configuration and sets the default values
|
||||||
func (config *Config) ValidateAndSetDefaults() error {
|
func (config *Config) ValidateAndSetDefaults() error {
|
||||||
if config.Badge != nil {
|
if config.Badge != nil {
|
||||||
if len(config.Badge.ResponseTime.Thresholds) != 5 {
|
if len(config.Badge.ResponseTime.Thresholds) != 5 {
|
||||||
|
|||||||
@@ -117,8 +117,15 @@ func extractValue(currentKey string, value interface{}) interface{} {
|
|||||||
}
|
}
|
||||||
if valueAsSlice, ok := value.([]interface{}); ok {
|
if valueAsSlice, ok := value.([]interface{}); ok {
|
||||||
// If the type is a slice, return it
|
// If the type is a slice, return it
|
||||||
|
// This happens when the body (value) is a JSON array
|
||||||
return valueAsSlice
|
return valueAsSlice
|
||||||
}
|
}
|
||||||
// otherwise, it's a map
|
if valueAsMap, ok := value.(map[string]interface{}); ok {
|
||||||
return value.(map[string]interface{})[currentKey]
|
// If the value is a map, then we get the currentKey from that map
|
||||||
|
// This happens when the body (value) is a JSON object
|
||||||
|
return valueAsMap[currentKey]
|
||||||
|
}
|
||||||
|
// If the value is neither a map, nor a slice, nor an index, then we cannot retrieve the currentKey
|
||||||
|
// from said value. This usually happens when the body (value) is null.
|
||||||
|
return value
|
||||||
}
|
}
|
||||||
@@ -83,9 +83,12 @@ func initializeStorage(cfg *config.Config) {
|
|||||||
for _, endpoint := range cfg.Endpoints {
|
for _, endpoint := range cfg.Endpoints {
|
||||||
keys = append(keys, endpoint.Key())
|
keys = append(keys, endpoint.Key())
|
||||||
}
|
}
|
||||||
|
for _, externalEndpoint := range cfg.ExternalEndpoints {
|
||||||
|
keys = append(keys, externalEndpoint.Key())
|
||||||
|
}
|
||||||
numberOfEndpointStatusesDeleted := store.Get().DeleteAllEndpointStatusesNotInKeys(keys)
|
numberOfEndpointStatusesDeleted := store.Get().DeleteAllEndpointStatusesNotInKeys(keys)
|
||||||
if numberOfEndpointStatusesDeleted > 0 {
|
if numberOfEndpointStatusesDeleted > 0 {
|
||||||
log.Printf("[main][initializeStorage] Deleted %d endpoint statuses because their matching endpoints no longer existed", numberOfEndpointStatusesDeleted)
|
log.Printf("[main.initializeStorage] Deleted %d endpoint statuses because their matching endpoints no longer existed", numberOfEndpointStatusesDeleted)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,15 +96,15 @@ func listenToConfigurationFileChanges(cfg *config.Config) {
|
|||||||
for {
|
for {
|
||||||
time.Sleep(30 * time.Second)
|
time.Sleep(30 * time.Second)
|
||||||
if cfg.HasLoadedConfigurationBeenModified() {
|
if cfg.HasLoadedConfigurationBeenModified() {
|
||||||
log.Println("[main][listenToConfigurationFileChanges] Configuration file has been modified")
|
log.Println("[main.listenToConfigurationFileChanges] Configuration file has been modified")
|
||||||
stop(cfg)
|
stop(cfg)
|
||||||
time.Sleep(time.Second) // Wait a bit to make sure everything is done.
|
time.Sleep(time.Second) // Wait a bit to make sure everything is done.
|
||||||
save()
|
save()
|
||||||
updatedConfig, err := loadConfiguration()
|
updatedConfig, err := loadConfiguration()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if cfg.SkipInvalidConfigUpdate {
|
if cfg.SkipInvalidConfigUpdate {
|
||||||
log.Println("[main][listenToConfigurationFileChanges] Failed to load new configuration:", err.Error())
|
log.Println("[main.listenToConfigurationFileChanges] Failed to load new configuration:", err.Error())
|
||||||
log.Println("[main][listenToConfigurationFileChanges] The configuration file was updated, but it is not valid. The old configuration will continue being used.")
|
log.Println("[main.listenToConfigurationFileChanges] The configuration file was updated, but it is not valid. The old configuration will continue being used.")
|
||||||
// Update the last file modification time to avoid trying to process the same invalid configuration again
|
// Update the last file modification time to avoid trying to process the same invalid configuration again
|
||||||
cfg.UpdateLastFileModTime()
|
cfg.UpdateLastFileModTime()
|
||||||
continue
|
continue
|
||||||
|
|||||||
+1
-1
@@ -99,7 +99,7 @@ func (c *Config) IsAuthenticated(ctx *fiber.Ctx) bool {
|
|||||||
// TODO: Update g8 to support fasthttp natively? (see g8's fasthttp branch)
|
// TODO: Update g8 to support fasthttp natively? (see g8's fasthttp branch)
|
||||||
request, err := adaptor.ConvertRequest(ctx, false)
|
request, err := adaptor.ConvertRequest(ctx, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[IsAuthenticated] Unexpected error converting request: %v", err)
|
log.Printf("[security.IsAuthenticated] Unexpected error converting request: %v", err)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
token := c.gate.ExtractTokenFromRequest(request)
|
token := c.gate.ExtractTokenFromRequest(request)
|
||||||
|
|||||||
+1
-1
@@ -124,7 +124,7 @@ func (c *OIDCConfig) callbackHandler(w http.ResponseWriter, r *http.Request) { /
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("[security][callbackHandler] Subject %s is not in the list of allowed subjects", idToken.Subject)
|
log.Printf("[security.callbackHandler] Subject %s is not in the list of allowed subjects", idToken.Subject)
|
||||||
http.Redirect(w, r, "/?error=access_denied", http.StatusFound)
|
http.Redirect(w, r, "/?error=access_denied", http.StatusFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-24
@@ -231,16 +231,16 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
|
|||||||
}
|
}
|
||||||
endpointID, err := s.getEndpointID(tx, endpoint)
|
endpointID, err := s.getEndpointID(tx, endpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == common.ErrEndpointNotFound {
|
if errors.Is(err, common.ErrEndpointNotFound) {
|
||||||
// Endpoint doesn't exist in the database, insert it
|
// Endpoint doesn't exist in the database, insert it
|
||||||
if endpointID, err = s.insertEndpoint(tx, endpoint); err != nil {
|
if endpointID, err = s.insertEndpoint(tx, endpoint); err != nil {
|
||||||
_ = tx.Rollback()
|
_ = tx.Rollback()
|
||||||
log.Printf("[sql][Insert] Failed to create endpoint with group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to create endpoint with group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
_ = tx.Rollback()
|
_ = tx.Rollback()
|
||||||
log.Printf("[sql][Insert] Failed to retrieve id of endpoint with group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to retrieve id of endpoint with group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -256,7 +256,7 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
|
|||||||
numberOfEvents, err := s.getNumberOfEventsByEndpointID(tx, endpointID)
|
numberOfEvents, err := s.getNumberOfEventsByEndpointID(tx, endpointID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Silently fail
|
// Silently fail
|
||||||
log.Printf("[sql][Insert] Failed to retrieve total number of events for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to retrieve total number of events for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
if numberOfEvents == 0 {
|
if numberOfEvents == 0 {
|
||||||
// There's no events yet, which means we need to add the EventStart and the first healthy/unhealthy event
|
// There's no events yet, which means we need to add the EventStart and the first healthy/unhealthy event
|
||||||
@@ -266,18 +266,18 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Silently fail
|
// Silently fail
|
||||||
log.Printf("[sql][Insert] Failed to insert event=%s for group=%s; endpoint=%s: %s", core.EventStart, endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to insert event=%s for group=%s; endpoint=%s: %s", core.EventStart, endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
event := core.NewEventFromResult(result)
|
event := core.NewEventFromResult(result)
|
||||||
if err = s.insertEndpointEvent(tx, endpointID, event); err != nil {
|
if err = s.insertEndpointEvent(tx, endpointID, event); err != nil {
|
||||||
// Silently fail
|
// Silently fail
|
||||||
log.Printf("[sql][Insert] Failed to insert event=%s for group=%s; endpoint=%s: %s", event.Type, endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to insert event=%s for group=%s; endpoint=%s: %s", event.Type, endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Get the success value of the previous result
|
// Get the success value of the previous result
|
||||||
var lastResultSuccess bool
|
var lastResultSuccess bool
|
||||||
if lastResultSuccess, err = s.getLastEndpointResultSuccessValue(tx, endpointID); err != nil {
|
if lastResultSuccess, err = s.getLastEndpointResultSuccessValue(tx, endpointID); err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to retrieve outcome of previous result for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to retrieve outcome of previous result for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
} else {
|
} else {
|
||||||
// If we managed to retrieve the outcome of the previous result, we'll compare it with the new result.
|
// If we managed to retrieve the outcome of the previous result, we'll compare it with the new result.
|
||||||
// If the final outcome (success or failure) of the previous and the new result aren't the same, it means
|
// If the final outcome (success or failure) of the previous and the new result aren't the same, it means
|
||||||
@@ -287,7 +287,7 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
|
|||||||
event := core.NewEventFromResult(result)
|
event := core.NewEventFromResult(result)
|
||||||
if err = s.insertEndpointEvent(tx, endpointID, event); err != nil {
|
if err = s.insertEndpointEvent(tx, endpointID, event); err != nil {
|
||||||
// Silently fail
|
// Silently fail
|
||||||
log.Printf("[sql][Insert] Failed to insert event=%s for group=%s; endpoint=%s: %s", event.Type, endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to insert event=%s for group=%s; endpoint=%s: %s", event.Type, endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -296,40 +296,40 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
|
|||||||
// (since we're only deleting MaximumNumberOfEvents at a time instead of 1)
|
// (since we're only deleting MaximumNumberOfEvents at a time instead of 1)
|
||||||
if numberOfEvents > eventsCleanUpThreshold {
|
if numberOfEvents > eventsCleanUpThreshold {
|
||||||
if err = s.deleteOldEndpointEvents(tx, endpointID); err != nil {
|
if err = s.deleteOldEndpointEvents(tx, endpointID); err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to delete old events for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to delete old events for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Second, we need to insert the result.
|
// Second, we need to insert the result.
|
||||||
if err = s.insertEndpointResult(tx, endpointID, result); err != nil {
|
if err = s.insertEndpointResult(tx, endpointID, result); err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to insert result for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to insert result for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
_ = tx.Rollback() // If we can't insert the result, we'll rollback now since there's no point continuing
|
_ = tx.Rollback() // If we can't insert the result, we'll rollback now since there's no point continuing
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Clean up old results
|
// Clean up old results
|
||||||
numberOfResults, err := s.getNumberOfResultsByEndpointID(tx, endpointID)
|
numberOfResults, err := s.getNumberOfResultsByEndpointID(tx, endpointID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to retrieve total number of results for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to retrieve total number of results for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
} else {
|
} else {
|
||||||
if numberOfResults > resultsCleanUpThreshold {
|
if numberOfResults > resultsCleanUpThreshold {
|
||||||
if err = s.deleteOldEndpointResults(tx, endpointID); err != nil {
|
if err = s.deleteOldEndpointResults(tx, endpointID); err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to delete old results for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to delete old results for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Finally, we need to insert the uptime data.
|
// Finally, we need to insert the uptime data.
|
||||||
// Because the uptime data significantly outlives the results, we can't rely on the results for determining the uptime
|
// Because the uptime data significantly outlives the results, we can't rely on the results for determining the uptime
|
||||||
if err = s.updateEndpointUptime(tx, endpointID, result); err != nil {
|
if err = s.updateEndpointUptime(tx, endpointID, result); err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to update uptime for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to update uptime for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
// Clean up old uptime entries
|
// Clean up old uptime entries
|
||||||
ageOfOldestUptimeEntry, err := s.getAgeOfOldestEndpointUptimeEntry(tx, endpointID)
|
ageOfOldestUptimeEntry, err := s.getAgeOfOldestEndpointUptimeEntry(tx, endpointID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to retrieve oldest endpoint uptime entry for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to retrieve oldest endpoint uptime entry for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
} else {
|
} else {
|
||||||
if ageOfOldestUptimeEntry > uptimeCleanUpThreshold {
|
if ageOfOldestUptimeEntry > uptimeCleanUpThreshold {
|
||||||
if err = s.deleteOldUptimeEntries(tx, endpointID, time.Now().Add(-(uptimeRetention + time.Hour))); err != nil {
|
if err = s.deleteOldUptimeEntries(tx, endpointID, time.Now().Add(-(uptimeRetention + time.Hour))); err != nil {
|
||||||
log.Printf("[sql][Insert] Failed to delete old uptime entries for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
log.Printf("[sql.Insert] Failed to delete old uptime entries for group=%s; endpoint=%s: %s", endpoint.Group, endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -339,7 +339,7 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
|
|||||||
s.writeThroughCache.Delete(cacheKey)
|
s.writeThroughCache.Delete(cacheKey)
|
||||||
endpointKey, params, err := extractKeyAndParamsFromCacheKey(cacheKey)
|
endpointKey, params, err := extractKeyAndParamsFromCacheKey(cacheKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[sql][Insert] Silently deleting cache key %s instead of refreshing due to error: %s", cacheKey, err.Error())
|
log.Printf("[sql.Insert] Silently deleting cache key %s instead of refreshing due to error: %s", cacheKey, err.Error())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Retrieve the endpoint status by key, which will in turn refresh the cache
|
// Retrieve the endpoint status by key, which will in turn refresh the cache
|
||||||
@@ -370,7 +370,7 @@ func (s *Store) DeleteAllEndpointStatusesNotInKeys(keys []string) int {
|
|||||||
result, err = s.db.Exec(query, args...)
|
result, err = s.db.Exec(query, args...)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
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 {
|
if s.writeThroughCache != nil {
|
||||||
@@ -406,7 +406,7 @@ func (s *Store) Close() {
|
|||||||
|
|
||||||
// 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
|
||||||
func (s *Store) insertEndpoint(tx *sql.Tx, endpoint *core.Endpoint) (int64, error) {
|
func (s *Store) insertEndpoint(tx *sql.Tx, endpoint *core.Endpoint) (int64, error) {
|
||||||
//log.Printf("[sql][insertEndpoint] Inserting endpoint with group=%s and name=%s", endpoint.Group, endpoint.Name)
|
//log.Printf("[sql.insertEndpoint] Inserting endpoint with group=%s and name=%s", endpoint.Group, endpoint.Name)
|
||||||
var id int64
|
var id int64
|
||||||
err := tx.QueryRow(
|
err := tx.QueryRow(
|
||||||
"INSERT INTO endpoints (endpoint_key, endpoint_name, endpoint_group) VALUES ($1, $2, $3) RETURNING endpoint_id",
|
"INSERT INTO endpoints (endpoint_key, endpoint_name, endpoint_group) VALUES ($1, $2, $3) RETURNING endpoint_id",
|
||||||
@@ -531,12 +531,12 @@ func (s *Store) getEndpointStatusByKey(tx *sql.Tx, key string, parameters *pagin
|
|||||||
endpointStatus := core.NewEndpointStatus(group, endpointName)
|
endpointStatus := core.NewEndpointStatus(group, endpointName)
|
||||||
if parameters.EventsPageSize > 0 {
|
if parameters.EventsPageSize > 0 {
|
||||||
if endpointStatus.Events, err = s.getEndpointEventsByEndpointID(tx, endpointID, parameters.EventsPage, parameters.EventsPageSize); err != nil {
|
if endpointStatus.Events, err = s.getEndpointEventsByEndpointID(tx, endpointID, parameters.EventsPage, parameters.EventsPageSize); err != nil {
|
||||||
log.Printf("[sql][getEndpointStatusByKey] Failed to retrieve events for key=%s: %s", key, err.Error())
|
log.Printf("[sql.getEndpointStatusByKey] Failed to retrieve events for key=%s: %s", key, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if parameters.ResultsPageSize > 0 {
|
if parameters.ResultsPageSize > 0 {
|
||||||
if endpointStatus.Results, err = s.getEndpointResultsByEndpointID(tx, endpointID, parameters.ResultsPage, parameters.ResultsPageSize); err != nil {
|
if endpointStatus.Results, err = s.getEndpointResultsByEndpointID(tx, endpointID, parameters.ResultsPage, parameters.ResultsPageSize); err != nil {
|
||||||
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 {
|
if s.writeThroughCache != nil {
|
||||||
@@ -556,7 +556,7 @@ func (s *Store) getEndpointIDGroupAndNameByKey(tx *sql.Tx, key string) (id int64
|
|||||||
key,
|
key,
|
||||||
).Scan(&id, &group, &name)
|
).Scan(&id, &group, &name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == sql.ErrNoRows {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return 0, "", "", common.ErrEndpointNotFound
|
return 0, "", "", common.ErrEndpointNotFound
|
||||||
}
|
}
|
||||||
return 0, "", "", err
|
return 0, "", "", err
|
||||||
@@ -611,7 +611,7 @@ func (s *Store) getEndpointResultsByEndpointID(tx *sql.Tx, endpointID int64, pag
|
|||||||
var joinedErrors string
|
var joinedErrors string
|
||||||
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)
|
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 {
|
if err != nil {
|
||||||
log.Printf("[sql][getEndpointResultsByEndpointID] Silently failed to retrieve endpoint result for endpointID=%d: %s", endpointID, err.Error())
|
log.Printf("[sql.getEndpointResultsByEndpointID] Silently failed to retrieve endpoint result for endpointID=%d: %s", endpointID, err.Error())
|
||||||
err = nil
|
err = nil
|
||||||
}
|
}
|
||||||
if len(joinedErrors) != 0 {
|
if len(joinedErrors) != 0 {
|
||||||
@@ -738,7 +738,7 @@ func (s *Store) getEndpointID(tx *sql.Tx, endpoint *core.Endpoint) (int64, error
|
|||||||
var id int64
|
var id int64
|
||||||
err := tx.QueryRow("SELECT endpoint_id FROM endpoints WHERE endpoint_key = $1", endpoint.Key()).Scan(&id)
|
err := tx.QueryRow("SELECT endpoint_id FROM endpoints WHERE endpoint_key = $1", endpoint.Key()).Scan(&id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == sql.ErrNoRows {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return 0, common.ErrEndpointNotFound
|
return 0, common.ErrEndpointNotFound
|
||||||
}
|
}
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -788,7 +788,7 @@ func (s *Store) getLastEndpointResultSuccessValue(tx *sql.Tx, endpointID int64)
|
|||||||
var success bool
|
var success bool
|
||||||
err := tx.QueryRow("SELECT success FROM endpoint_results WHERE endpoint_id = $1 ORDER BY endpoint_result_id DESC LIMIT 1", endpointID).Scan(&success)
|
err := tx.QueryRow("SELECT success FROM endpoint_results WHERE endpoint_id = $1 ORDER BY endpoint_result_id DESC LIMIT 1", endpointID).Scan(&success)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == sql.ErrNoRows {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return false, errNoRowsReturned
|
return false, errNoRowsReturned
|
||||||
}
|
}
|
||||||
return false, err
|
return false, err
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ var (
|
|||||||
func Get() Store {
|
func Get() Store {
|
||||||
if !initialized {
|
if !initialized {
|
||||||
// This only happens in tests
|
// This only happens in tests
|
||||||
log.Println("[store][Get] Provider requested before it was initialized, automatically initializing")
|
log.Println("[store.Get] Provider requested before it was initialized, automatically initializing")
|
||||||
err := Initialize(nil)
|
err := Initialize(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic("failed to automatically initialize store: " + err.Error())
|
panic("failed to automatically initialize store: " + err.Error())
|
||||||
@@ -94,11 +94,11 @@ func Initialize(cfg *storage.Config) error {
|
|||||||
}
|
}
|
||||||
if cfg == nil {
|
if cfg == nil {
|
||||||
// This only happens in tests
|
// This only happens in tests
|
||||||
log.Println("[store][Initialize] nil storage config passed as parameter. This should only happen in tests. Defaulting to an empty config.")
|
log.Println("[store.Initialize] nil storage config passed as parameter. This should only happen in tests. Defaulting to an empty config.")
|
||||||
cfg = &storage.Config{}
|
cfg = &storage.Config{}
|
||||||
}
|
}
|
||||||
if len(cfg.Path) == 0 && cfg.Type != storage.TypePostgres {
|
if len(cfg.Path) == 0 && cfg.Type != storage.TypePostgres {
|
||||||
log.Printf("[store][Initialize] Creating storage provider of type=%s", cfg.Type)
|
log.Printf("[store.Initialize] Creating storage provider of type=%s", cfg.Type)
|
||||||
}
|
}
|
||||||
ctx, cancelFunc = context.WithCancel(context.Background())
|
ctx, cancelFunc = context.WithCancel(context.Background())
|
||||||
switch cfg.Type {
|
switch cfg.Type {
|
||||||
@@ -120,13 +120,13 @@ func autoSave(ctx context.Context, store Store, interval time.Duration) {
|
|||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
log.Printf("[store][autoSave] Stopping active job")
|
log.Printf("[store.autoSave] Stopping active job")
|
||||||
return
|
return
|
||||||
case <-time.After(interval):
|
case <-time.After(interval):
|
||||||
log.Printf("[store][autoSave] Saving")
|
log.Printf("[store.autoSave] Saving")
|
||||||
err := store.Save()
|
err := store.Save()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("[store][autoSave] Save failed:", err.Error())
|
log.Println("[store.autoSave] Save failed:", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,13 +31,13 @@ func handleAlertsToTrigger(endpoint *core.Endpoint, result *core.Result, alertin
|
|||||||
}
|
}
|
||||||
if endpointAlert.Triggered {
|
if endpointAlert.Triggered {
|
||||||
if debug {
|
if debug {
|
||||||
log.Printf("[watchdog][handleAlertsToTrigger] Alert for endpoint=%s with description='%s' has already been TRIGGERED, skipping", endpoint.Name, endpointAlert.GetDescription())
|
log.Printf("[watchdog.handleAlertsToTrigger] Alert for endpoint=%s with description='%s' has already been TRIGGERED, skipping", endpoint.Name, endpointAlert.GetDescription())
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
alertProvider := alertingConfig.GetAlertingProviderByAlertType(endpointAlert.Type)
|
alertProvider := alertingConfig.GetAlertingProviderByAlertType(endpointAlert.Type)
|
||||||
if alertProvider != nil {
|
if alertProvider != nil {
|
||||||
log.Printf("[watchdog][handleAlertsToTrigger] Sending %s alert because alert for endpoint=%s with description='%s' has been TRIGGERED", endpointAlert.Type, endpoint.Name, endpointAlert.GetDescription())
|
log.Printf("[watchdog.handleAlertsToTrigger] Sending %s alert because alert for endpoint=%s with description='%s' has been TRIGGERED", endpointAlert.Type, endpoint.Name, endpointAlert.GetDescription())
|
||||||
var err error
|
var err error
|
||||||
if os.Getenv("MOCK_ALERT_PROVIDER") == "true" {
|
if os.Getenv("MOCK_ALERT_PROVIDER") == "true" {
|
||||||
if os.Getenv("MOCK_ALERT_PROVIDER_ERROR") == "true" {
|
if os.Getenv("MOCK_ALERT_PROVIDER_ERROR") == "true" {
|
||||||
@@ -47,12 +47,12 @@ func handleAlertsToTrigger(endpoint *core.Endpoint, result *core.Result, alertin
|
|||||||
err = alertProvider.Send(endpoint, endpointAlert, result, false)
|
err = alertProvider.Send(endpoint, endpointAlert, result, false)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[watchdog][handleAlertsToTrigger] Failed to send an alert for endpoint=%s: %s", endpoint.Name, err.Error())
|
log.Printf("[watchdog.handleAlertsToTrigger] Failed to send an alert for endpoint=%s: %s", endpoint.Name, err.Error())
|
||||||
} else {
|
} else {
|
||||||
endpointAlert.Triggered = true
|
endpointAlert.Triggered = true
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[watchdog][handleAlertsToResolve] Not sending alert of type=%s despite being TRIGGERED, because the provider wasn't configured properly", endpointAlert.Type)
|
log.Printf("[watchdog.handleAlertsToResolve] Not sending alert of type=%s despite being TRIGGERED, because the provider wasn't configured properly", endpointAlert.Type)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,13 +71,13 @@ func handleAlertsToResolve(endpoint *core.Endpoint, result *core.Result, alertin
|
|||||||
}
|
}
|
||||||
alertProvider := alertingConfig.GetAlertingProviderByAlertType(endpointAlert.Type)
|
alertProvider := alertingConfig.GetAlertingProviderByAlertType(endpointAlert.Type)
|
||||||
if alertProvider != nil {
|
if alertProvider != nil {
|
||||||
log.Printf("[watchdog][handleAlertsToResolve] Sending %s alert because alert for endpoint=%s with description='%s' has been RESOLVED", endpointAlert.Type, endpoint.Name, endpointAlert.GetDescription())
|
log.Printf("[watchdog.handleAlertsToResolve] Sending %s alert because alert for endpoint=%s with description='%s' has been RESOLVED", endpointAlert.Type, endpoint.Name, endpointAlert.GetDescription())
|
||||||
err := alertProvider.Send(endpoint, endpointAlert, result, true)
|
err := alertProvider.Send(endpoint, endpointAlert, result, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[watchdog][handleAlertsToResolve] Failed to send an alert for endpoint=%s: %s", endpoint.Name, err.Error())
|
log.Printf("[watchdog.handleAlertsToResolve] Failed to send an alert for endpoint=%s: %s", endpoint.Name, err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[watchdog][handleAlertsToResolve] Not sending alert of type=%s despite being RESOLVED, because the provider wasn't configured properly", endpointAlert.Type)
|
log.Printf("[watchdog.handleAlertsToResolve] Not sending alert of type=%s despite being RESOLVED, because the provider wasn't configured properly", endpointAlert.Type)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
endpoint.NumberOfFailuresInARow = 0
|
endpoint.NumberOfFailuresInARow = 0
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v5/alerting/provider/custom"
|
"github.com/TwiN/gatus/v5/alerting/provider/custom"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/discord"
|
"github.com/TwiN/gatus/v5/alerting/provider/discord"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/email"
|
"github.com/TwiN/gatus/v5/alerting/provider/email"
|
||||||
|
"github.com/TwiN/gatus/v5/alerting/provider/jetbrainsspace"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
"github.com/TwiN/gatus/v5/alerting/provider/matrix"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v5/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v5/alerting/provider/messagebird"
|
||||||
@@ -281,6 +282,17 @@ func TestHandleAlertingWithProviderThatReturnsAnError(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "jetbrainsspace",
|
||||||
|
AlertType: alert.TypeJetBrainsSpace,
|
||||||
|
AlertingConfig: &alerting.Config{
|
||||||
|
JetBrainsSpace: &jetbrainsspace.AlertProvider{
|
||||||
|
Project: "foo",
|
||||||
|
ChannelID: "bar",
|
||||||
|
Token: "baz",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Name: "mattermost",
|
Name: "mattermost",
|
||||||
AlertType: alert.TypeMattermost,
|
AlertType: alert.TypeMattermost,
|
||||||
@@ -365,7 +377,7 @@ func TestHandleAlertingWithProviderThatReturnsAnError(t *testing.T) {
|
|||||||
AlertType: alert.TypeMatrix,
|
AlertType: alert.TypeMatrix,
|
||||||
AlertingConfig: &alerting.Config{
|
AlertingConfig: &alerting.Config{
|
||||||
Matrix: &matrix.AlertProvider{
|
Matrix: &matrix.AlertProvider{
|
||||||
MatrixProviderConfig: matrix.MatrixProviderConfig{
|
ProviderConfig: matrix.ProviderConfig{
|
||||||
ServerURL: "https://example.com",
|
ServerURL: "https://example.com",
|
||||||
AccessToken: "1",
|
AccessToken: "1",
|
||||||
InternalRoomID: "!a:example.com",
|
InternalRoomID: "!a:example.com",
|
||||||
|
|||||||
+11
-8
@@ -44,12 +44,15 @@ func monitor(endpoint *core.Endpoint, alertingConfig *alerting.Config, maintenan
|
|||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
log.Printf("[watchdog][monitor] Canceling current execution of group=%s; endpoint=%s", endpoint.Group, endpoint.Name)
|
log.Printf("[watchdog.monitor] Canceling current execution of group=%s; endpoint=%s", endpoint.Group, endpoint.Name)
|
||||||
return
|
return
|
||||||
case <-time.After(endpoint.Interval):
|
case <-time.After(endpoint.Interval):
|
||||||
execute(endpoint, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics, debug)
|
execute(endpoint, alertingConfig, maintenanceConfig, connectivityConfig, disableMonitoringLock, enabledMetrics, debug)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Just in case somebody wandered all the way to here and wonders, "what about ExternalEndpoints?"
|
||||||
|
// Alerting is checked every time an external endpoint is pushed to Gatus, so they're not monitored
|
||||||
|
// periodically like they are for normal endpoints.
|
||||||
}
|
}
|
||||||
|
|
||||||
func execute(endpoint *core.Endpoint, alertingConfig *alerting.Config, maintenanceConfig *maintenance.Config, connectivityConfig *connectivity.Config, disableMonitoringLock, enabledMetrics, debug bool) {
|
func execute(endpoint *core.Endpoint, alertingConfig *alerting.Config, maintenanceConfig *maintenance.Config, connectivityConfig *connectivity.Config, disableMonitoringLock, enabledMetrics, debug bool) {
|
||||||
@@ -61,11 +64,11 @@ func execute(endpoint *core.Endpoint, alertingConfig *alerting.Config, maintenan
|
|||||||
}
|
}
|
||||||
// If there's a connectivity checker configured, check if Gatus has internet connectivity
|
// If there's a connectivity checker configured, check if Gatus has internet connectivity
|
||||||
if connectivityConfig != nil && connectivityConfig.Checker != nil && !connectivityConfig.Checker.IsConnected() {
|
if connectivityConfig != nil && connectivityConfig.Checker != nil && !connectivityConfig.Checker.IsConnected() {
|
||||||
log.Println("[watchdog][execute] No connectivity; skipping execution")
|
log.Println("[watchdog.execute] No connectivity; skipping execution")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if debug {
|
if debug {
|
||||||
log.Printf("[watchdog][execute] Monitoring group=%s; endpoint=%s", endpoint.Group, endpoint.Name)
|
log.Printf("[watchdog.execute] Monitoring group=%s; endpoint=%s", endpoint.Group, endpoint.Name)
|
||||||
}
|
}
|
||||||
result := endpoint.EvaluateHealth()
|
result := endpoint.EvaluateHealth()
|
||||||
if enabledMetrics {
|
if enabledMetrics {
|
||||||
@@ -73,25 +76,25 @@ func execute(endpoint *core.Endpoint, alertingConfig *alerting.Config, maintenan
|
|||||||
}
|
}
|
||||||
UpdateEndpointStatuses(endpoint, result)
|
UpdateEndpointStatuses(endpoint, result)
|
||||||
if debug && !result.Success {
|
if debug && !result.Success {
|
||||||
log.Printf("[watchdog][execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s; body=%s", endpoint.Group, endpoint.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond), result.Body)
|
log.Printf("[watchdog.execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s; body=%s", endpoint.Group, endpoint.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond), result.Body)
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[watchdog][execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s", endpoint.Group, endpoint.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond))
|
log.Printf("[watchdog.execute] Monitored group=%s; endpoint=%s; success=%v; errors=%d; duration=%s", endpoint.Group, endpoint.Name, result.Success, len(result.Errors), result.Duration.Round(time.Millisecond))
|
||||||
}
|
}
|
||||||
if !maintenanceConfig.IsUnderMaintenance() {
|
if !maintenanceConfig.IsUnderMaintenance() {
|
||||||
// TODO: Consider moving this after the monitoring lock is unlocked? I mean, how much noise can a single alerting provider cause...
|
// TODO: Consider moving this after the monitoring lock is unlocked? I mean, how much noise can a single alerting provider cause...
|
||||||
HandleAlerting(endpoint, result, alertingConfig, debug)
|
HandleAlerting(endpoint, result, alertingConfig, debug)
|
||||||
} else if debug {
|
} else if debug {
|
||||||
log.Println("[watchdog][execute] Not handling alerting because currently in the maintenance window")
|
log.Println("[watchdog.execute] Not handling alerting because currently in the maintenance window")
|
||||||
}
|
}
|
||||||
if debug {
|
if debug {
|
||||||
log.Printf("[watchdog][execute] Waiting for interval=%s before monitoring group=%s endpoint=%s again", endpoint.Interval, endpoint.Group, endpoint.Name)
|
log.Printf("[watchdog.execute] Waiting for interval=%s before monitoring group=%s endpoint=%s again", endpoint.Interval, endpoint.Group, endpoint.Name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateEndpointStatuses updates the slice of endpoint statuses
|
// UpdateEndpointStatuses updates the slice of endpoint statuses
|
||||||
func UpdateEndpointStatuses(endpoint *core.Endpoint, result *core.Result) {
|
func UpdateEndpointStatuses(endpoint *core.Endpoint, result *core.Result) {
|
||||||
if err := store.Get().Insert(endpoint, result); err != nil {
|
if err := store.Get().Insert(endpoint, result); err != nil {
|
||||||
log.Println("[watchdog][UpdateEndpointStatuses] Failed to insert data in storage:", err.Error())
|
log.Println("[watchdog.UpdateEndpointStatuses] Failed to insert result in storage:", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,12 +5,14 @@
|
|||||||
<code id="tooltip-timestamp">{{ prettifyTimestamp(result.timestamp) }}</code>
|
<code id="tooltip-timestamp">{{ prettifyTimestamp(result.timestamp) }}</code>
|
||||||
<div class="tooltip-title">Response time:</div>
|
<div class="tooltip-title">Response time:</div>
|
||||||
<code id="tooltip-response-time">{{ (result.duration / 1000000).toFixed(0) }}ms</code>
|
<code id="tooltip-response-time">{{ (result.duration / 1000000).toFixed(0) }}ms</code>
|
||||||
<div class="tooltip-title">Conditions:</div>
|
<slot v-if="result.conditionResults && result.conditionResults.length">
|
||||||
<code id="tooltip-conditions">
|
<div class="tooltip-title">Conditions:</div>
|
||||||
<slot v-for="conditionResult in result.conditionResults" :key="conditionResult">
|
<code id="tooltip-conditions">
|
||||||
{{ conditionResult.success ? "✓" : "X" }} ~ {{ conditionResult.condition }}<br/>
|
<slot v-for="conditionResult in result.conditionResults" :key="conditionResult">
|
||||||
</slot>
|
{{ conditionResult.success ? "✓" : "X" }} ~ {{ conditionResult.condition }}<br/>
|
||||||
</code>
|
</slot>
|
||||||
|
</code>
|
||||||
|
</slot>
|
||||||
<div id="tooltip-errors-container" v-if="result.errors && result.errors.length">
|
<div id="tooltip-errors-container" v-if="result.errors && result.errors.length">
|
||||||
<div class="tooltip-title">Errors:</div>
|
<div class="tooltip-title">Errors:</div>
|
||||||
<code id="tooltip-errors">
|
<code id="tooltip-errors">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<router-link to="../"
|
<router-link to="../"
|
||||||
class="absolute top-2 left-2 inline-block px-2 pb-0.5 text-lg text-black bg-gray-100 rounded hover:bg-gray-200 focus:outline-none border border-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-500 dark:hover:bg-gray-600">
|
class="absolute top-2 left-5 inline-block px-2 pb-0.5 text-sm text-black bg-gray-100 rounded hover:bg-gray-200 focus:outline-none border border-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-500 dark:hover:bg-gray-600">
|
||||||
←
|
←
|
||||||
</router-link>
|
</router-link>
|
||||||
<div>
|
<div>
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="endpointStatus && endpointStatus.key" class="mt-12">
|
<div v-if="endpointStatus && endpointStatus.key && showResponseTimeChartAndBadges" class="mt-12">
|
||||||
<h1 class="text-xl xl:text-3xl font-mono text-gray-400">RESPONSE TIME</h1>
|
<h1 class="text-xl xl:text-3xl font-mono text-gray-400">RESPONSE TIME</h1>
|
||||||
<hr/>
|
<hr/>
|
||||||
<img :src="generateResponseTimeChartImageURL()" alt="response time chart" class="mt-6"/>
|
<img :src="generateResponseTimeChartImageURL()" alt="response time chart" class="mt-6"/>
|
||||||
@@ -118,7 +118,6 @@ export default {
|
|||||||
response.json().then(data => {
|
response.json().then(data => {
|
||||||
if (JSON.stringify(this.endpointStatus) !== JSON.stringify(data)) {
|
if (JSON.stringify(this.endpointStatus) !== JSON.stringify(data)) {
|
||||||
this.endpointStatus = data;
|
this.endpointStatus = data;
|
||||||
this.uptime = data.uptime;
|
|
||||||
let events = [];
|
let events = [];
|
||||||
for (let i = data.events.length - 1; i >= 0; i--) {
|
for (let i = data.events.length - 1; i >= 0; i--) {
|
||||||
let event = data.events[i];
|
let event = data.events[i];
|
||||||
@@ -148,6 +147,15 @@ export default {
|
|||||||
events.push(event);
|
events.push(event);
|
||||||
}
|
}
|
||||||
this.events = events;
|
this.events = events;
|
||||||
|
// Check if there's any non-0 response time data
|
||||||
|
// If there isn't, it's likely an external endpoint, which means we should
|
||||||
|
// hide the response time chart and badges
|
||||||
|
for (let i = 0; i < data.results.length; i++) {
|
||||||
|
if (data.results[i].duration > 0) {
|
||||||
|
this.showResponseTimeChartAndBadges = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -183,13 +191,13 @@ export default {
|
|||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
endpointStatus: {},
|
endpointStatus: {},
|
||||||
uptime: {},
|
|
||||||
events: [],
|
events: [],
|
||||||
hourlyAverageResponseTime: {},
|
hourlyAverageResponseTime: {},
|
||||||
// Since this page isn't at the root, we need to modify the server URL a bit
|
// Since this page isn't at the root, we need to modify the server URL a bit
|
||||||
serverUrl: SERVER_URL === '.' ? '..' : SERVER_URL,
|
serverUrl: SERVER_URL === '.' ? '..' : SERVER_URL,
|
||||||
currentPage: 1,
|
currentPage: 1,
|
||||||
showAverageResponseTime: true,
|
showAverageResponseTime: true,
|
||||||
|
showResponseTimeChartAndBadges: false,
|
||||||
chartLabels: [],
|
chartLabels: [],
|
||||||
chartValues: [],
|
chartValues: [],
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,4 +2,4 @@
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
! tailwindcss v3.1.8 | MIT License | https://tailwindcss.com
|
! tailwindcss v3.1.8 | MIT License | https://tailwindcss.com
|
||||||
*/*,:after,:before{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:after,:before{--tw-content:""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:Consolas,Monaco,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::-webkit-backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.coLine truncated
|
*/*,:after,:before{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:after,:before{--tw-content:""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:Consolas,Monaco,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::-webkit-backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.coLine truncated
|
||||||
@@ -1 +1 @@
|
|||||||
(function(){"use strict";var e={9140:function(e,t,s){s.d(t,{L:function(){return us}});s(7727);var n=s(9963),o=s(6252),a=s(3577),r=s.p+"img/logo.svg";const i={class:"mb-2"},l={class:"flex flex-wrap"},d={class:"w-3/4 text-left my-auto"},g={class:"text-3xl xl:text-5xl lg:text-4xl font-light"},h={class:"w-1/4 flex justify-end"},u=["src"],c={key:1,src:r,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},p={key:0,class:"flex flex-wrap"},m=["href"],v={key:2,class:"mx-auto max-w-md pt-12"},f=(0,o._)("img",{src:r,alt:"Gatus",class:"mx-auto",style:{"max-width":"160px","min-width":"50px","min-height":"50px"}},null,-1),w=(0,o._)("h2",{class:"mt-4 text-center text-4xl font-extrabold text-gray-800 dark:text-gray-200"}," Gatus ",-1),x={class:"py-7 px-4 rounded-sm sm:px-10"},y={key:0,class:"text-red-500 text-center mb-5"},k={class:"text-sm"},T={key:0,class:"text-red-500"},b={key:1,class:"text-red-500"},R=["href"];function _(e,t,s,n,r,_){const S=(0,o.up)("Loading"),D=(0,o.up)("router-view"),I=(0,o.up)("Tooltip"),A=(0,o.up)("Social");return(0,o.wg)(),(0,o.iD)(o.HY,null,[r.retrievedConfig?((0,o.wg)(),(0,o.iD)("div",{key:1,class:(0,a.C_)([r.config&&r.config.oidc&&!r.config.authenticated?"hidden":"","container container-xs relative mx-auto xl:rounded xl:border xl:shadow-xl xl:my-5 p-5 pb-12 xl:pb-5 text-left dark:bg-gray-800 dark:text-gray-200 dark:border-gray-500"]),id:"global"},[(0,o._)("div",i,[(0,o._)("div",l,[(0,o._)("div",d,[(0,o._)("div",g,(0,a.zw)(_.header),1)]),(0,o._)("div",h,[((0,o.wg)(),(0,o.j4)((0,o.LL)(_.link?"a":"div"),{href:_.link,target:"_blank",class:"flex items-center justify-center",style:{width:"100px","min-height":"100px"}},{default:(0,o.w5)((()=>[_.logo?((0,o.wg)(),(0,o.iD)("img",{key:0,src:_.logo,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},null,8,u)):((0,o.wg)(),(0,o.iD)("img",c))])),_:1},8,["href"]))])]),_.buttons?((0,o.wg)(),(0,o.iD)("div",p,[((0,o.wg)(!0),(0,o.iD)(o.HY,null,(0,o.Ko)(_.buttons,(e=>((0,o.wg)(),(0,o.iD)("a",{key:e.name,href:e.link,target:"_blank",class:"px-2 py-0.5 font-medium select-none text-gray-600 hover:text-gray-500 dark:text-gray-300 dark:hover:text-gray-400 hover:underline"},(0,a.zw)(e.name),9,m)))),128))])):(0,o.kq)("",!0)]),(0,o.Wm)(D,{onShowTooltip:_.showTooltip},null,8,["onShowTooltip"])],2)):((0,o.wg)(),(0,o.j4)(S,{key:0,class:"h-64 w-64 px-4"})),r.config&&r.config.oidc&&!r.config.authenticated?((0,o.wg)(),(0,o.iD)("div",v,[f,w,(0,o._)("div",x,[e.$route&&e.$route.query.error?((0,o.wg)(),(0,o.iD)("div",y,[(0,o._)("div",k,["access_denied"===e.$route.query.error?((0,o.wg)(),(0,o.iD)("span",T,"You do not have access to this status page")):((0,o.wg)(),(0,o.iD)("span",b,(0,a.zw)(e.$route.query.error),1))])])):(0,o.kq)("",!0),(0,o._)("div",null,[(0,o._)("a",{href:`${r.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 ",8,R)])])])):(0,o.kq)("",!0),(0,o.Wm)(I,{result:r.tooltip.result,event:r.tooltip.event},null,8,["result","event"]),(0,o.Wm)(A)],64)}const S=e=>((0,o.dD)("data-v-a4b3d200"),e=e(),(0,o.Cn)(),e),D={id:"social"},I=S((()=>(0,o._)("a",{href:"https://github.com/TwiN/gatus",target:"_blank",title:"Gatus on GitHub"},[(0,o._)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"32",height:"32",viewBox:"0 0 16 16",class:"hover:scale-110"},[(0,o._)("path",{fill:"gray",d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})])],-1))),A=[I];function C(e,t,s,n,a,r){return(0,o.wg)(),(0,o.iD)("div",D,A)}var $={name:"Social"},P=s(3744);const E=(0,P.Z)($,[["render",C],["__scopeId","data-v-a4b3d200"]]);var H=E;const L=(0,o._)("div",{class:"tooltip-title"},"Timestamp:",-1),U={id:"tooltip-timestamp"},W=(0,o._)("div",{class:"tooltip-title"},"Response time:",-1),M={id:"tooltip-response-time"},O=(0,o._)("div",{class:"tooltip-title"},"Conditions:",-1),j={id:"tooltip-conditions"},q=(0,o._)("br",null,null,-1),B={key:0,id:"tooltip-errors-container"},z=(0,o._)("div",{class:"tooltip-title"},"Errors:",-1),Y={id:"tooltip-errors"},N=(0,o._)("br",null,null,-1);function Z(e,t,s,n,r,i){return(0,o.wg)(),(0,o.iD)("div",{id:"tooltip",ref:"tooltip",class:(0,a.C_)(r.hidden?"invisible":""),style:(0,a.j5)("top:"+r.top+"px; left:"+r.left+"px")},[s.result?(0,o.WI)(e.$slots,"defaultLine truncated
|
(function(){"use strict";var e={1865:function(e,t,s){s.d(t,{L:function(){return us}});s(7727);var n=s(9963),o=s(6252),a=s(3577),r=s.p+"img/logo.svg";const i={class:"mb-2"},l={class:"flex flex-wrap"},d={class:"w-3/4 text-left my-auto"},g={class:"text-3xl xl:text-5xl lg:text-4xl font-light"},h={class:"w-1/4 flex justify-end"},u=["src"],c={key:1,src:r,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},p={key:0,class:"flex flex-wrap"},m=["href"],v={key:2,class:"mx-auto max-w-md pt-12"},f=(0,o._)("img",{src:r,alt:"Gatus",class:"mx-auto",style:{"max-width":"160px","min-width":"50px","min-height":"50px"}},null,-1),w=(0,o._)("h2",{class:"mt-4 text-center text-4xl font-extrabold text-gray-800 dark:text-gray-200"}," Gatus ",-1),x={class:"py-7 px-4 rounded-sm sm:px-10"},y={key:0,class:"text-red-500 text-center mb-5"},k={class:"text-sm"},T={key:0,class:"text-red-500"},b={key:1,class:"text-red-500"},R=["href"];function _(e,t,s,n,r,_){const S=(0,o.up)("Loading"),D=(0,o.up)("router-view"),I=(0,o.up)("Tooltip"),A=(0,o.up)("Social");return(0,o.wg)(),(0,o.iD)(o.HY,null,[r.retrievedConfig?((0,o.wg)(),(0,o.iD)("div",{key:1,class:(0,a.C_)([r.config&&r.config.oidc&&!r.config.authenticated?"hidden":"","container container-xs relative mx-auto xl:rounded xl:border xl:shadow-xl xl:my-5 p-5 pb-12 xl:pb-5 text-left dark:bg-gray-800 dark:text-gray-200 dark:border-gray-500"]),id:"global"},[(0,o._)("div",i,[(0,o._)("div",l,[(0,o._)("div",d,[(0,o._)("div",g,(0,a.zw)(_.header),1)]),(0,o._)("div",h,[((0,o.wg)(),(0,o.j4)((0,o.LL)(_.link?"a":"div"),{href:_.link,target:"_blank",class:"flex items-center justify-center",style:{width:"100px","min-height":"100px"}},{default:(0,o.w5)((()=>[_.logo?((0,o.wg)(),(0,o.iD)("img",{key:0,src:_.logo,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},null,8,u)):((0,o.wg)(),(0,o.iD)("img",c))])),_:1},8,["href"]))])]),_.buttons?((0,o.wg)(),(0,o.iD)("div",p,[((0,o.wg)(!0),(0,o.iD)(o.HY,null,(0,o.Ko)(_.buttons,(e=>((0,o.wg)(),(0,o.iD)("a",{key:e.name,href:e.link,target:"_blank",class:"px-2 py-0.5 font-medium select-none text-gray-600 hover:text-gray-500 dark:text-gray-300 dark:hover:text-gray-400 hover:underline"},(0,a.zw)(e.name),9,m)))),128))])):(0,o.kq)("",!0)]),(0,o.Wm)(D,{onShowTooltip:_.showTooltip},null,8,["onShowTooltip"])],2)):((0,o.wg)(),(0,o.j4)(S,{key:0,class:"h-64 w-64 px-4"})),r.config&&r.config.oidc&&!r.config.authenticated?((0,o.wg)(),(0,o.iD)("div",v,[f,w,(0,o._)("div",x,[e.$route&&e.$route.query.error?((0,o.wg)(),(0,o.iD)("div",y,[(0,o._)("div",k,["access_denied"===e.$route.query.error?((0,o.wg)(),(0,o.iD)("span",T,"You do not have access to this status page")):((0,o.wg)(),(0,o.iD)("span",b,(0,a.zw)(e.$route.query.error),1))])])):(0,o.kq)("",!0),(0,o._)("div",null,[(0,o._)("a",{href:`${r.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 ",8,R)])])])):(0,o.kq)("",!0),(0,o.Wm)(I,{result:r.tooltip.result,event:r.tooltip.event},null,8,["result","event"]),(0,o.Wm)(A)],64)}const S=e=>((0,o.dD)("data-v-a4b3d200"),e=e(),(0,o.Cn)(),e),D={id:"social"},I=S((()=>(0,o._)("a",{href:"https://github.com/TwiN/gatus",target:"_blank",title:"Gatus on GitHub"},[(0,o._)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"32",height:"32",viewBox:"0 0 16 16",class:"hover:scale-110"},[(0,o._)("path",{fill:"gray",d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})])],-1))),A=[I];function C(e,t,s,n,a,r){return(0,o.wg)(),(0,o.iD)("div",D,A)}var $={name:"Social"},P=s(3744);const E=(0,P.Z)($,[["render",C],["__scopeId","data-v-a4b3d200"]]);var H=E;const L=(0,o._)("div",{class:"tooltip-title"},"Timestamp:",-1),U={id:"tooltip-timestamp"},W=(0,o._)("div",{class:"tooltip-title"},"Response time:",-1),M={id:"tooltip-response-time"},O=(0,o._)("div",{class:"tooltip-title"},"Conditions:",-1),B={id:"tooltip-conditions"},j=(0,o._)("br",null,null,-1),q={key:1,id:"tooltip-errors-container"},z=(0,o._)("div",{class:"tooltip-title"},"Errors:",-1),Y={id:"tooltip-errors"},N=(0,o._)("br",null,null,-1);function Z(e,t,s,n,r,i){return(0,o.wg)(),(0,o.iD)("div",{id:"tooltip",ref:"tooltip",class:(0,a.C_)(r.hidden?"invisible":""),style:(0,a.j5)("top:"+r.top+"px; left:"+r.left+"px")},[s.result?(0,o.WI)(e.$slots,"defaultLine truncated
|
||||||
Reference in new issue
Block a user