Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2be81b8e1a | ||
|
|
4bed86dec9 | ||
|
|
072cf20cc6 | ||
|
|
cca421e283 | ||
|
|
a044f1d274 | ||
|
|
9de6334f21 | ||
|
|
f01b66f083 | ||
|
|
262d436533 | ||
|
|
b8ab17eee1 | ||
|
|
7bbd7bcee3 | ||
|
|
4865d12147 | ||
|
|
0713ca1c1a | ||
|
|
dce202d0be | ||
|
|
4673d147db | ||
|
|
0943c45ae6 | ||
|
|
798c4248ff | ||
|
|
1bce4e727e | ||
|
|
1aa94a3365 | ||
|
|
319f460553 | ||
|
|
7daf2b5cac | ||
|
|
f0fc275f67 | ||
|
|
04a682eddc | ||
|
|
2fb807632c | ||
|
|
4b339bca37 | ||
|
|
09c3a6c72b | ||
|
|
755c8bb43a | ||
|
|
9d4a639f31 | ||
|
|
60e6b2b039 | ||
|
|
37f3f964ea | ||
|
|
4a1a8ff380 | ||
|
|
6787fed062 |
No files matched your search
@@ -0,0 +1,28 @@
|
|||||||
|
name: publish-experimental
|
||||||
|
on: [workflow_dispatch]
|
||||||
|
jobs:
|
||||||
|
publish-experimental:
|
||||||
|
name: publish-experimental
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 20
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Get image repository
|
||||||
|
run: echo IMAGE_REPOSITORY=$(echo ${{ secrets.DOCKER_USERNAME }}/${{ github.event.repository.name }} | tr '[:upper:]' '[:lower:]') >> $GITHUB_ENV
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v1
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v1
|
||||||
|
- name: Login to Docker Registry
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
- name: Build and push docker image
|
||||||
|
uses: docker/build-push-action@v2
|
||||||
|
with:
|
||||||
|
platforms: linux/amd64
|
||||||
|
pull: true
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
${{ env.IMAGE_REPOSITORY }}:experimental
|
||||||
@@ -9,7 +9,7 @@ jobs:
|
|||||||
name: publish-latest
|
name: publish-latest
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||||
timeout-minutes: 45
|
timeout-minutes: 60
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Get image repository
|
- name: Get image repository
|
||||||
@@ -19,7 +19,7 @@ jobs:
|
|||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v1
|
uses: docker/setup-buildx-action@v1
|
||||||
- name: Login to Docker Registry
|
- name: Login to Docker Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ jobs:
|
|||||||
publish-release:
|
publish-release:
|
||||||
name: publish-release
|
name: publish-release
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 45
|
timeout-minutes: 60
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Get image repository
|
- name: Get image repository
|
||||||
@@ -18,7 +18,7 @@ jobs:
|
|||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v1
|
uses: docker/setup-buildx-action@v1
|
||||||
- name: Login to Docker Registry
|
- name: Login to Docker Registry
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|||||||
@@ -186,7 +186,7 @@
|
|||||||
same "printed page" as the copyright notice for easier
|
same "printed page" as the copyright notice for easier
|
||||||
identification within third-party archives.
|
identification within third-party archives.
|
||||||
|
|
||||||
Copyright 2021 TwiN
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ For more details, see [Usage](#usage)
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
Have any feedback or want to share your good/bad experience with Gatus? Feel free to email me at [feedback@gatus.io](mailto:feedback@gatus.io)
|
Have any feedback or questions? [Create a discussion](https://github.com/TwiN/gatus/discussions/new).
|
||||||
|
|
||||||
## Table of Contents
|
## Table of Contents
|
||||||
- [Why Gatus?](#why-gatus)
|
- [Why Gatus?](#why-gatus)
|
||||||
@@ -42,6 +42,7 @@ Have any feedback or want to share your good/bad experience with Gatus? Feel fre
|
|||||||
- [Configuring Discord alerts](#configuring-discord-alerts)
|
- [Configuring Discord alerts](#configuring-discord-alerts)
|
||||||
- [Configuring Email alerts](#configuring-email-alerts)
|
- [Configuring Email alerts](#configuring-email-alerts)
|
||||||
- [Configuring Google Chat alerts](#configuring-google-chat-alerts)
|
- [Configuring Google Chat alerts](#configuring-google-chat-alerts)
|
||||||
|
- [Configuring Matrix alerts](#configuring-matrix-alerts)
|
||||||
- [Configuring Mattermost alerts](#configuring-mattermost-alerts)
|
- [Configuring Mattermost alerts](#configuring-mattermost-alerts)
|
||||||
- [Configuring Messagebird alerts](#configuring-messagebird-alerts)
|
- [Configuring Messagebird alerts](#configuring-messagebird-alerts)
|
||||||
- [Configuring Opsgenie alerts](#configuring-opsgenie-alerts)
|
- [Configuring Opsgenie alerts](#configuring-opsgenie-alerts)
|
||||||
@@ -57,6 +58,7 @@ Have any feedback or want to share your good/bad experience with Gatus? Feel fre
|
|||||||
- [Basic](#basic)
|
- [Basic](#basic)
|
||||||
- [OIDC (ALPHA)](#oidc-alpha)
|
- [OIDC (ALPHA)](#oidc-alpha)
|
||||||
- [Metrics](#metrics)
|
- [Metrics](#metrics)
|
||||||
|
- [Remote instances (EXPERIMENTAL)](#remote-instances-experimental)
|
||||||
- [Deployment](#deployment)
|
- [Deployment](#deployment)
|
||||||
- [Docker](#docker)
|
- [Docker](#docker)
|
||||||
- [Helm Chart](#helm-chart)
|
- [Helm Chart](#helm-chart)
|
||||||
@@ -177,6 +179,7 @@ If you want to test it locally, see [Docker](#docker).
|
|||||||
| `endpoints[].ui.hide-hostname` | Whether to hide the hostname in the result. | `false` |
|
| `endpoints[].ui.hide-hostname` | Whether to hide the hostname in the result. | `false` |
|
||||||
| `endpoints[].ui.hide-url` | Whether to ensure the URL is not displayed in the results. Useful if the URL contains a token. | `false` |
|
| `endpoints[].ui.hide-url` | Whether to ensure the URL is not displayed in the results. Useful if the URL contains a token. | `false` |
|
||||||
| `endpoints[].ui.dont-resolve-failed-conditions` | Whether to resolve failed conditions for the UI. | `false` |
|
| `endpoints[].ui.dont-resolve-failed-conditions` | Whether to resolve failed conditions for the UI. | `false` |
|
||||||
|
| `endpoints[].ui.badge.reponse-time` | List of response time thresholds. Each time a threshold is reached, the badge has a different color. | `[50, 200, 300, 500, 750]` |
|
||||||
| `alerting` | [Alerting configuration](#alerting). | `{}` |
|
| `alerting` | [Alerting configuration](#alerting). | `{}` |
|
||||||
| `security` | [Security configuration](#security). | `{}` |
|
| `security` | [Security configuration](#security). | `{}` |
|
||||||
| `disable-monitoring-lock` | Whether to [disable the monitoring lock](#disable-monitoring-lock). | `false` |
|
| `disable-monitoring-lock` | Whether to [disable the monitoring lock](#disable-monitoring-lock). | `false` |
|
||||||
@@ -245,11 +248,12 @@ Here are some examples of conditions you can use:
|
|||||||
|
|
||||||
|
|
||||||
### Storage
|
### Storage
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:---------------|:-------------------------------------------------------------------------------|:-----------|
|
|:------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------|:-----------|
|
||||||
| `storage` | Storage configuration | `{}` |
|
| `storage` | Storage configuration | `{}` |
|
||||||
| `storage.path` | Path to persist the data in. Only supported for types `sqlite` and `postgres`. | `""` |
|
| `storage.path` | Path to persist the data in. Only supported for types `sqlite` and `postgres`. | `""` |
|
||||||
| `storage.type` | Type of storage. Valid types: `memory`, `sqlite`, `postgres`. | `"memory"` |
|
| `storage.type` | Type of storage. Valid types: `memory`, `sqlite`, `postgres`. | `"memory"` |
|
||||||
|
| `storage.caching` | Whether to use write-through caching. Improves loading time for large dashboards. <br />Only supported if `storage.type` is `sqlite` or `postgres` | `false` |
|
||||||
|
|
||||||
- If `storage.type` is `memory` (default):
|
- If `storage.type` is `memory` (default):
|
||||||
```yaml
|
```yaml
|
||||||
@@ -488,6 +492,37 @@ endpoints:
|
|||||||
send-on-resolved: true
|
send-on-resolved: true
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Configuring Matrix alerts
|
||||||
|
| Parameter | Description | Default |
|
||||||
|
|:-----------------------------------|:-------------------------------------------------------------------------------------------------|:-----------------------------------|
|
||||||
|
| `alerting.matrix` | Settings for alerts of type `matrix` | `{}` |
|
||||||
|
| `alerting.matrix.server-url` | Homeserver URL | `https://matrix-client.matrix.org` |
|
||||||
|
| `alerting.matrix.access-token` | Bot user access token (see https://webapps.stackexchange.com/q/131056) | Required `""` |
|
||||||
|
| `alerting.matrix.internal-room-id` | Internal room ID of room to send alerts to (can be found in Element in Room Settings > Advanced) | Required `""` |
|
||||||
|
| `alerting.matrix.default-alert` | Default alert configuration. <br />See [Setting a default alert](#setting-a-default-alert) | N/A |
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
alerting:
|
||||||
|
matrix:
|
||||||
|
server-url: "..."
|
||||||
|
access-token: "..."
|
||||||
|
internal-room-id: "..."
|
||||||
|
|
||||||
|
endpoints:
|
||||||
|
- name: website
|
||||||
|
interval: 30s
|
||||||
|
url: "https://twin.sh/health"
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
- "[BODY].status == UP"
|
||||||
|
- "[RESPONSE_TIME] < 300"
|
||||||
|
alerts:
|
||||||
|
- type: matrix
|
||||||
|
enabled: true
|
||||||
|
send-on-resolved: true
|
||||||
|
description: "healthcheck failed"
|
||||||
|
```
|
||||||
|
|
||||||
#### Configuring Mattermost alerts
|
#### Configuring Mattermost alerts
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:----------------------------------------------|:--------------------------------------------------------------------------------------------|:--------------|
|
|:----------------------------------------------|:--------------------------------------------------------------------------------------------|:--------------|
|
||||||
@@ -801,7 +836,6 @@ endpoints:
|
|||||||
description: "healthcheck failed"
|
description: "healthcheck failed"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
#### Configuring custom alerts
|
#### Configuring custom alerts
|
||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|:--------------------------------|:-------------------------------------------------------------------------------------------|:--------------|
|
|:--------------------------------|:-------------------------------------------------------------------------------------------|:--------------|
|
||||||
@@ -1059,6 +1093,32 @@ endpoint on the same port your application is configured to run on (`web.port`).
|
|||||||
See [examples/docker-compose-grafana-prometheus](.examples/docker-compose-grafana-prometheus) for further documentation as well as an example.
|
See [examples/docker-compose-grafana-prometheus](.examples/docker-compose-grafana-prometheus) for further documentation as well as an example.
|
||||||
|
|
||||||
|
|
||||||
|
### Remote instances (EXPERIMENTAL)
|
||||||
|
This feature allows you to retrieve endpoint statuses from a remote Gatus instance.
|
||||||
|
|
||||||
|
There are two main use cases for this:
|
||||||
|
- You have multiple Gatus instances running on different machines, and you wish to visually expose the statuses through a single dashboard
|
||||||
|
- You have one or more Gatus instances that are not publicly accessible (e.g. behind a firewall), and you wish to retrieve
|
||||||
|
|
||||||
|
This is an experimental feature. It may be removed or updated in a breaking manner at any time. Furthermore,
|
||||||
|
there are known issues with this feature. If you'd like to provide some feedback, please write a comment in [#64](https://github.com/TwiN/gatus/issues/64).
|
||||||
|
Use at your own risk.
|
||||||
|
|
||||||
|
| Parameter | Description | Default |
|
||||||
|
|:-----------------------------------|:---------------------------------------------|:---------------|
|
||||||
|
| `remote` | Remote configuration | `{}` |
|
||||||
|
| `remote.instances` | List of remote instances | Required `[]` |
|
||||||
|
| `remote.instances.endpoint-prefix` | String to prefix all endpoint names with | `""` |
|
||||||
|
| `remote.instances.url` | URL from which to retrieve endpoint statuses | Required `""` |
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
remote:
|
||||||
|
instances:
|
||||||
|
- endpoint-prefix: "status.example.org-"
|
||||||
|
url: "https://status.example.org/api/v1/endpoints/statuses"
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## Deployment
|
## Deployment
|
||||||
Many examples can be found in the [.examples](.examples) folder, but this section will focus on the most popular ways of deploying Gatus.
|
Many examples can be found in the [.examples](.examples) folder, but this section will focus on the most popular ways of deploying Gatus.
|
||||||
|
|
||||||
@@ -1438,6 +1498,24 @@ Where:
|
|||||||
- `{duration}` is `7d`, `24h` or `1h`
|
- `{duration}` is `7d`, `24h` or `1h`
|
||||||
- `{key}` has the pattern `<GROUP_NAME>_<ENDPOINT_NAME>` in which both variables have ` `, `/`, `_`, `,` and `.` replaced by `-`.
|
- `{key}` has the pattern `<GROUP_NAME>_<ENDPOINT_NAME>` in which both variables have ` `, `/`, `_`, `,` and `.` replaced by `-`.
|
||||||
|
|
||||||
|
##### How to change the color thresholds of the response time badge
|
||||||
|
To change the response time badges threshold, a corresponding configuration can be added to an endpoint.
|
||||||
|
The values in the array correspond to the levels [Awesome, Great, Good, Passable, Bad]
|
||||||
|
All five values must be given in milliseconds (ms).
|
||||||
|
|
||||||
|
```
|
||||||
|
endpoints:
|
||||||
|
- name: nas
|
||||||
|
group: internal
|
||||||
|
url: "https://example.org/"
|
||||||
|
interval: 5m
|
||||||
|
conditions:
|
||||||
|
- "[STATUS] == 200"
|
||||||
|
ui:
|
||||||
|
badge:
|
||||||
|
response-time:
|
||||||
|
thresholds: [550, 850, 1350, 1650, 1750]
|
||||||
|
```
|
||||||
|
|
||||||
### API
|
### API
|
||||||
Gatus provides a simple read-only API that can be queried in order to programmatically determine endpoint status and history.
|
Gatus provides a simple read-only API that can be queried in order to programmatically determine endpoint status and history.
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ const (
|
|||||||
// TypeGoogleChat is the Type for the googlechat alerting provider
|
// TypeGoogleChat is the Type for the googlechat alerting provider
|
||||||
TypeGoogleChat Type = "googlechat"
|
TypeGoogleChat Type = "googlechat"
|
||||||
|
|
||||||
|
// TypeMatrix is the Type for the matrix alerting provider
|
||||||
|
TypeMatrix Type = "matrix"
|
||||||
|
|
||||||
// TypeMattermost is the Type for the mattermost alerting provider
|
// TypeMattermost is the Type for the mattermost alerting provider
|
||||||
TypeMattermost Type = "mattermost"
|
TypeMattermost Type = "mattermost"
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v4/alerting/provider/discord"
|
"github.com/TwiN/gatus/v4/alerting/provider/discord"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/email"
|
"github.com/TwiN/gatus/v4/alerting/provider/email"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/googlechat"
|
"github.com/TwiN/gatus/v4/alerting/provider/googlechat"
|
||||||
|
"github.com/TwiN/gatus/v4/alerting/provider/matrix"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v4/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v4/alerting/provider/messagebird"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/opsgenie"
|
"github.com/TwiN/gatus/v4/alerting/provider/opsgenie"
|
||||||
@@ -31,6 +32,9 @@ type Config struct {
|
|||||||
// Email is the configuration for the email alerting provider
|
// Email is the configuration for the email alerting provider
|
||||||
Email *email.AlertProvider `yaml:"email,omitempty"`
|
Email *email.AlertProvider `yaml:"email,omitempty"`
|
||||||
|
|
||||||
|
// Matrix is the configuration for the matrix alerting provider
|
||||||
|
Matrix *matrix.AlertProvider `yaml:"matrix,omitempty"`
|
||||||
|
|
||||||
// Mattermost is the configuration for the mattermost alerting provider
|
// Mattermost is the configuration for the mattermost alerting provider
|
||||||
Mattermost *mattermost.AlertProvider `yaml:"mattermost,omitempty"`
|
Mattermost *mattermost.AlertProvider `yaml:"mattermost,omitempty"`
|
||||||
|
|
||||||
@@ -83,6 +87,12 @@ func (config Config) GetAlertingProviderByAlertType(alertType alert.Type) provid
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return config.GoogleChat
|
return config.GoogleChat
|
||||||
|
case alert.TypeMatrix:
|
||||||
|
if config.Matrix == nil {
|
||||||
|
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return config.Matrix
|
||||||
case alert.TypeMattermost:
|
case alert.TypeMattermost:
|
||||||
if config.Mattermost == nil {
|
if config.Mattermost == nil {
|
||||||
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
// Since we're returning an interface, we need to explicitly return nil, even if the provider itself is nil
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
package matrix
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v4/client"
|
||||||
|
"github.com/TwiN/gatus/v4/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AlertProvider is the configuration necessary for sending an alert using Matrix
|
||||||
|
type AlertProvider struct {
|
||||||
|
MatrixProviderConfig `yaml:",inline"`
|
||||||
|
|
||||||
|
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
|
||||||
|
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
|
||||||
|
|
||||||
|
// Overrides is a list of Override that may be prioritized over the default configuration
|
||||||
|
Overrides []Override `yaml:"overrides,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Override is a case under which the default integration is overridden
|
||||||
|
type Override struct {
|
||||||
|
Group string `yaml:"group"`
|
||||||
|
|
||||||
|
MatrixProviderConfig `yaml:",inline"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultHomeserverURL = "https://matrix-client.matrix.org"
|
||||||
|
|
||||||
|
type MatrixProviderConfig struct {
|
||||||
|
// ServerURL is the custom homeserver to use (optional)
|
||||||
|
ServerURL string `yaml:"server-url"`
|
||||||
|
|
||||||
|
// AccessToken is the bot user's access token to send messages
|
||||||
|
AccessToken string `yaml:"access-token"`
|
||||||
|
|
||||||
|
// InternalRoomID is the room that the bot user has permissions to send messages to
|
||||||
|
InternalRoomID string `yaml:"internal-room-id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsValid returns whether the provider's configuration is valid
|
||||||
|
func (provider *AlertProvider) IsValid() bool {
|
||||||
|
registeredGroups := make(map[string]bool)
|
||||||
|
if provider.Overrides != nil {
|
||||||
|
for _, override := range provider.Overrides {
|
||||||
|
if isAlreadyRegistered := registeredGroups[override.Group]; isAlreadyRegistered || override.Group == "" || len(override.AccessToken) == 0 || len(override.InternalRoomID) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
registeredGroups[override.Group] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(provider.AccessToken) > 0 && len(provider.InternalRoomID) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send an alert using the provider
|
||||||
|
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
|
||||||
|
buffer := bytes.NewBuffer([]byte(provider.buildRequestBody(endpoint, alert, result, resolved)))
|
||||||
|
config := provider.getConfigForGroup(endpoint.Group)
|
||||||
|
if config.ServerURL == "" {
|
||||||
|
config.ServerURL = defaultHomeserverURL
|
||||||
|
}
|
||||||
|
// The Matrix endpoint requires a unique transaction ID for each event sent
|
||||||
|
txnId := randStringBytes(24)
|
||||||
|
request, err := http.NewRequest(
|
||||||
|
http.MethodPut,
|
||||||
|
fmt.Sprintf("%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s?access_token=%s",
|
||||||
|
config.ServerURL,
|
||||||
|
url.PathEscape(config.InternalRoomID),
|
||||||
|
txnId,
|
||||||
|
url.QueryEscape(config.AccessToken),
|
||||||
|
),
|
||||||
|
buffer,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := client.GetHTTPClient(nil).Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if response.StatusCode > 399 {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
return fmt.Errorf("call to provider alert returned status code %d: %s", response.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRequestBody builds the request body for the provider
|
||||||
|
func (provider *AlertProvider) buildRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
|
return fmt.Sprintf(`{
|
||||||
|
"msgtype": "m.text",
|
||||||
|
"format": "org.matrix.custom.html",
|
||||||
|
"body": "%s",
|
||||||
|
"formatted_body": "%s"
|
||||||
|
}`,
|
||||||
|
buildPlaintextMessageBody(endpoint, alert, result, resolved),
|
||||||
|
buildHTMLMessageBody(endpoint, alert, result, resolved),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildPlaintextMessageBody builds the message body in plaintext to include in request
|
||||||
|
func buildPlaintextMessageBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
|
var message, results string
|
||||||
|
if resolved {
|
||||||
|
message = fmt.Sprintf("An alert for `%s` has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
|
} else {
|
||||||
|
message = fmt.Sprintf("An alert for `%s` has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
|
}
|
||||||
|
for _, conditionResult := range result.ConditionResults {
|
||||||
|
var prefix string
|
||||||
|
if conditionResult.Success {
|
||||||
|
prefix = "✓"
|
||||||
|
} else {
|
||||||
|
prefix = "✕"
|
||||||
|
}
|
||||||
|
results += fmt.Sprintf("\\n%s - %s", prefix, conditionResult.Condition)
|
||||||
|
}
|
||||||
|
var description string
|
||||||
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
|
description = "\\n" + alertDescription
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s%s\\n%s", message, description, results)
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildHTMLMessageBody builds the message body in HTML to include in request
|
||||||
|
func buildHTMLMessageBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) string {
|
||||||
|
var message, results string
|
||||||
|
if resolved {
|
||||||
|
message = fmt.Sprintf("An alert for <code>%s</code> has been resolved after passing successfully %d time(s) in a row", endpoint.DisplayName(), alert.SuccessThreshold)
|
||||||
|
} else {
|
||||||
|
message = fmt.Sprintf("An alert for <code>%s</code> has been triggered due to having failed %d time(s) in a row", endpoint.DisplayName(), alert.FailureThreshold)
|
||||||
|
}
|
||||||
|
for _, conditionResult := range result.ConditionResults {
|
||||||
|
var prefix string
|
||||||
|
if conditionResult.Success {
|
||||||
|
prefix = "✅"
|
||||||
|
} else {
|
||||||
|
prefix = "❌"
|
||||||
|
}
|
||||||
|
results += fmt.Sprintf("<li>%s - <code>%s</code></li>", prefix, conditionResult.Condition)
|
||||||
|
}
|
||||||
|
var description string
|
||||||
|
if alertDescription := alert.GetDescription(); len(alertDescription) > 0 {
|
||||||
|
description = fmt.Sprintf("\\n<blockquote>%s</blockquote>", alertDescription)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("<h3>%s</h3>%s\\n<h5>Condition results</h5><ul>%s</ul>", message, description, results)
|
||||||
|
}
|
||||||
|
|
||||||
|
// getConfigForGroup returns the appropriate configuration for a given group
|
||||||
|
func (provider *AlertProvider) getConfigForGroup(group string) MatrixProviderConfig {
|
||||||
|
if provider.Overrides != nil {
|
||||||
|
for _, override := range provider.Overrides {
|
||||||
|
if group == override.Group {
|
||||||
|
return MatrixProviderConfig{
|
||||||
|
ServerURL: override.ServerURL,
|
||||||
|
AccessToken: override.AccessToken,
|
||||||
|
InternalRoomID: override.InternalRoomID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return MatrixProviderConfig{
|
||||||
|
ServerURL: provider.ServerURL,
|
||||||
|
AccessToken: provider.AccessToken,
|
||||||
|
InternalRoomID: provider.InternalRoomID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func randStringBytes(n int) string {
|
||||||
|
// All the compatible characters to use in a transaction ID
|
||||||
|
const availableCharacterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
|
||||||
|
b := make([]byte, n)
|
||||||
|
rand.Seed(time.Now().UnixNano())
|
||||||
|
for i := range b {
|
||||||
|
b[i] = availableCharacterBytes[rand.Intn(len(availableCharacterBytes))]
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultAlert returns the provider's default alert configuration
|
||||||
|
func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
|
||||||
|
return provider.DefaultAlert
|
||||||
|
}
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
package matrix
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/alerting/alert"
|
||||||
|
"github.com/TwiN/gatus/v4/client"
|
||||||
|
"github.com/TwiN/gatus/v4/core"
|
||||||
|
"github.com/TwiN/gatus/v4/test"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAlertProvider_IsValid(t *testing.T) {
|
||||||
|
invalidProvider := AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
AccessToken: "",
|
||||||
|
InternalRoomID: "",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if invalidProvider.IsValid() {
|
||||||
|
t.Error("provider shouldn't have been valid")
|
||||||
|
}
|
||||||
|
validProvider := AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if !validProvider.IsValid() {
|
||||||
|
t.Error("provider should've been valid")
|
||||||
|
}
|
||||||
|
validProviderWithHomeserver := AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if !validProviderWithHomeserver.IsValid() {
|
||||||
|
t.Error("provider with homeserver should've been valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_IsValidWithOverride(t *testing.T) {
|
||||||
|
providerWithInvalidOverrideGroup := AlertProvider{
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "",
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
AccessToken: "",
|
||||||
|
InternalRoomID: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if providerWithInvalidOverrideGroup.IsValid() {
|
||||||
|
t.Error("provider Group shouldn't have been valid")
|
||||||
|
}
|
||||||
|
providerWithInvalidOverrideTo := AlertProvider{
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
AccessToken: "",
|
||||||
|
InternalRoomID: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if providerWithInvalidOverrideTo.IsValid() {
|
||||||
|
t.Error("provider integration key shouldn't have been valid")
|
||||||
|
}
|
||||||
|
providerWithValidOverride := AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if !providerWithValidOverride.IsValid() {
|
||||||
|
t.Error("provider should've been valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_Send(t *testing.T) {
|
||||||
|
defer client.InjectHTTPClient(nil)
|
||||||
|
firstDescription := "description-1"
|
||||||
|
secondDescription := "description-2"
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
MockRoundTripper test.MockRoundTripper
|
||||||
|
ExpectedError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "triggered-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved-error",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
MockRoundTripper: test.MockRoundTripper(func(r *http.Request) *http.Response {
|
||||||
|
return &http.Response{StatusCode: http.StatusInternalServerError, Body: http.NoBody}
|
||||||
|
}),
|
||||||
|
ExpectedError: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
|
||||||
|
err := scenario.Provider.Send(
|
||||||
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
|
&scenario.Alert,
|
||||||
|
&core.Result{
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scenario.Resolved,
|
||||||
|
)
|
||||||
|
if scenario.ExpectedError && err == nil {
|
||||||
|
t.Error("expected error, got none")
|
||||||
|
}
|
||||||
|
if !scenario.ExpectedError && err != nil {
|
||||||
|
t.Error("expected no error, got", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_buildRequestBody(t *testing.T) {
|
||||||
|
firstDescription := "description-1"
|
||||||
|
secondDescription := "description-2"
|
||||||
|
scenarios := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
Alert alert.Alert
|
||||||
|
Resolved bool
|
||||||
|
ExpectedBody string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "triggered",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &firstDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: false,
|
||||||
|
ExpectedBody: "{\n\t\"msgtype\": \"m.text\",\n\t\"format\": \"org.matrix.custom.html\",\n\t\"body\": \"An alert for `endpoint-name` has been triggered due to having failed 3 time(s) in a row\\ndescription-1\\n\\n✕ - [CONNECTED] == true\\n✕ - [STATUS] == 200\",\n\t\"formatted_body\": \"<h3>An alert for <code>endpoint-name</code> has been triggered due to having failed 3 time(s) in a row</h3>\\n<blockquote>description-1</blockquote>\\n<h5>Condition results</h5><ul><li>❌ - <code>[CONNECTED] == true</code></li><li>❌ - <code>[STATUS] == 200</code></li></ul>\"\n}",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "resolved",
|
||||||
|
Provider: AlertProvider{},
|
||||||
|
Alert: alert.Alert{Description: &secondDescription, SuccessThreshold: 5, FailureThreshold: 3},
|
||||||
|
Resolved: true,
|
||||||
|
ExpectedBody: "{\n\t\"msgtype\": \"m.text\",\n\t\"format\": \"org.matrix.custom.html\",\n\t\"body\": \"An alert for `endpoint-name` has been resolved after passing successfully 5 time(s) in a row\\ndescription-2\\n\\n✓ - [CONNECTED] == true\\n✓ - [STATUS] == 200\",\n\t\"formatted_body\": \"<h3>An alert for <code>endpoint-name</code> has been resolved after passing successfully 5 time(s) in a row</h3>\\n<blockquote>description-2</blockquote>\\n<h5>Condition results</h5><ul><li>✅ - <code>[CONNECTED] == true</code></li><li>✅ - <code>[STATUS] == 200</code></li></ul>\"\n}",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
body := scenario.Provider.buildRequestBody(
|
||||||
|
&core.Endpoint{Name: "endpoint-name"},
|
||||||
|
&scenario.Alert,
|
||||||
|
&core.Result{
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{Condition: "[CONNECTED] == true", Success: scenario.Resolved},
|
||||||
|
{Condition: "[STATUS] == 200", Success: scenario.Resolved},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scenario.Resolved,
|
||||||
|
)
|
||||||
|
if body != scenario.ExpectedBody {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.ExpectedBody, body)
|
||||||
|
}
|
||||||
|
out := make(map[string]interface{})
|
||||||
|
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||||
|
t.Error("expected body to be valid JSON, got error:", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_GetDefaultAlert(t *testing.T) {
|
||||||
|
if (AlertProvider{DefaultAlert: &alert.Alert{}}).GetDefaultAlert() == nil {
|
||||||
|
t.Error("expected default alert to be not nil")
|
||||||
|
}
|
||||||
|
if (AlertProvider{DefaultAlert: nil}).GetDefaultAlert() != nil {
|
||||||
|
t.Error("expected default alert to be nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAlertProvider_getConfigForGroup(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
Name string
|
||||||
|
Provider AlertProvider
|
||||||
|
InputGroup string
|
||||||
|
ExpectedOutput MatrixProviderConfig
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Name: "provider-no-override-specify-no-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
Overrides: nil,
|
||||||
|
},
|
||||||
|
InputGroup: "",
|
||||||
|
ExpectedOutput: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-no-override-specify-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
Overrides: nil,
|
||||||
|
},
|
||||||
|
InputGroup: "group",
|
||||||
|
ExpectedOutput: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-with-override-specify-no-group-should-default",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example01.com",
|
||||||
|
AccessToken: "12",
|
||||||
|
InternalRoomID: "!a:example01.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
InputGroup: "",
|
||||||
|
ExpectedOutput: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "provider-with-override-specify-group-should-override",
|
||||||
|
Provider: AlertProvider{
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
Overrides: []Override{
|
||||||
|
{
|
||||||
|
Group: "group",
|
||||||
|
MatrixProviderConfig: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example01.com",
|
||||||
|
AccessToken: "12",
|
||||||
|
InternalRoomID: "!a:example01.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
InputGroup: "group",
|
||||||
|
ExpectedOutput: MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example01.com",
|
||||||
|
AccessToken: "12",
|
||||||
|
InternalRoomID: "!a:example01.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.Name, func(t *testing.T) {
|
||||||
|
if got := tt.Provider.getConfigForGroup(tt.InputGroup); got != tt.ExpectedOutput {
|
||||||
|
t.Errorf("AlertProvider.getConfigForGroup() = %v, want %v", got, tt.ExpectedOutput)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v4/alerting/provider/discord"
|
"github.com/TwiN/gatus/v4/alerting/provider/discord"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/email"
|
"github.com/TwiN/gatus/v4/alerting/provider/email"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/googlechat"
|
"github.com/TwiN/gatus/v4/alerting/provider/googlechat"
|
||||||
|
"github.com/TwiN/gatus/v4/alerting/provider/matrix"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v4/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v4/alerting/provider/messagebird"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/opsgenie"
|
"github.com/TwiN/gatus/v4/alerting/provider/opsgenie"
|
||||||
@@ -57,6 +58,7 @@ var (
|
|||||||
_ AlertProvider = (*discord.AlertProvider)(nil)
|
_ AlertProvider = (*discord.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*email.AlertProvider)(nil)
|
_ AlertProvider = (*email.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*googlechat.AlertProvider)(nil)
|
_ AlertProvider = (*googlechat.AlertProvider)(nil)
|
||||||
|
_ AlertProvider = (*matrix.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*mattermost.AlertProvider)(nil)
|
_ AlertProvider = (*mattermost.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*messagebird.AlertProvider)(nil)
|
_ AlertProvider = (*messagebird.AlertProvider)(nil)
|
||||||
_ AlertProvider = (*opsgenie.AlertProvider)(nil)
|
_ AlertProvider = (*opsgenie.AlertProvider)(nil)
|
||||||
|
|||||||
+1
-1
@@ -17,7 +17,7 @@ import (
|
|||||||
// injectedHTTPClient is used for testing purposes
|
// injectedHTTPClient is used for testing purposes
|
||||||
var injectedHTTPClient *http.Client
|
var injectedHTTPClient *http.Client
|
||||||
|
|
||||||
// GetHTTPClient returns the shared HTTP client
|
// GetHTTPClient returns the shared HTTP client, or the client from the configuration passed
|
||||||
func GetHTTPClient(config *Config) *http.Client {
|
func GetHTTPClient(config *Config) *http.Client {
|
||||||
if injectedHTTPClient != nil {
|
if injectedHTTPClient != nil {
|
||||||
return injectedHTTPClient
|
return injectedHTTPClient
|
||||||
|
|||||||
@@ -10,11 +10,13 @@ import (
|
|||||||
"github.com/TwiN/gatus/v4/alerting/alert"
|
"github.com/TwiN/gatus/v4/alerting/alert"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider"
|
"github.com/TwiN/gatus/v4/alerting/provider"
|
||||||
"github.com/TwiN/gatus/v4/config/maintenance"
|
"github.com/TwiN/gatus/v4/config/maintenance"
|
||||||
|
"github.com/TwiN/gatus/v4/config/remote"
|
||||||
"github.com/TwiN/gatus/v4/config/ui"
|
"github.com/TwiN/gatus/v4/config/ui"
|
||||||
"github.com/TwiN/gatus/v4/config/web"
|
"github.com/TwiN/gatus/v4/config/web"
|
||||||
"github.com/TwiN/gatus/v4/core"
|
"github.com/TwiN/gatus/v4/core"
|
||||||
"github.com/TwiN/gatus/v4/security"
|
"github.com/TwiN/gatus/v4/security"
|
||||||
"github.com/TwiN/gatus/v4/storage"
|
"github.com/TwiN/gatus/v4/storage"
|
||||||
|
"github.com/TwiN/gatus/v4/util"
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -85,10 +87,24 @@ type Config struct {
|
|||||||
// Maintenance is the configuration for creating a maintenance window in which no alerts are sent
|
// Maintenance is the configuration for creating a maintenance window in which no alerts are sent
|
||||||
Maintenance *maintenance.Config `yaml:"maintenance,omitempty"`
|
Maintenance *maintenance.Config `yaml:"maintenance,omitempty"`
|
||||||
|
|
||||||
|
// Remote is the configuration for remote Gatus instances
|
||||||
|
// WARNING: This is in ALPHA and may change or be completely removed in the future
|
||||||
|
Remote *remote.Config `yaml:"remote,omitempty"`
|
||||||
|
|
||||||
filePath string // path to the file from which config was loaded from
|
filePath string // path to the file from which config was loaded from
|
||||||
lastFileModTime time.Time // last modification time
|
lastFileModTime time.Time // last modification time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (config *Config) GetEndpointByKey(key string) *core.Endpoint {
|
||||||
|
for i := 0; i < len(config.Endpoints); i++ {
|
||||||
|
ep := config.Endpoints[i]
|
||||||
|
if util.ConvertGroupAndEndpointNameToKey(ep.Group, ep.Name) == key {
|
||||||
|
return ep
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// HasLoadedConfigurationFileBeenModified returns whether the file that the
|
// HasLoadedConfigurationFileBeenModified returns whether the file that the
|
||||||
// configuration has been loaded from has been modified since it was last read
|
// configuration has been loaded from has been modified since it was last read
|
||||||
func (config Config) HasLoadedConfigurationFileBeenModified() bool {
|
func (config Config) HasLoadedConfigurationFileBeenModified() bool {
|
||||||
@@ -185,10 +201,22 @@ func parseAndValidateConfigBytes(yamlBytes []byte) (config *Config, err error) {
|
|||||||
if err := validateStorageConfig(config); err != nil {
|
if err := validateStorageConfig(config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := validateRemoteConfig(config); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateRemoteConfig(config *Config) error {
|
||||||
|
if config.Remote != nil {
|
||||||
|
if err := config.Remote.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func validateStorageConfig(config *Config) error {
|
func validateStorageConfig(config *Config) error {
|
||||||
if config.Storage == nil {
|
if config.Storage == nil {
|
||||||
config.Storage = &storage.Config{
|
config.Storage = &storage.Config{
|
||||||
@@ -274,6 +302,7 @@ func validateAlertingConfig(alertingConfig *alerting.Config, endpoints []*core.E
|
|||||||
alert.TypeCustom,
|
alert.TypeCustom,
|
||||||
alert.TypeDiscord,
|
alert.TypeDiscord,
|
||||||
alert.TypeEmail,
|
alert.TypeEmail,
|
||||||
|
alert.TypeMatrix,
|
||||||
alert.TypeMattermost,
|
alert.TypeMattermost,
|
||||||
alert.TypeMessagebird,
|
alert.TypeMessagebird,
|
||||||
alert.TypeOpsgenie,
|
alert.TypeOpsgenie,
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package remote
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/client"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NOTICE: This is an experimental alpha feature and may be updated/removed in future versions.
|
||||||
|
// For more information, see https://github.com/TwiN/gatus/issues/64
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
// Instances is a list of remote instances to retrieve endpoint statuses from.
|
||||||
|
Instances []Instance `yaml:"instances,omitempty"`
|
||||||
|
|
||||||
|
// ClientConfig is the configuration of the client used to communicate with the provider's target
|
||||||
|
ClientConfig *client.Config `yaml:"client,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Instance struct {
|
||||||
|
EndpointPrefix string `yaml:"endpoint-prefix"`
|
||||||
|
URL string `yaml:"url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) ValidateAndSetDefaults() error {
|
||||||
|
if c.ClientConfig == nil {
|
||||||
|
c.ClientConfig = client.GetDefaultConfig()
|
||||||
|
} else {
|
||||||
|
if err := c.ClientConfig.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(c.Instances) > 0 {
|
||||||
|
log.Println("WARNING: Your configuration is using 'remote', which is in alpha and may be updated/removed in future versions.")
|
||||||
|
log.Println("WARNING: See https://github.com/TwiN/gatus/issues/64 for more information")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -8,10 +8,9 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/config"
|
||||||
"github.com/TwiN/gatus/v4/config/ui"
|
"github.com/TwiN/gatus/v4/config/ui"
|
||||||
"github.com/TwiN/gatus/v4/config/web"
|
|
||||||
"github.com/TwiN/gatus/v4/controller/handler"
|
"github.com/TwiN/gatus/v4/controller/handler"
|
||||||
"github.com/TwiN/gatus/v4/security"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -21,19 +20,19 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Handle creates the router and starts the server
|
// Handle creates the router and starts the server
|
||||||
func Handle(securityConfig *security.Config, webConfig *web.Config, uiConfig *ui.Config, enableMetrics bool) {
|
func Handle(cfg *config.Config) {
|
||||||
var router http.Handler = handler.CreateRouter(ui.StaticFolder, securityConfig, uiConfig, enableMetrics)
|
var router http.Handler = handler.CreateRouter(ui.StaticFolder, cfg)
|
||||||
if os.Getenv("ENVIRONMENT") == "dev" {
|
if os.Getenv("ENVIRONMENT") == "dev" {
|
||||||
router = handler.DevelopmentCORS(router)
|
router = handler.DevelopmentCORS(router)
|
||||||
}
|
}
|
||||||
server = &http.Server{
|
server = &http.Server{
|
||||||
Addr: fmt.Sprintf("%s:%d", webConfig.Address, webConfig.Port),
|
Addr: fmt.Sprintf("%s:%d", cfg.Web.Address, cfg.Web.Port),
|
||||||
Handler: router,
|
Handler: router,
|
||||||
ReadTimeout: 15 * time.Second,
|
ReadTimeout: 15 * time.Second,
|
||||||
WriteTimeout: 15 * time.Second,
|
WriteTimeout: 15 * time.Second,
|
||||||
IdleTimeout: 15 * time.Second,
|
IdleTimeout: 15 * time.Second,
|
||||||
}
|
}
|
||||||
log.Println("[controller][Handle] Listening on " + webConfig.SocketAddress())
|
log.Println("[controller][Handle] Listening on " + cfg.Web.SocketAddress())
|
||||||
if os.Getenv("ROUTER_TEST") == "true" {
|
if os.Getenv("ROUTER_TEST") == "true" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func TestHandle(t *testing.T) {
|
|||||||
_ = os.Setenv("ROUTER_TEST", "true")
|
_ = os.Setenv("ROUTER_TEST", "true")
|
||||||
_ = os.Setenv("ENVIRONMENT", "dev")
|
_ = os.Setenv("ENVIRONMENT", "dev")
|
||||||
defer os.Clearenv()
|
defer os.Clearenv()
|
||||||
Handle(cfg.Security, cfg.Web, cfg.UI, cfg.Metrics)
|
Handle(cfg)
|
||||||
defer Shutdown()
|
defer Shutdown()
|
||||||
request, _ := http.NewRequest("GET", "/health", http.NoBody)
|
request, _ := http.NewRequest("GET", "/health", http.NoBody)
|
||||||
responseRecorder := httptest.NewRecorder()
|
responseRecorder := httptest.NewRecorder()
|
||||||
|
|||||||
+46
-43
@@ -7,6 +7,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/config"
|
||||||
"github.com/TwiN/gatus/v4/storage/store"
|
"github.com/TwiN/gatus/v4/storage/store"
|
||||||
"github.com/TwiN/gatus/v4/storage/store/common"
|
"github.com/TwiN/gatus/v4/storage/store/common"
|
||||||
"github.com/TwiN/gatus/v4/storage/store/common/paging"
|
"github.com/TwiN/gatus/v4/storage/store/common/paging"
|
||||||
@@ -28,6 +29,10 @@ const (
|
|||||||
HealthStatusUnknown = "?"
|
HealthStatusUnknown = "?"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
badgeColors = []string{badgeColorHexAwesome, badgeColorHexGreat, badgeColorHexGood, badgeColorHexPassable, badgeColorHexBad}
|
||||||
|
)
|
||||||
|
|
||||||
// UptimeBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
// UptimeBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
||||||
//
|
//
|
||||||
// Valid values for {duration}: 7d, 24h, 1h
|
// Valid values for {duration}: 7d, 24h, 1h
|
||||||
@@ -68,38 +73,40 @@ func UptimeBadge(writer http.ResponseWriter, request *http.Request) {
|
|||||||
// ResponseTimeBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
// ResponseTimeBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
||||||
//
|
//
|
||||||
// Valid values for {duration}: 7d, 24h, 1h
|
// Valid values for {duration}: 7d, 24h, 1h
|
||||||
func ResponseTimeBadge(writer http.ResponseWriter, request *http.Request) {
|
func ResponseTimeBadge(config *config.Config) http.HandlerFunc {
|
||||||
variables := mux.Vars(request)
|
return func(writer http.ResponseWriter, request *http.Request) {
|
||||||
duration := variables["duration"]
|
variables := mux.Vars(request)
|
||||||
var from time.Time
|
duration := variables["duration"]
|
||||||
switch duration {
|
var from time.Time
|
||||||
case "7d":
|
switch duration {
|
||||||
from = time.Now().Add(-7 * 24 * time.Hour)
|
case "7d":
|
||||||
case "24h":
|
from = time.Now().Add(-7 * 24 * time.Hour)
|
||||||
from = time.Now().Add(-24 * time.Hour)
|
case "24h":
|
||||||
case "1h":
|
from = time.Now().Add(-24 * time.Hour)
|
||||||
from = time.Now().Add(-2 * time.Hour) // Because response time metrics are stored by hour, we have to cheat a little
|
case "1h":
|
||||||
default:
|
from = time.Now().Add(-2 * time.Hour) // Because response time metrics are stored by hour, we have to cheat a little
|
||||||
http.Error(writer, "Durations supported: 7d, 24h, 1h", http.StatusBadRequest)
|
default:
|
||||||
return
|
http.Error(writer, "Durations supported: 7d, 24h, 1h", http.StatusBadRequest)
|
||||||
}
|
return
|
||||||
key := variables["key"]
|
|
||||||
averageResponseTime, err := store.Get().GetAverageResponseTimeByKey(key, from, time.Now())
|
|
||||||
if err != nil {
|
|
||||||
if err == common.ErrEndpointNotFound {
|
|
||||||
http.Error(writer, err.Error(), http.StatusNotFound)
|
|
||||||
} else if err == common.ErrInvalidTimeRange {
|
|
||||||
http.Error(writer, err.Error(), http.StatusBadRequest)
|
|
||||||
} else {
|
|
||||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
|
||||||
}
|
}
|
||||||
return
|
key := variables["key"]
|
||||||
|
averageResponseTime, err := store.Get().GetAverageResponseTimeByKey(key, from, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
if err == common.ErrEndpointNotFound {
|
||||||
|
http.Error(writer, err.Error(), http.StatusNotFound)
|
||||||
|
} else if err == common.ErrInvalidTimeRange {
|
||||||
|
http.Error(writer, err.Error(), http.StatusBadRequest)
|
||||||
|
} else {
|
||||||
|
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writer.Header().Set("Content-Type", "image/svg+xml")
|
||||||
|
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||||
|
writer.Header().Set("Expires", "0")
|
||||||
|
writer.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = writer.Write(generateResponseTimeBadgeSVG(duration, averageResponseTime, key, config))
|
||||||
}
|
}
|
||||||
writer.Header().Set("Content-Type", "image/svg+xml")
|
|
||||||
writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
||||||
writer.Header().Set("Expires", "0")
|
|
||||||
writer.WriteHeader(http.StatusOK)
|
|
||||||
_, _ = writer.Write(generateResponseTimeBadgeSVG(duration, averageResponseTime))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// HealthBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
// HealthBadge handles the automatic generation of badge based on the group name and endpoint name passed.
|
||||||
@@ -199,7 +206,7 @@ func getBadgeColorFromUptime(uptime float64) string {
|
|||||||
return badgeColorHexVeryBad
|
return badgeColorHexVeryBad
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateResponseTimeBadgeSVG(duration string, averageResponseTime int) []byte {
|
func generateResponseTimeBadgeSVG(duration string, averageResponseTime int, key string, cfg *config.Config) []byte {
|
||||||
var labelWidth, valueWidth int
|
var labelWidth, valueWidth int
|
||||||
switch duration {
|
switch duration {
|
||||||
case "7d":
|
case "7d":
|
||||||
@@ -210,7 +217,7 @@ func generateResponseTimeBadgeSVG(duration string, averageResponseTime int) []by
|
|||||||
labelWidth = 105
|
labelWidth = 105
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
color := getBadgeColorFromResponseTime(averageResponseTime)
|
color := getBadgeColorFromResponseTime(averageResponseTime, key, cfg)
|
||||||
sanitizedValue := strconv.Itoa(averageResponseTime) + "ms"
|
sanitizedValue := strconv.Itoa(averageResponseTime) + "ms"
|
||||||
valueWidth = len(sanitizedValue) * 11
|
valueWidth = len(sanitizedValue) * 11
|
||||||
width := labelWidth + valueWidth
|
width := labelWidth + valueWidth
|
||||||
@@ -247,17 +254,13 @@ func generateResponseTimeBadgeSVG(duration string, averageResponseTime int) []by
|
|||||||
return svg
|
return svg
|
||||||
}
|
}
|
||||||
|
|
||||||
func getBadgeColorFromResponseTime(responseTime int) string {
|
func getBadgeColorFromResponseTime(responseTime int, key string, cfg *config.Config) string {
|
||||||
if responseTime <= 50 {
|
endpoint := cfg.GetEndpointByKey(key)
|
||||||
return badgeColorHexAwesome
|
// the threshold config requires 5 values, so we can be sure it's set here
|
||||||
} else if responseTime <= 200 {
|
for i := 0; i < 5; i++ {
|
||||||
return badgeColorHexGreat
|
if responseTime <= endpoint.UIConfig.Badge.ResponseTime.Thresholds[i] {
|
||||||
} else if responseTime <= 300 {
|
return badgeColors[i]
|
||||||
return badgeColorHexGood
|
}
|
||||||
} else if responseTime <= 500 {
|
|
||||||
return badgeColorHexPassable
|
|
||||||
} else if responseTime <= 750 {
|
|
||||||
return badgeColorHexBad
|
|
||||||
}
|
}
|
||||||
return badgeColorHexVeryBad
|
return badgeColorHexVeryBad
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
|
|
||||||
"github.com/TwiN/gatus/v4/config"
|
"github.com/TwiN/gatus/v4/config"
|
||||||
"github.com/TwiN/gatus/v4/core"
|
"github.com/TwiN/gatus/v4/core"
|
||||||
|
"github.com/TwiN/gatus/v4/core/ui"
|
||||||
"github.com/TwiN/gatus/v4/storage/store"
|
"github.com/TwiN/gatus/v4/storage/store"
|
||||||
"github.com/TwiN/gatus/v4/watchdog"
|
"github.com/TwiN/gatus/v4/watchdog"
|
||||||
)
|
)
|
||||||
@@ -29,9 +30,39 @@ func TestBadge(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
testSuccessfulResult = core.Result{
|
||||||
|
Hostname: "example.org",
|
||||||
|
IP: "127.0.0.1",
|
||||||
|
HTTPStatus: 200,
|
||||||
|
Errors: nil,
|
||||||
|
Connected: true,
|
||||||
|
Success: true,
|
||||||
|
Timestamp: timestamp,
|
||||||
|
Duration: 150 * time.Millisecond,
|
||||||
|
CertificateExpiration: 10 * time.Hour,
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{
|
||||||
|
Condition: "[STATUS] == 200",
|
||||||
|
Success: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Condition: "[RESPONSE_TIME] < 500",
|
||||||
|
Success: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Condition: "[CERTIFICATE_EXPIRATION] < 72h",
|
||||||
|
Success: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.Endpoints[0].UIConfig = ui.GetDefaultConfig()
|
||||||
|
cfg.Endpoints[1].UIConfig = ui.GetDefaultConfig()
|
||||||
|
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Connected: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Connected: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Connected: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Connected: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg)
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
Path string
|
Path string
|
||||||
@@ -181,55 +212,128 @@ func TestGetBadgeColorFromUptime(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestGetBadgeColorFromResponseTime(t *testing.T) {
|
func TestGetBadgeColorFromResponseTime(t *testing.T) {
|
||||||
|
defer store.Get().Clear()
|
||||||
|
defer cache.Clear()
|
||||||
|
|
||||||
|
var (
|
||||||
|
firstCondition = core.Condition("[STATUS] == 200")
|
||||||
|
secondCondition = core.Condition("[RESPONSE_TIME] < 500")
|
||||||
|
thirdCondition = core.Condition("[CERTIFICATE_EXPIRATION] < 72h")
|
||||||
|
)
|
||||||
|
|
||||||
|
firstTestEndpoint := core.Endpoint{
|
||||||
|
Name: "a",
|
||||||
|
URL: "https://example.org/what/ever",
|
||||||
|
Method: "GET",
|
||||||
|
Body: "body",
|
||||||
|
Interval: 30 * time.Second,
|
||||||
|
Conditions: []core.Condition{firstCondition, secondCondition, thirdCondition},
|
||||||
|
Alerts: nil,
|
||||||
|
NumberOfFailuresInARow: 0,
|
||||||
|
NumberOfSuccessesInARow: 0,
|
||||||
|
UIConfig: ui.GetDefaultConfig(),
|
||||||
|
}
|
||||||
|
secondTestEndpoint := core.Endpoint{
|
||||||
|
Name: "b",
|
||||||
|
URL: "https://example.org/what/ever",
|
||||||
|
Method: "GET",
|
||||||
|
Body: "body",
|
||||||
|
Interval: 30 * time.Second,
|
||||||
|
Conditions: []core.Condition{firstCondition, secondCondition, thirdCondition},
|
||||||
|
Alerts: nil,
|
||||||
|
NumberOfFailuresInARow: 0,
|
||||||
|
NumberOfSuccessesInARow: 0,
|
||||||
|
UIConfig: &ui.Config{
|
||||||
|
Badge: &ui.Badge{
|
||||||
|
ResponseTime: &ui.ResponseTime{
|
||||||
|
Thresholds: []int{100, 500, 1000, 2000, 3000},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cfg := &config.Config{
|
||||||
|
Metrics: true,
|
||||||
|
Endpoints: []*core.Endpoint{&firstTestEndpoint, &secondTestEndpoint},
|
||||||
|
}
|
||||||
|
|
||||||
|
store.Get().Insert(&firstTestEndpoint, &testSuccessfulResult)
|
||||||
|
store.Get().Insert(&secondTestEndpoint, &testSuccessfulResult)
|
||||||
|
|
||||||
scenarios := []struct {
|
scenarios := []struct {
|
||||||
|
Key string
|
||||||
ResponseTime int
|
ResponseTime int
|
||||||
ExpectedColor string
|
ExpectedColor string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 10,
|
ResponseTime: 10,
|
||||||
ExpectedColor: badgeColorHexAwesome,
|
ExpectedColor: badgeColorHexAwesome,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 50,
|
ResponseTime: 50,
|
||||||
ExpectedColor: badgeColorHexAwesome,
|
ExpectedColor: badgeColorHexAwesome,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 75,
|
ResponseTime: 75,
|
||||||
ExpectedColor: badgeColorHexGreat,
|
ExpectedColor: badgeColorHexGreat,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 150,
|
ResponseTime: 150,
|
||||||
ExpectedColor: badgeColorHexGreat,
|
ExpectedColor: badgeColorHexGreat,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 201,
|
ResponseTime: 201,
|
||||||
ExpectedColor: badgeColorHexGood,
|
ExpectedColor: badgeColorHexGood,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 300,
|
ResponseTime: 300,
|
||||||
ExpectedColor: badgeColorHexGood,
|
ExpectedColor: badgeColorHexGood,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 301,
|
ResponseTime: 301,
|
||||||
ExpectedColor: badgeColorHexPassable,
|
ExpectedColor: badgeColorHexPassable,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 450,
|
ResponseTime: 450,
|
||||||
ExpectedColor: badgeColorHexPassable,
|
ExpectedColor: badgeColorHexPassable,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 700,
|
ResponseTime: 700,
|
||||||
ExpectedColor: badgeColorHexBad,
|
ExpectedColor: badgeColorHexBad,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
Key: firstTestEndpoint.Key(),
|
||||||
ResponseTime: 1500,
|
ResponseTime: 1500,
|
||||||
ExpectedColor: badgeColorHexVeryBad,
|
ExpectedColor: badgeColorHexVeryBad,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Key: secondTestEndpoint.Key(),
|
||||||
|
ResponseTime: 50,
|
||||||
|
ExpectedColor: badgeColorHexAwesome,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Key: secondTestEndpoint.Key(),
|
||||||
|
ResponseTime: 1500,
|
||||||
|
ExpectedColor: badgeColorHexPassable,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Key: secondTestEndpoint.Key(),
|
||||||
|
ResponseTime: 2222,
|
||||||
|
ExpectedColor: badgeColorHexBad,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
t.Run("response-time-"+strconv.Itoa(scenario.ResponseTime), func(t *testing.T) {
|
t.Run(scenario.Key+"-response-time-"+strconv.Itoa(scenario.ResponseTime), func(t *testing.T) {
|
||||||
if getBadgeColorFromResponseTime(scenario.ResponseTime) != scenario.ExpectedColor {
|
if getBadgeColorFromResponseTime(scenario.ResponseTime, scenario.Key, cfg) != scenario.ExpectedColor {
|
||||||
t.Errorf("expected %s from %d, got %v", scenario.ExpectedColor, scenario.ResponseTime, getBadgeColorFromResponseTime(scenario.ResponseTime))
|
t.Errorf("expected %s from %d, got %v", scenario.ExpectedColor, scenario.ResponseTime, getBadgeColorFromResponseTime(scenario.ResponseTime, scenario.Key, cfg))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestResponseTimeChart(t *testing.T) {
|
|||||||
}
|
}
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg)
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
Path string
|
Path string
|
||||||
|
|||||||
@@ -5,11 +5,16 @@ import (
|
|||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/client"
|
||||||
|
"github.com/TwiN/gatus/v4/config"
|
||||||
|
"github.com/TwiN/gatus/v4/config/remote"
|
||||||
|
"github.com/TwiN/gatus/v4/core"
|
||||||
"github.com/TwiN/gatus/v4/storage/store"
|
"github.com/TwiN/gatus/v4/storage/store"
|
||||||
"github.com/TwiN/gatus/v4/storage/store/common"
|
"github.com/TwiN/gatus/v4/storage/store/common"
|
||||||
"github.com/TwiN/gatus/v4/storage/store/common/paging"
|
"github.com/TwiN/gatus/v4/storage/store/common/paging"
|
||||||
@@ -28,48 +33,89 @@ var (
|
|||||||
// EndpointStatuses handles requests to retrieve all EndpointStatus
|
// EndpointStatuses handles requests to retrieve all EndpointStatus
|
||||||
// Due to the size of the response, this function leverages a cache.
|
// Due to the size of the response, this function leverages a cache.
|
||||||
// Must not be wrapped by GzipHandler
|
// Must not be wrapped by GzipHandler
|
||||||
func EndpointStatuses(writer http.ResponseWriter, r *http.Request) {
|
func EndpointStatuses(cfg *config.Config) http.HandlerFunc {
|
||||||
page, pageSize := extractPageAndPageSizeFromRequest(r)
|
return func(writer http.ResponseWriter, r *http.Request) {
|
||||||
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
|
page, pageSize := extractPageAndPageSizeFromRequest(r)
|
||||||
var exists bool
|
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
|
||||||
var value interface{}
|
var exists bool
|
||||||
if gzipped {
|
var value interface{}
|
||||||
writer.Header().Set("Content-Encoding", "gzip")
|
|
||||||
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize))
|
|
||||||
} else {
|
|
||||||
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize))
|
|
||||||
}
|
|
||||||
var data []byte
|
|
||||||
if !exists {
|
|
||||||
var err error
|
|
||||||
buffer := &bytes.Buffer{}
|
|
||||||
gzipWriter := gzip.NewWriter(buffer)
|
|
||||||
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("[handler][EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
|
|
||||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data, err = json.Marshal(endpointStatuses)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("[handler][EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
|
|
||||||
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_, _ = gzipWriter.Write(data)
|
|
||||||
_ = gzipWriter.Close()
|
|
||||||
gzippedData := buffer.Bytes()
|
|
||||||
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
|
|
||||||
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize), gzippedData, cacheTTL)
|
|
||||||
if gzipped {
|
if gzipped {
|
||||||
data = gzippedData
|
writer.Header().Set("Content-Encoding", "gzip")
|
||||||
|
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize))
|
||||||
|
} else {
|
||||||
|
value, exists = cache.Get(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize))
|
||||||
}
|
}
|
||||||
} else {
|
var data []byte
|
||||||
data = value.([]byte)
|
if !exists {
|
||||||
|
var err error
|
||||||
|
buffer := &bytes.Buffer{}
|
||||||
|
gzipWriter := gzip.NewWriter(buffer)
|
||||||
|
endpointStatuses, err := store.Get().GetAllEndpointStatuses(paging.NewEndpointStatusParams().WithResults(page, pageSize))
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[handler][EndpointStatuses] Failed to retrieve endpoint statuses: %s", err.Error())
|
||||||
|
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// ALPHA: Retrieve endpoint statuses from remote instances
|
||||||
|
if endpointStatusesFromRemote, err := getEndpointStatusesFromRemoteInstances(cfg.Remote); err != nil {
|
||||||
|
log.Printf("[handler][EndpointStatuses] Silently failed to retrieve endpoint statuses from remote: %s", err.Error())
|
||||||
|
} else if endpointStatusesFromRemote != nil {
|
||||||
|
endpointStatuses = append(endpointStatuses, endpointStatusesFromRemote...)
|
||||||
|
}
|
||||||
|
// Marshal endpoint statuses to JSON
|
||||||
|
data, err = json.Marshal(endpointStatuses)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[handler][EndpointStatuses] Unable to marshal object to JSON: %s", err.Error())
|
||||||
|
http.Error(writer, "unable to marshal object to JSON", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = gzipWriter.Write(data)
|
||||||
|
_ = gzipWriter.Close()
|
||||||
|
gzippedData := buffer.Bytes()
|
||||||
|
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d", page, pageSize), data, cacheTTL)
|
||||||
|
cache.SetWithTTL(fmt.Sprintf("endpoint-status-%d-%d-gzipped", page, pageSize), gzippedData, cacheTTL)
|
||||||
|
if gzipped {
|
||||||
|
data = gzippedData
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
data = value.([]byte)
|
||||||
|
}
|
||||||
|
writer.Header().Add("Content-Type", "application/json")
|
||||||
|
writer.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = writer.Write(data)
|
||||||
}
|
}
|
||||||
writer.Header().Add("Content-Type", "application/json")
|
}
|
||||||
writer.WriteHeader(http.StatusOK)
|
|
||||||
_, _ = writer.Write(data)
|
func getEndpointStatusesFromRemoteInstances(remoteConfig *remote.Config) ([]*core.EndpointStatus, error) {
|
||||||
|
if remoteConfig == nil || len(remoteConfig.Instances) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var endpointStatusesFromAllRemotes []*core.EndpointStatus
|
||||||
|
httpClient := client.GetHTTPClient(remoteConfig.ClientConfig)
|
||||||
|
for _, instance := range remoteConfig.Instances {
|
||||||
|
response, err := httpClient.Get(instance.URL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(response.Body)
|
||||||
|
if err != nil {
|
||||||
|
_ = response.Body.Close()
|
||||||
|
log.Printf("[handler][getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var endpointStatuses []*core.EndpointStatus
|
||||||
|
if err = json.Unmarshal(body, &endpointStatuses); err != nil {
|
||||||
|
_ = response.Body.Close()
|
||||||
|
log.Printf("[handler][getEndpointStatusesFromRemoteInstances] Silently failed to retrieve endpoint statuses from %s: %s", instance.URL, err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_ = response.Body.Close()
|
||||||
|
for _, endpointStatus := range endpointStatuses {
|
||||||
|
endpointStatus.Name = instance.EndpointPrefix + endpointStatus.Name
|
||||||
|
}
|
||||||
|
endpointStatusesFromAllRemotes = append(endpointStatusesFromAllRemotes, endpointStatuses...)
|
||||||
|
}
|
||||||
|
return endpointStatusesFromAllRemotes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// EndpointStatus retrieves a single core.EndpointStatus by group and endpoint name
|
// EndpointStatus retrieves a single core.EndpointStatus by group and endpoint name
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ func TestEndpointStatus(t *testing.T) {
|
|||||||
}
|
}
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg)
|
||||||
|
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
@@ -153,7 +153,7 @@ func TestEndpointStatuses(t *testing.T) {
|
|||||||
// Can't be bothered dealing with timezone issues on the worker that runs the automated tests
|
// Can't be bothered dealing with timezone issues on the worker that runs the automated tests
|
||||||
firstResult.Timestamp = time.Time{}
|
firstResult.Timestamp = time.Time{}
|
||||||
secondResult.Timestamp = time.Time{}
|
secondResult.Timestamp = time.Time{}
|
||||||
router := CreateRouter("../../web/static", nil, nil, false)
|
router := CreateRouter("../../web/static", &config.Config{Metrics: true})
|
||||||
|
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestFavIcon(t *testing.T) {
|
func TestFavIcon(t *testing.T) {
|
||||||
router := CreateRouter("../../web/static", nil, nil, false)
|
router := CreateRouter("../../web/static", &config.Config{})
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
Path string
|
Path string
|
||||||
|
|||||||
@@ -3,43 +3,42 @@ package handler
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/TwiN/gatus/v4/config/ui"
|
"github.com/TwiN/gatus/v4/config"
|
||||||
"github.com/TwiN/gatus/v4/security"
|
|
||||||
"github.com/TwiN/health"
|
"github.com/TwiN/health"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateRouter(staticFolder string, securityConfig *security.Config, uiConfig *ui.Config, enabledMetrics bool) *mux.Router {
|
func CreateRouter(staticFolder string, cfg *config.Config) *mux.Router {
|
||||||
router := mux.NewRouter()
|
router := mux.NewRouter()
|
||||||
if enabledMetrics {
|
if cfg.Metrics {
|
||||||
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
||||||
}
|
}
|
||||||
api := router.PathPrefix("/api").Subrouter()
|
api := router.PathPrefix("/api").Subrouter()
|
||||||
protected := api.PathPrefix("/").Subrouter()
|
protected := api.PathPrefix("/").Subrouter()
|
||||||
unprotected := api.PathPrefix("/").Subrouter()
|
unprotected := api.PathPrefix("/").Subrouter()
|
||||||
if securityConfig != nil {
|
if cfg.Security != nil {
|
||||||
if err := securityConfig.RegisterHandlers(router); err != nil {
|
if err := cfg.Security.RegisterHandlers(router); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
if err := securityConfig.ApplySecurityMiddleware(protected); err != nil {
|
if err := cfg.Security.ApplySecurityMiddleware(protected); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Endpoints
|
// Endpoints
|
||||||
unprotected.Handle("/v1/config", ConfigHandler{securityConfig: securityConfig}).Methods("GET")
|
unprotected.Handle("/v1/config", ConfigHandler{securityConfig: cfg.Security}).Methods("GET")
|
||||||
protected.HandleFunc("/v1/endpoints/statuses", EndpointStatuses).Methods("GET") // No GzipHandler for this one, because we cache the content as Gzipped already
|
protected.HandleFunc("/v1/endpoints/statuses", EndpointStatuses(cfg)).Methods("GET") // No GzipHandler for this one, because we cache the content as Gzipped already
|
||||||
protected.HandleFunc("/v1/endpoints/{key}/statuses", GzipHandlerFunc(EndpointStatus)).Methods("GET")
|
protected.HandleFunc("/v1/endpoints/{key}/statuses", GzipHandlerFunc(EndpointStatus)).Methods("GET")
|
||||||
unprotected.HandleFunc("/v1/endpoints/{key}/health/badge.svg", HealthBadge).Methods("GET")
|
unprotected.HandleFunc("/v1/endpoints/{key}/health/badge.svg", HealthBadge).Methods("GET")
|
||||||
unprotected.HandleFunc("/v1/endpoints/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET")
|
unprotected.HandleFunc("/v1/endpoints/{key}/uptimes/{duration}/badge.svg", UptimeBadge).Methods("GET")
|
||||||
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge).Methods("GET")
|
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/badge.svg", ResponseTimeBadge(cfg)).Methods("GET")
|
||||||
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET")
|
unprotected.HandleFunc("/v1/endpoints/{key}/response-times/{duration}/chart.svg", ResponseTimeChart).Methods("GET")
|
||||||
// Misc
|
// Misc
|
||||||
router.Handle("/health", health.Handler().WithJSON(true)).Methods("GET")
|
router.Handle("/health", health.Handler().WithJSON(true)).Methods("GET")
|
||||||
router.HandleFunc("/favicon.ico", FavIcon(staticFolder)).Methods("GET")
|
router.HandleFunc("/favicon.ico", FavIcon(staticFolder)).Methods("GET")
|
||||||
// SPA
|
// SPA
|
||||||
router.HandleFunc("/endpoints/{name}", SinglePageApplication(staticFolder, uiConfig)).Methods("GET")
|
router.HandleFunc("/endpoints/{name}", SinglePageApplication(staticFolder, cfg.UI)).Methods("GET")
|
||||||
router.HandleFunc("/", SinglePageApplication(staticFolder, uiConfig)).Methods("GET")
|
router.HandleFunc("/", SinglePageApplication(staticFolder, cfg.UI)).Methods("GET")
|
||||||
// Everything else falls back on static content
|
// Everything else falls back on static content
|
||||||
router.PathPrefix("/").Handler(GzipHandler(http.FileServer(http.Dir(staticFolder))))
|
router.PathPrefix("/").Handler(GzipHandler(http.FileServer(http.Dir(staticFolder))))
|
||||||
return router
|
return router
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/TwiN/gatus/v4/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCreateRouter(t *testing.T) {
|
func TestCreateRouter(t *testing.T) {
|
||||||
router := CreateRouter("../../web/static", nil, nil, true)
|
router := CreateRouter("../../web/static", &config.Config{Metrics: true})
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
Path string
|
Path string
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestSinglePageApplication(t *testing.T) {
|
|||||||
}
|
}
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
watchdog.UpdateEndpointStatuses(cfg.Endpoints[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
router := CreateRouter("../../web/static", cfg.Security, nil, cfg.Metrics)
|
router := CreateRouter("../../web/static", cfg)
|
||||||
type Scenario struct {
|
type Scenario struct {
|
||||||
Name string
|
Name string
|
||||||
Path string
|
Path string
|
||||||
|
|||||||
@@ -145,6 +145,10 @@ func (endpoint *Endpoint) ValidateAndSetDefaults() error {
|
|||||||
}
|
}
|
||||||
if endpoint.UIConfig == nil {
|
if endpoint.UIConfig == nil {
|
||||||
endpoint.UIConfig = ui.GetDefaultConfig()
|
endpoint.UIConfig = ui.GetDefaultConfig()
|
||||||
|
} else {
|
||||||
|
if err := endpoint.UIConfig.ValidateAndSetDefaults(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if endpoint.Interval == 0 {
|
if endpoint.Interval == 0 {
|
||||||
endpoint.Interval = 1 * time.Minute
|
endpoint.Interval = 1 * time.Minute
|
||||||
|
|||||||
@@ -1,13 +1,48 @@
|
|||||||
package ui
|
package ui
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
// Config is the UI configuration for core.Endpoint
|
// Config is the UI configuration for core.Endpoint
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// HideHostname whether to hide the hostname in the Result
|
// HideHostname whether to hide the hostname in the Result
|
||||||
HideHostname bool `yaml:"hide-hostname"`
|
HideHostname bool `yaml:"hide-hostname"`
|
||||||
|
|
||||||
// HideURL whether to ensure the URL is not displayed in the results. Useful if the URL contains a token.
|
// HideURL whether to ensure the URL is not displayed in the results. Useful if the URL contains a token.
|
||||||
HideURL bool `yaml:"hide-url"`
|
HideURL bool `yaml:"hide-url"`
|
||||||
|
|
||||||
// DontResolveFailedConditions whether to resolve failed conditions in the Result for display in the UI
|
// DontResolveFailedConditions whether to resolve failed conditions in the Result for display in the UI
|
||||||
DontResolveFailedConditions bool `yaml:"dont-resolve-failed-conditions"`
|
DontResolveFailedConditions bool `yaml:"dont-resolve-failed-conditions"`
|
||||||
|
|
||||||
|
// Badge is the configuration for the badges generated
|
||||||
|
Badge *Badge `yaml:"badge"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Badge struct {
|
||||||
|
ResponseTime *ResponseTime `yaml:"response-time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResponseTime struct {
|
||||||
|
Thresholds []int `yaml:"thresholds"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidBadgeResponseTimeConfig = errors.New("invalid response time badge configuration: expected parameter 'response-time' to have 5 ascending numerical values")
|
||||||
|
)
|
||||||
|
|
||||||
|
func (config *Config) ValidateAndSetDefaults() error {
|
||||||
|
if config.Badge != nil {
|
||||||
|
if len(config.Badge.ResponseTime.Thresholds) != 5 {
|
||||||
|
return ErrInvalidBadgeResponseTimeConfig
|
||||||
|
}
|
||||||
|
for i := 4; i > 0; i-- {
|
||||||
|
if config.Badge.ResponseTime.Thresholds[i] < config.Badge.ResponseTime.Thresholds[i-1] {
|
||||||
|
return ErrInvalidBadgeResponseTimeConfig
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
config.Badge = GetDefaultConfig().Badge
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaultConfig retrieves the default UI configuration
|
// GetDefaultConfig retrieves the default UI configuration
|
||||||
@@ -16,5 +51,10 @@ func GetDefaultConfig() *Config {
|
|||||||
HideHostname: false,
|
HideHostname: false,
|
||||||
HideURL: false,
|
HideURL: false,
|
||||||
DontResolveFailedConditions: false,
|
DontResolveFailedConditions: false,
|
||||||
|
Badge: &Badge{
|
||||||
|
ResponseTime: &ResponseTime{
|
||||||
|
Thresholds: []int{50, 200, 300, 500, 750},
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@ go 1.18
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/TwiN/g8 v1.3.0
|
github.com/TwiN/g8 v1.3.0
|
||||||
github.com/TwiN/gocache/v2 v2.0.0
|
github.com/TwiN/gocache/v2 v2.1.0
|
||||||
github.com/TwiN/health v1.4.0
|
github.com/TwiN/health v1.4.0
|
||||||
github.com/coreos/go-oidc/v3 v3.1.0
|
github.com/coreos/go-oidc/v3 v3.1.0
|
||||||
github.com/go-ping/ping v0.0.0-20210911151512-381826476871
|
github.com/go-ping/ping v0.0.0-20210911151512-381826476871
|
||||||
|
|||||||
@@ -35,8 +35,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
|
|||||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||||
github.com/TwiN/g8 v1.3.0 h1:mNv3R35GhDn1gEV0BKMl1oupZ1tDtOWPTHUKu+W/k3U=
|
github.com/TwiN/g8 v1.3.0 h1:mNv3R35GhDn1gEV0BKMl1oupZ1tDtOWPTHUKu+W/k3U=
|
||||||
github.com/TwiN/g8 v1.3.0/go.mod h1:SiIdItS0agSUloFqdQQt/RObB2jGSq+nnE9WfFv3RIo=
|
github.com/TwiN/g8 v1.3.0/go.mod h1:SiIdItS0agSUloFqdQQt/RObB2jGSq+nnE9WfFv3RIo=
|
||||||
github.com/TwiN/gocache/v2 v2.0.0 h1:CPbDNKdSJpmBkh7aWcO7D3KK1yWaMlwX+3dsBPE8/so=
|
github.com/TwiN/gocache/v2 v2.1.0 h1:AJnSX7Sgz22fsO7rdXYQzMQ4zWpMjBKqk70ADeqtLDU=
|
||||||
github.com/TwiN/gocache/v2 v2.0.0/go.mod h1:j4MABVaia2Tp53ERWc/3l4YxkswtPjB2hQzmL/kD/VQ=
|
github.com/TwiN/gocache/v2 v2.1.0/go.mod h1:AKHAFZSwLLmoLm1a2siDOWmZ2RjIKqentRGfOFWkllY=
|
||||||
github.com/TwiN/health v1.4.0 h1:Ts7lb4ihYDpVEbFSGAhSEZTSwuDOADnwJLFngFl4xzw=
|
github.com/TwiN/health v1.4.0 h1:Ts7lb4ihYDpVEbFSGAhSEZTSwuDOADnwJLFngFl4xzw=
|
||||||
github.com/TwiN/health v1.4.0/go.mod h1:CSUh+ryfD2POS2vKtc/yO4IxgR58lKvQ0/8qnoPqPqs=
|
github.com/TwiN/health v1.4.0/go.mod h1:CSUh+ryfD2POS2vKtc/yO4IxgR58lKvQ0/8qnoPqPqs=
|
||||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func start(cfg *config.Config) {
|
func start(cfg *config.Config) {
|
||||||
go controller.Handle(cfg.Security, cfg.Web, cfg.UI, cfg.Metrics)
|
go controller.Handle(cfg)
|
||||||
watchdog.Monitor(cfg)
|
watchdog.Monitor(cfg)
|
||||||
go listenToConfigurationFileChanges(cfg)
|
go listenToConfigurationFileChanges(cfg)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,12 @@ type Config struct {
|
|||||||
// Type of store
|
// Type of store
|
||||||
// If blank, uses the default in-memory store
|
// If blank, uses the default in-memory store
|
||||||
Type Type `yaml:"type"`
|
Type Type `yaml:"type"`
|
||||||
|
|
||||||
|
// Caching is whether to enable caching.
|
||||||
|
// This is used to drastically decrease read latency by pre-emptively caching writes
|
||||||
|
// as they happen, also known as the write-through caching strategy.
|
||||||
|
// Does not apply if Config.Type is not TypePostgres or TypeSQLite.
|
||||||
|
Caching bool `yaml:"caching,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ValidateAndSetDefaults validates the configuration and sets the default values (if applicable)
|
// ValidateAndSetDefaults validates the configuration and sets the default values (if applicable)
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package memory
|
package memory
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/gob"
|
|
||||||
"sort"
|
"sort"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -13,14 +12,6 @@ import (
|
|||||||
"github.com/TwiN/gocache/v2"
|
"github.com/TwiN/gocache/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
|
||||||
gob.Register(&core.EndpointStatus{})
|
|
||||||
gob.Register(&core.HourlyUptimeStatistics{})
|
|
||||||
gob.Register(&core.Uptime{})
|
|
||||||
gob.Register(&core.Result{})
|
|
||||||
gob.Register(&core.Event{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store that leverages gocache
|
// Store that leverages gocache
|
||||||
type Store struct {
|
type Store struct {
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
@@ -32,7 +23,7 @@ type Store struct {
|
|||||||
//
|
//
|
||||||
// This store holds everything in memory, and if the file parameter is not blank,
|
// This store holds everything in memory, and if the file parameter is not blank,
|
||||||
// supports eventual persistence.
|
// supports eventual persistence.
|
||||||
func NewStore(file string) (*Store, error) {
|
func NewStore() (*Store, error) {
|
||||||
store := &Store{
|
store := &Store{
|
||||||
cache: gocache.NewCache().WithMaxSize(gocache.NoMaxSize),
|
cache: gocache.NewCache().WithMaxSize(gocache.NoMaxSize),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ var (
|
|||||||
// Note that are much more extensive tests in /storage/store/store_test.go.
|
// Note that are much more extensive tests in /storage/store/store_test.go.
|
||||||
// This test is simply an extra sanity check
|
// This test is simply an extra sanity check
|
||||||
func TestStore_SanityCheck(t *testing.T) {
|
func TestStore_SanityCheck(t *testing.T) {
|
||||||
store, _ := NewStore("")
|
store, _ := NewStore()
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
store.Insert(&testEndpoint, &testSuccessfulResult)
|
store.Insert(&testEndpoint, &testSuccessfulResult)
|
||||||
endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams())
|
endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams())
|
||||||
@@ -122,22 +122,14 @@ func TestStore_SanityCheck(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStore_Save(t *testing.T) {
|
func TestStore_Save(t *testing.T) {
|
||||||
files := []string{
|
store, err := NewStore()
|
||||||
"",
|
if err != nil {
|
||||||
t.TempDir() + "/test.db",
|
t.Fatal("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
for _, file := range files {
|
err = store.Save()
|
||||||
t.Run(file, func(t *testing.T) {
|
if err != nil {
|
||||||
store, err := NewStore(file)
|
t.Fatal("expected no error, got", err.Error())
|
||||||
if err != nil {
|
|
||||||
t.Fatal("expected no error, got", err.Error())
|
|
||||||
}
|
|
||||||
err = store.Save()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal("expected no error, got", err.Error())
|
|
||||||
}
|
|
||||||
store.Clear()
|
|
||||||
store.Close()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
store.Clear()
|
||||||
|
store.Close()
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v4/storage/store/common"
|
"github.com/TwiN/gatus/v4/storage/store/common"
|
||||||
"github.com/TwiN/gatus/v4/storage/store/common/paging"
|
"github.com/TwiN/gatus/v4/storage/store/common/paging"
|
||||||
"github.com/TwiN/gatus/v4/util"
|
"github.com/TwiN/gatus/v4/util"
|
||||||
|
"github.com/TwiN/gocache/v2"
|
||||||
_ "github.com/lib/pq"
|
_ "github.com/lib/pq"
|
||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
@@ -32,6 +33,8 @@ const (
|
|||||||
resultsCleanUpThreshold = common.MaximumNumberOfResults + 10 // Maximum number of results before triggering a clean up
|
resultsCleanUpThreshold = common.MaximumNumberOfResults + 10 // Maximum number of results before triggering a clean up
|
||||||
|
|
||||||
uptimeRetention = 7 * 24 * time.Hour
|
uptimeRetention = 7 * 24 * time.Hour
|
||||||
|
|
||||||
|
cacheTTL = 10 * time.Minute
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -49,10 +52,14 @@ type Store struct {
|
|||||||
driver, path string
|
driver, path string
|
||||||
|
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
|
|
||||||
|
// writeThroughCache is a cache used to drastically decrease read latency by pre-emptively
|
||||||
|
// caching writes as they happen. If nil, writes are not cached.
|
||||||
|
writeThroughCache *gocache.Cache
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewStore initializes the database and creates the schema if it doesn't already exist in the path specified
|
// NewStore initializes the database and creates the schema if it doesn't already exist in the path specified
|
||||||
func NewStore(driver, path string) (*Store, error) {
|
func NewStore(driver, path string, caching bool) (*Store, error) {
|
||||||
if len(driver) == 0 {
|
if len(driver) == 0 {
|
||||||
return nil, ErrDatabaseDriverNotSpecified
|
return nil, ErrDatabaseDriverNotSpecified
|
||||||
}
|
}
|
||||||
@@ -79,6 +86,9 @@ func NewStore(driver, path string) (*Store, error) {
|
|||||||
_ = store.db.Close()
|
_ = store.db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if caching {
|
||||||
|
store.writeThroughCache = gocache.NewCache().WithMaxSize(10000)
|
||||||
|
}
|
||||||
return store, nil
|
return store, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,6 +333,19 @@ func (s *Store) Insert(endpoint *core.Endpoint, result *core.Result) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if s.writeThroughCache != nil {
|
||||||
|
cacheKeysToRefresh := s.writeThroughCache.GetKeysByPattern(endpoint.Key()+"*", 0)
|
||||||
|
for _, cacheKey := range cacheKeysToRefresh {
|
||||||
|
s.writeThroughCache.Delete(cacheKey)
|
||||||
|
endpointKey, params, err := extractKeyAndParamsFromCacheKey(cacheKey)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[sql][Insert] Silently deleting cache key %s instead of refreshing due to error: %s", cacheKey, err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Retrieve the endpoint status by key, which will in turn refresh the cache
|
||||||
|
_, _ = s.getEndpointStatusByKey(tx, endpointKey, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
if err = tx.Commit(); err != nil {
|
if err = tx.Commit(); err != nil {
|
||||||
_ = tx.Rollback()
|
_ = tx.Rollback()
|
||||||
}
|
}
|
||||||
@@ -350,6 +373,11 @@ func (s *Store) DeleteAllEndpointStatusesNotInKeys(keys []string) int {
|
|||||||
log.Printf("[sql][DeleteAllEndpointStatusesNotInKeys] Failed to delete rows that do not belong to any of keys=%v: %s", keys, err.Error())
|
log.Printf("[sql][DeleteAllEndpointStatusesNotInKeys] Failed to delete rows that do not belong to any of keys=%v: %s", keys, err.Error())
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
if s.writeThroughCache != nil {
|
||||||
|
// It's easier to just wipe out the entire cache than to try to find all keys that are not in the keys list
|
||||||
|
_ = s.writeThroughCache.DeleteKeysByPattern("*")
|
||||||
|
}
|
||||||
|
// Return number of rows deleted
|
||||||
rowsAffects, _ := result.RowsAffected()
|
rowsAffects, _ := result.RowsAffected()
|
||||||
return int(rowsAffects)
|
return int(rowsAffects)
|
||||||
}
|
}
|
||||||
@@ -357,6 +385,9 @@ func (s *Store) DeleteAllEndpointStatusesNotInKeys(keys []string) int {
|
|||||||
// Clear deletes everything from the store
|
// Clear deletes everything from the store
|
||||||
func (s *Store) Clear() {
|
func (s *Store) Clear() {
|
||||||
_, _ = s.db.Exec("DELETE FROM endpoints")
|
_, _ = s.db.Exec("DELETE FROM endpoints")
|
||||||
|
if s.writeThroughCache != nil {
|
||||||
|
_ = s.writeThroughCache.DeleteKeysByPattern("*")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save does nothing, because this store is immediately persistent.
|
// Save does nothing, because this store is immediately persistent.
|
||||||
@@ -367,6 +398,10 @@ func (s *Store) Save() error {
|
|||||||
// Close the database handle
|
// Close the database handle
|
||||||
func (s *Store) Close() {
|
func (s *Store) Close() {
|
||||||
_ = s.db.Close()
|
_ = s.db.Close()
|
||||||
|
if s.writeThroughCache != nil {
|
||||||
|
// Clear the cache too. If the store's been closed, we don't want to keep the cache around.
|
||||||
|
_ = s.writeThroughCache.DeleteKeysByPattern("*")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// insertEndpoint inserts an endpoint in the store and returns the generated id of said endpoint
|
// insertEndpoint inserts an endpoint in the store and returns the generated id of said endpoint
|
||||||
@@ -479,6 +514,15 @@ func (s *Store) getAllEndpointKeys(tx *sql.Tx) (keys []string, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) getEndpointStatusByKey(tx *sql.Tx, key string, parameters *paging.EndpointStatusParams) (*core.EndpointStatus, error) {
|
func (s *Store) getEndpointStatusByKey(tx *sql.Tx, key string, parameters *paging.EndpointStatusParams) (*core.EndpointStatus, error) {
|
||||||
|
var cacheKey string
|
||||||
|
if s.writeThroughCache != nil {
|
||||||
|
cacheKey = generateCacheKey(key, parameters)
|
||||||
|
if cachedEndpointStatus, exists := s.writeThroughCache.Get(cacheKey); exists {
|
||||||
|
if castedCachedEndpointStatus, ok := cachedEndpointStatus.(*core.EndpointStatus); ok {
|
||||||
|
return castedCachedEndpointStatus, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
endpointID, group, endpointName, err := s.getEndpointIDGroupAndNameByKey(tx, key)
|
endpointID, group, endpointName, err := s.getEndpointIDGroupAndNameByKey(tx, key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -494,6 +538,9 @@ func (s *Store) getEndpointStatusByKey(tx *sql.Tx, key string, parameters *pagin
|
|||||||
log.Printf("[sql][getEndpointStatusByKey] Failed to retrieve results for key=%s: %s", key, err.Error())
|
log.Printf("[sql][getEndpointStatusByKey] Failed to retrieve results for key=%s: %s", key, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if s.writeThroughCache != nil {
|
||||||
|
s.writeThroughCache.SetWithTTL(cacheKey, endpointStatus, cacheTTL)
|
||||||
|
}
|
||||||
return endpointStatus, nil
|
return endpointStatus, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -788,3 +835,29 @@ func (s *Store) deleteOldUptimeEntries(tx *sql.Tx, endpointID int64, maxAge time
|
|||||||
_, err := tx.Exec("DELETE FROM endpoint_uptimes WHERE endpoint_id = $1 AND hour_unix_timestamp < $2", endpointID, maxAge.Unix())
|
_, err := tx.Exec("DELETE FROM endpoint_uptimes WHERE endpoint_id = $1 AND hour_unix_timestamp < $2", endpointID, maxAge.Unix())
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func generateCacheKey(endpointKey string, p *paging.EndpointStatusParams) string {
|
||||||
|
return fmt.Sprintf("%s-%d-%d-%d-%d", endpointKey, p.EventsPage, p.EventsPageSize, p.ResultsPage, p.ResultsPageSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractKeyAndParamsFromCacheKey(cacheKey string) (string, *paging.EndpointStatusParams, error) {
|
||||||
|
parts := strings.Split(cacheKey, "-")
|
||||||
|
if len(parts) < 5 {
|
||||||
|
return "", nil, fmt.Errorf("invalid cache key: %s", cacheKey)
|
||||||
|
}
|
||||||
|
params := &paging.EndpointStatusParams{}
|
||||||
|
var err error
|
||||||
|
if params.EventsPage, err = strconv.Atoi(parts[len(parts)-4]); err != nil {
|
||||||
|
return "", nil, fmt.Errorf("invalid cache key: %s", err.Error())
|
||||||
|
}
|
||||||
|
if params.EventsPageSize, err = strconv.Atoi(parts[len(parts)-3]); err != nil {
|
||||||
|
return "", nil, fmt.Errorf("invalid cache key: %s", err.Error())
|
||||||
|
}
|
||||||
|
if params.ResultsPage, err = strconv.Atoi(parts[len(parts)-2]); err != nil {
|
||||||
|
return "", nil, fmt.Errorf("invalid cache key: %s", err.Error())
|
||||||
|
}
|
||||||
|
if params.ResultsPageSize, err = strconv.Atoi(parts[len(parts)-1]); err != nil {
|
||||||
|
return "", nil, fmt.Errorf("invalid cache key: %s", err.Error())
|
||||||
|
}
|
||||||
|
return strings.Join(parts[:len(parts)-4], "-"), params, nil
|
||||||
|
}
|
||||||
@@ -81,13 +81,13 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestNewStore(t *testing.T) {
|
func TestNewStore(t *testing.T) {
|
||||||
if _, err := NewStore("", "TestNewStore.db"); err != ErrDatabaseDriverNotSpecified {
|
if _, err := NewStore("", "TestNewStore.db", false); err != ErrDatabaseDriverNotSpecified {
|
||||||
t.Error("expected error due to blank driver parameter")
|
t.Error("expected error due to blank driver parameter")
|
||||||
}
|
}
|
||||||
if _, err := NewStore("sqlite", ""); err != ErrPathNotSpecified {
|
if _, err := NewStore("sqlite", "", false); err != ErrPathNotSpecified {
|
||||||
t.Error("expected error due to blank path parameter")
|
t.Error("expected error due to blank path parameter")
|
||||||
}
|
}
|
||||||
if store, err := NewStore("sqlite", t.TempDir()+"/TestNewStore.db"); err != nil {
|
if store, err := NewStore("sqlite", t.TempDir()+"/TestNewStore.db", false); err != nil {
|
||||||
t.Error("shouldn't have returned any error, got", err.Error())
|
t.Error("shouldn't have returned any error, got", err.Error())
|
||||||
} else {
|
} else {
|
||||||
_ = store.db.Close()
|
_ = store.db.Close()
|
||||||
@@ -95,7 +95,7 @@ func TestNewStore(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStore_InsertCleansUpOldUptimeEntriesProperly(t *testing.T) {
|
func TestStore_InsertCleansUpOldUptimeEntriesProperly(t *testing.T) {
|
||||||
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpOldUptimeEntriesProperly.db")
|
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpOldUptimeEntriesProperly.db", false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
now := time.Now().Round(time.Minute)
|
now := time.Now().Round(time.Minute)
|
||||||
now = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
|
now = time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
|
||||||
@@ -152,7 +152,7 @@ func TestStore_InsertCleansUpOldUptimeEntriesProperly(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStore_InsertCleansUpEventsAndResultsProperly(t *testing.T) {
|
func TestStore_InsertCleansUpEventsAndResultsProperly(t *testing.T) {
|
||||||
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpEventsAndResultsProperly.db")
|
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InsertCleansUpEventsAndResultsProperly.db", false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
for i := 0; i < resultsCleanUpThreshold+eventsCleanUpThreshold; i++ {
|
for i := 0; i < resultsCleanUpThreshold+eventsCleanUpThreshold; i++ {
|
||||||
store.Insert(&testEndpoint, &testSuccessfulResult)
|
store.Insert(&testEndpoint, &testSuccessfulResult)
|
||||||
@@ -170,7 +170,7 @@ func TestStore_InsertCleansUpEventsAndResultsProperly(t *testing.T) {
|
|||||||
|
|
||||||
func TestStore_Persistence(t *testing.T) {
|
func TestStore_Persistence(t *testing.T) {
|
||||||
path := t.TempDir() + "/TestStore_Persistence.db"
|
path := t.TempDir() + "/TestStore_Persistence.db"
|
||||||
store, _ := NewStore("sqlite", path)
|
store, _ := NewStore("sqlite", path, false)
|
||||||
store.Insert(&testEndpoint, &testSuccessfulResult)
|
store.Insert(&testEndpoint, &testSuccessfulResult)
|
||||||
store.Insert(&testEndpoint, &testUnsuccessfulResult)
|
store.Insert(&testEndpoint, &testUnsuccessfulResult)
|
||||||
if uptime, _ := store.GetUptimeByKey(testEndpoint.Key(), time.Now().Add(-time.Hour), time.Now()); uptime != 0.5 {
|
if uptime, _ := store.GetUptimeByKey(testEndpoint.Key(), time.Now().Add(-time.Hour), time.Now()); uptime != 0.5 {
|
||||||
@@ -188,7 +188,7 @@ func TestStore_Persistence(t *testing.T) {
|
|||||||
t.Fatal("sanity check failed")
|
t.Fatal("sanity check failed")
|
||||||
}
|
}
|
||||||
store.Close()
|
store.Close()
|
||||||
store, _ = NewStore("sqlite", path)
|
store, _ = NewStore("sqlite", path, false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
ssFromNewStore, _ := store.GetEndpointStatus(testEndpoint.Group, testEndpoint.Name, paging.NewEndpointStatusParams().WithResults(1, common.MaximumNumberOfResults).WithEvents(1, common.MaximumNumberOfEvents))
|
ssFromNewStore, _ := store.GetEndpointStatus(testEndpoint.Group, testEndpoint.Name, paging.NewEndpointStatusParams().WithResults(1, common.MaximumNumberOfResults).WithEvents(1, common.MaximumNumberOfEvents))
|
||||||
if ssFromNewStore == nil || ssFromNewStore.Group != "group" || ssFromNewStore.Name != "name" || len(ssFromNewStore.Events) != 3 || len(ssFromNewStore.Results) != 2 {
|
if ssFromNewStore == nil || ssFromNewStore.Group != "group" || ssFromNewStore.Name != "name" || len(ssFromNewStore.Events) != 3 || len(ssFromNewStore.Results) != 2 {
|
||||||
@@ -252,7 +252,7 @@ func TestStore_Persistence(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStore_Save(t *testing.T) {
|
func TestStore_Save(t *testing.T) {
|
||||||
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_Save.db")
|
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_Save.db", false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
if store.Save() != nil {
|
if store.Save() != nil {
|
||||||
t.Error("Save shouldn't do anything for this store")
|
t.Error("Save shouldn't do anything for this store")
|
||||||
@@ -262,7 +262,7 @@ func TestStore_Save(t *testing.T) {
|
|||||||
// Note that are much more extensive tests in /storage/store/store_test.go.
|
// Note that are much more extensive tests in /storage/store/store_test.go.
|
||||||
// This test is simply an extra sanity check
|
// This test is simply an extra sanity check
|
||||||
func TestStore_SanityCheck(t *testing.T) {
|
func TestStore_SanityCheck(t *testing.T) {
|
||||||
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_SanityCheck.db")
|
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_SanityCheck.db", false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
store.Insert(&testEndpoint, &testSuccessfulResult)
|
store.Insert(&testEndpoint, &testSuccessfulResult)
|
||||||
endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams())
|
endpointStatuses, _ := store.GetAllEndpointStatuses(paging.NewEndpointStatusParams())
|
||||||
@@ -306,7 +306,7 @@ func TestStore_SanityCheck(t *testing.T) {
|
|||||||
|
|
||||||
// TestStore_InvalidTransaction tests what happens if an invalid transaction is passed as parameter
|
// TestStore_InvalidTransaction tests what happens if an invalid transaction is passed as parameter
|
||||||
func TestStore_InvalidTransaction(t *testing.T) {
|
func TestStore_InvalidTransaction(t *testing.T) {
|
||||||
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InvalidTransaction.db")
|
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_InvalidTransaction.db", false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
tx, _ := store.db.Begin()
|
tx, _ := store.db.Begin()
|
||||||
tx.Commit()
|
tx.Commit()
|
||||||
@@ -364,7 +364,7 @@ func TestStore_InvalidTransaction(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStore_NoRows(t *testing.T) {
|
func TestStore_NoRows(t *testing.T) {
|
||||||
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_NoRows.db")
|
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_NoRows.db", false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
tx, _ := store.db.Begin()
|
tx, _ := store.db.Begin()
|
||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
@@ -378,7 +378,7 @@ func TestStore_NoRows(t *testing.T) {
|
|||||||
|
|
||||||
// This tests very unlikely cases where a table is deleted.
|
// This tests very unlikely cases where a table is deleted.
|
||||||
func TestStore_BrokenSchema(t *testing.T) {
|
func TestStore_BrokenSchema(t *testing.T) {
|
||||||
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_BrokenSchema.db")
|
store, _ := NewStore("sqlite", t.TempDir()+"/TestStore_BrokenSchema.db", false)
|
||||||
defer store.Close()
|
defer store.Close()
|
||||||
if err := store.Insert(&testEndpoint, &testSuccessfulResult); err != nil {
|
if err := store.Insert(&testEndpoint, &testSuccessfulResult); err != nil {
|
||||||
t.Fatal("expected no error, got", err.Error())
|
t.Fatal("expected no error, got", err.Error())
|
||||||
@@ -391,6 +391,7 @@ func TestStore_BrokenSchema(t *testing.T) {
|
|||||||
}
|
}
|
||||||
// Break
|
// Break
|
||||||
_, _ = store.db.Exec("DROP TABLE endpoints")
|
_, _ = store.db.Exec("DROP TABLE endpoints")
|
||||||
|
// And now we'll try to insert something in our broken schema
|
||||||
if err := store.Insert(&testEndpoint, &testSuccessfulResult); err == nil {
|
if err := store.Insert(&testEndpoint, &testSuccessfulResult); err == nil {
|
||||||
t.Fatal("expected an error")
|
t.Fatal("expected an error")
|
||||||
}
|
}
|
||||||
@@ -477,3 +478,89 @@ func TestStore_BrokenSchema(t *testing.T) {
|
|||||||
t.Fatal("expected an error")
|
t.Fatal("expected an error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCacheKey(t *testing.T) {
|
||||||
|
scenarios := []struct {
|
||||||
|
endpointKey string
|
||||||
|
params paging.EndpointStatusParams
|
||||||
|
overrideCacheKey string
|
||||||
|
expectedCacheKey string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
endpointKey: "simple",
|
||||||
|
params: paging.EndpointStatusParams{EventsPage: 1, EventsPageSize: 2, ResultsPage: 3, ResultsPageSize: 4},
|
||||||
|
expectedCacheKey: "simple-1-2-3-4",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
endpointKey: "with-hyphen",
|
||||||
|
params: paging.EndpointStatusParams{EventsPage: 0, EventsPageSize: 0, ResultsPage: 1, ResultsPageSize: 20},
|
||||||
|
expectedCacheKey: "with-hyphen-0-0-1-20",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
endpointKey: "with-multiple-hyphens",
|
||||||
|
params: paging.EndpointStatusParams{EventsPage: 0, EventsPageSize: 0, ResultsPage: 2, ResultsPageSize: 20},
|
||||||
|
expectedCacheKey: "with-multiple-hyphens-0-0-2-20",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
overrideCacheKey: "invalid-a-2-3-4",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
overrideCacheKey: "invalid-1-a-3-4",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
overrideCacheKey: "invalid-1-2-a-4",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
overrideCacheKey: "invalid-1-2-3-a",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
overrideCacheKey: "notenoughhyphen1-2-3-4",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.expectedCacheKey+scenario.overrideCacheKey, func(t *testing.T) {
|
||||||
|
var cacheKey string
|
||||||
|
if len(scenario.overrideCacheKey) > 0 {
|
||||||
|
cacheKey = scenario.overrideCacheKey
|
||||||
|
} else {
|
||||||
|
cacheKey = generateCacheKey(scenario.endpointKey, &scenario.params)
|
||||||
|
if cacheKey != scenario.expectedCacheKey {
|
||||||
|
t.Errorf("expected %s, got %s", scenario.expectedCacheKey, cacheKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extractedEndpointKey, extractedParams, err := extractKeyAndParamsFromCacheKey(cacheKey)
|
||||||
|
if (err != nil) != scenario.wantErr {
|
||||||
|
t.Errorf("expected error %v, got %v", scenario.wantErr, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
// If there's an error, we don't need to check the extracted values
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if extractedEndpointKey != scenario.endpointKey {
|
||||||
|
t.Errorf("expected endpointKey %s, got %s", scenario.endpointKey, extractedEndpointKey)
|
||||||
|
}
|
||||||
|
if extractedParams.EventsPage != scenario.params.EventsPage {
|
||||||
|
t.Errorf("expected EventsPage %d, got %d", scenario.params.EventsPage, extractedParams.EventsPage)
|
||||||
|
}
|
||||||
|
if extractedParams.EventsPageSize != scenario.params.EventsPageSize {
|
||||||
|
t.Errorf("expected EventsPageSize %d, got %d", scenario.params.EventsPageSize, extractedParams.EventsPageSize)
|
||||||
|
}
|
||||||
|
if extractedParams.ResultsPage != scenario.params.ResultsPage {
|
||||||
|
t.Errorf("expected ResultsPage %d, got %d", scenario.params.ResultsPage, extractedParams.ResultsPage)
|
||||||
|
}
|
||||||
|
if extractedParams.ResultsPageSize != scenario.params.ResultsPageSize {
|
||||||
|
t.Errorf("expected ResultsPageSize %d, got %d", scenario.params.ResultsPageSize, extractedParams.ResultsPageSize)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-11
@@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v4/storage/store/sql"
|
"github.com/TwiN/gatus/v4/storage/store/sql"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Store is the interface that each stores should implement
|
// Store is the interface that each store should implement
|
||||||
type Store interface {
|
type Store interface {
|
||||||
// GetAllEndpointStatuses returns the JSON encoding of all monitored core.EndpointStatus
|
// GetAllEndpointStatuses returns the JSON encoding of all monitored core.EndpointStatus
|
||||||
// with a subset of core.Result defined by the page and pageSize parameters
|
// with a subset of core.Result defined by the page and pageSize parameters
|
||||||
@@ -103,22 +103,14 @@ func Initialize(cfg *storage.Config) error {
|
|||||||
ctx, cancelFunc = context.WithCancel(context.Background())
|
ctx, cancelFunc = context.WithCancel(context.Background())
|
||||||
switch cfg.Type {
|
switch cfg.Type {
|
||||||
case storage.TypeSQLite, storage.TypePostgres:
|
case storage.TypeSQLite, storage.TypePostgres:
|
||||||
store, err = sql.NewStore(string(cfg.Type), cfg.Path)
|
store, err = sql.NewStore(string(cfg.Type), cfg.Path, cfg.Caching)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
case storage.TypeMemory:
|
case storage.TypeMemory:
|
||||||
fallthrough
|
fallthrough
|
||||||
default:
|
default:
|
||||||
if len(cfg.Path) > 0 {
|
store, _ = memory.NewStore()
|
||||||
store, err = memory.NewStore(cfg.Path)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
go autoSave(ctx, store, 7*time.Minute)
|
|
||||||
} else {
|
|
||||||
store, _ = memory.NewStore("")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,11 +12,11 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func BenchmarkStore_GetAllEndpointStatuses(b *testing.B) {
|
func BenchmarkStore_GetAllEndpointStatuses(b *testing.B) {
|
||||||
memoryStore, err := memory.NewStore("")
|
memoryStore, err := memory.NewStore()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal("failed to create store:", err.Error())
|
b.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetAllEndpointStatuses.db")
|
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetAllEndpointStatuses.db", false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal("failed to create store:", err.Error())
|
b.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
@@ -81,11 +81,11 @@ func BenchmarkStore_GetAllEndpointStatuses(b *testing.B) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkStore_Insert(b *testing.B) {
|
func BenchmarkStore_Insert(b *testing.B) {
|
||||||
memoryStore, err := memory.NewStore("")
|
memoryStore, err := memory.NewStore()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal("failed to create store:", err.Error())
|
b.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_Insert.db")
|
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_Insert.db", false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal("failed to create store:", err.Error())
|
b.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
@@ -153,11 +153,11 @@ func BenchmarkStore_Insert(b *testing.B) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkStore_GetEndpointStatusByKey(b *testing.B) {
|
func BenchmarkStore_GetEndpointStatusByKey(b *testing.B) {
|
||||||
memoryStore, err := memory.NewStore("")
|
memoryStore, err := memory.NewStore()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal("failed to create store:", err.Error())
|
b.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetEndpointStatusByKey.db")
|
sqliteStore, err := sql.NewStore("sqlite", b.TempDir()+"/BenchmarkStore_GetEndpointStatusByKey.db", false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal("failed to create store:", err.Error())
|
b.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -89,11 +89,15 @@ type Scenario struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func initStoresAndBaseScenarios(t *testing.T, testName string) []*Scenario {
|
func initStoresAndBaseScenarios(t *testing.T, testName string) []*Scenario {
|
||||||
memoryStore, err := memory.NewStore("")
|
memoryStore, err := memory.NewStore()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("failed to create store:", err.Error())
|
t.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
sqliteStore, err := sql.NewStore("sqlite", t.TempDir()+"/"+testName+".db")
|
sqliteStore, err := sql.NewStore("sqlite", t.TempDir()+"/"+testName+".db", false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to create store:", err.Error())
|
||||||
|
}
|
||||||
|
sqliteStoreWithCaching, err := sql.NewStore("sqlite", t.TempDir()+"/"+testName+"-with-caching.db", true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("failed to create store:", err.Error())
|
t.Fatal("failed to create store:", err.Error())
|
||||||
}
|
}
|
||||||
@@ -106,6 +110,10 @@ func initStoresAndBaseScenarios(t *testing.T, testName string) []*Scenario {
|
|||||||
Name: "sqlite",
|
Name: "sqlite",
|
||||||
Store: sqliteStore,
|
Store: sqliteStore,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "sqlite-with-caching",
|
||||||
|
Store: sqliteStoreWithCaching,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -528,17 +536,17 @@ func TestStore_DeleteAllEndpointStatusesNotInKeys(t *testing.T) {
|
|||||||
scenario.Store.Insert(&firstEndpoint, result)
|
scenario.Store.Insert(&firstEndpoint, result)
|
||||||
scenario.Store.Insert(&secondEndpoint, result)
|
scenario.Store.Insert(&secondEndpoint, result)
|
||||||
if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
|
if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
|
||||||
t.Fatal("firstEndpoint should exist")
|
t.Fatal("firstEndpoint should exist, got", ss)
|
||||||
}
|
}
|
||||||
if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
|
if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
|
||||||
t.Fatal("secondEndpoint should exist")
|
t.Fatal("secondEndpoint should exist, got", ss)
|
||||||
}
|
}
|
||||||
scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{firstEndpoint.Key()})
|
scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{firstEndpoint.Key()})
|
||||||
if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
|
if ss, _ := scenario.Store.GetEndpointStatusByKey(firstEndpoint.Key(), paging.NewEndpointStatusParams()); ss == nil {
|
||||||
t.Error("secondEndpoint should've been deleted")
|
t.Error("secondEndpoint should still exist, got", ss)
|
||||||
}
|
}
|
||||||
if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss != nil {
|
if ss, _ := scenario.Store.GetEndpointStatusByKey(secondEndpoint.Key(), paging.NewEndpointStatusParams()); ss != nil {
|
||||||
t.Error("firstEndpoint should still exist")
|
t.Error("firstEndpoint should have been deleted, got", ss)
|
||||||
}
|
}
|
||||||
// Delete everything
|
// Delete everything
|
||||||
scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{})
|
scenario.Store.DeleteAllEndpointStatusesNotInKeys([]string{})
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2021 TwiN
|
Copyright (c) 2022 TwiN
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
|||||||
+27
-26
@@ -1,9 +1,9 @@
|
|||||||
# gocache
|
# gocache
|
||||||

|

|
||||||
[](https://goreportcard.com/report/github.com/TwiN/gocache)
|
[](https://goreportcard.com/report/github.com/TwiN/gocache)
|
||||||
[](https://codecov.io/gh/TwiN/gocache)
|
[](https://codecov.io/gh/TwiN/gocache)
|
||||||
[](https://github.com/TwiN/gocache)
|
[](https://github.com/TwiN/gocache)
|
||||||
[](https://pkg.go.dev/github.com/TwiN/gocache)
|
[](https://pkg.go.dev/github.com/TwiN/gocache/v2)
|
||||||
[](https://github.com/TwiN)
|
[](https://github.com/TwiN)
|
||||||
|
|
||||||
gocache is an easy-to-use, high-performance, lightweight and thread-safe (goroutine-safe) in-memory key-value cache
|
gocache is an easy-to-use, high-performance, lightweight and thread-safe (goroutine-safe) in-memory key-value cache
|
||||||
@@ -65,27 +65,28 @@ cache.StartJanitor()
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Functions
|
### Functions
|
||||||
| Function | Description |
|
| Function | Description |
|
||||||
| --------------------------------- | ----------- |
|
|-----------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||||
| WithMaxSize | Sets the max size of the cache. `gocache.NoMaxSize` means there is no limit. If not set, the default max size is `gocache.DefaultMaxSize`.
|
| WithMaxSize | Sets the max size of the cache. `gocache.NoMaxSize` means there is no limit. If not set, the default max size is `gocache.DefaultMaxSize`. |
|
||||||
| WithMaxMemoryUsage | Sets the max memory usage of the cache. `gocache.NoMaxMemoryUsage` means there is no limit. The default behavior is to not evict based on memory usage.
|
| WithMaxMemoryUsage | Sets the max memory usage of the cache. `gocache.NoMaxMemoryUsage` means there is no limit. The default behavior is to not evict based on memory usage. |
|
||||||
| WithEvictionPolicy | Sets the eviction algorithm to be used when the cache reaches the max size. If not set, the default eviction policy is `gocache.FirstInFirstOut` (FIFO).
|
| WithEvictionPolicy | Sets the eviction algorithm to be used when the cache reaches the max size. If not set, the default eviction policy is `gocache.FirstInFirstOut` (FIFO). |
|
||||||
| WithForceNilInterfaceOnNilPointer | Configures whether values with a nil pointer passed to write functions should be forcefully set to nil. Defaults to true.
|
| WithForceNilInterfaceOnNilPointer | Configures whether values with a nil pointer passed to write functions should be forcefully set to nil. Defaults to true. |
|
||||||
| StartJanitor | Starts the janitor, which is in charge of deleting expired cache entries in the background.
|
| StartJanitor | Starts the janitor, which is in charge of deleting expired cache entries in the background. |
|
||||||
| StopJanitor | Stops the janitor.
|
| StopJanitor | Stops the janitor. |
|
||||||
| Set | Same as `SetWithTTL`, but with no expiration (`gocache.NoExpiration`)
|
| Set | Same as `SetWithTTL`, but with no expiration (`gocache.NoExpiration`) |
|
||||||
| SetAll | Same as `Set`, but in bulk
|
| SetAll | Same as `Set`, but in bulk |
|
||||||
| SetWithTTL | Creates or updates a cache entry with the given key, value and expiration time. If the max size after the aforementioned operation is above the configured max size, the tail will be evicted. Depending on the eviction policy, the tail is defined as the oldest
|
| SetWithTTL | Creates or updates a cache entry with the given key, value and expiration time. If the max size after the aforementioned operation is above the configured max size, the tail will be evicted. Depending on the eviction policy, the tail is defined as the oldest |
|
||||||
| Get | Gets a cache entry by its key.
|
| Get | Gets a cache entry by its key. |
|
||||||
| GetByKeys | Gets a map of entries by their keys. The resulting map will contain all keys, even if some of the keys in the slice passed as parameter were not present in the cache.
|
| GetByKeys | Gets a map of entries by their keys. The resulting map will contain all keys, even if some of the keys in the slice passed as parameter were not present in the cache. |
|
||||||
| GetAll | Gets all cache entries.
|
| GetAll | Gets all cache entries. |
|
||||||
| GetKeysByPattern | Retrieves a slice of keys that matches a given pattern.
|
| GetKeysByPattern | Retrieves a slice of keys that matches a given pattern. |
|
||||||
| Delete | Removes a key from the cache.
|
| Delete | Removes a key from the cache. |
|
||||||
| DeleteAll | Removes multiple keys from the cache.
|
| DeleteAll | Removes multiple keys from the cache. |
|
||||||
| Count | Gets the size of the cache. This includes cache keys which may have already expired, but have not been removed yet.
|
| DeleteKeysByPattern | Removes all keys that that matches a given pattern. |
|
||||||
| Clear | Wipes the cache.
|
| Count | Gets the size of the cache. This includes cache keys which may have already expired, but have not been removed yet. |
|
||||||
| TTL | Gets the time until a cache key expires.
|
| Clear | Wipes the cache. |
|
||||||
| Expire | Sets the expiration time of an existing cache key.
|
| TTL | Gets the time until a cache key expires. |
|
||||||
|
| Expire | Sets the expiration time of an existing cache key. |
|
||||||
|
|
||||||
For further documentation, please refer to [Go Reference](https://pkg.go.dev/github.com/TwiN/gocache)
|
For further documentation, please refer to [Go Reference](https://pkg.go.dev/github.com/TwiN/gocache)
|
||||||
|
|
||||||
@@ -132,7 +133,7 @@ func main() {
|
|||||||
cache.SetWithTTL("key-with-ttl", "value", 60*time.Minute)
|
cache.SetWithTTL("key-with-ttl", "value", 60*time.Minute)
|
||||||
cache.SetAll(map[string]interface{}{"k1": "v1", "k2": "v2", "k3": "v3"})
|
cache.SetAll(map[string]interface{}{"k1": "v1", "k2": "v2", "k3": "v3"})
|
||||||
|
|
||||||
fmt.Println("[Count] Cache size:", cache.Count())
|
fmt.Println("[Count] Cache size:", cache.Count())
|
||||||
|
|
||||||
value, exists := cache.Get("key")
|
value, exists := cache.Get("key")
|
||||||
fmt.Printf("[Get] key=key; value=%s; exists=%v\n", value, exists)
|
fmt.Printf("[Get] key=key; value=%s; exists=%v\n", value, exists)
|
||||||
@@ -345,8 +346,8 @@ import (
|
|||||||
var cache = gocache.NewCache()
|
var cache = gocache.NewCache()
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
data := retrieveCacheEntriesUsingWhateverMeanYouUsedToPersistIt()
|
data := retrieveCacheEntriesUsingWhateverMeanYouUsedToPersistIt()
|
||||||
cache.SetAll(data)
|
cache.SetAll(data)
|
||||||
// Start everything else on another goroutine to prevent blocking the main goroutine
|
// Start everything else on another goroutine to prevent blocking the main goroutine
|
||||||
go Start()
|
go Start()
|
||||||
// Wait for termination signal
|
// Wait for termination signal
|
||||||
|
|||||||
+9
-3
@@ -311,8 +311,8 @@ func (cache *Cache) Get(key string) (interface{}, bool) {
|
|||||||
cache.mutex.Lock()
|
cache.mutex.Lock()
|
||||||
entry, ok := cache.get(key)
|
entry, ok := cache.get(key)
|
||||||
if !ok {
|
if !ok {
|
||||||
cache.mutex.Unlock()
|
|
||||||
cache.stats.Misses++
|
cache.stats.Misses++
|
||||||
|
cache.mutex.Unlock()
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
if entry.Expired() {
|
if entry.Expired() {
|
||||||
@@ -388,8 +388,7 @@ func (cache *Cache) GetAll() map[string]interface{} {
|
|||||||
// cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them
|
// cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them
|
||||||
// cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them
|
// cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them
|
||||||
//
|
//
|
||||||
// Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry, the latter
|
// Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU).
|
||||||
// only applying if the cache uses the LeastRecentlyUsed eviction policy.
|
|
||||||
// The reason for that behavior is that these two (active eviction and access) only applies when you access the value
|
// The reason for that behavior is that these two (active eviction and access) only applies when you access the value
|
||||||
// of the cache entry, and this function only returns the keys.
|
// of the cache entry, and this function only returns the keys.
|
||||||
func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string {
|
func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string {
|
||||||
@@ -435,6 +434,13 @@ func (cache *Cache) DeleteAll(keys []string) int {
|
|||||||
return numberOfKeysDeleted
|
return numberOfKeysDeleted
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteKeysByPattern deletes all entries matching a given key pattern and returns the number of entries deleted.
|
||||||
|
//
|
||||||
|
// Note that DeleteKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU).
|
||||||
|
func (cache *Cache) DeleteKeysByPattern(pattern string) int {
|
||||||
|
return cache.DeleteAll(cache.GetKeysByPattern(pattern, 0))
|
||||||
|
}
|
||||||
|
|
||||||
// Count returns the total amount of entries in the cache, regardless of whether they're expired or not
|
// Count returns the total amount of entries in the cache, regardless of whether they're expired or not
|
||||||
func (cache *Cache) Count() int {
|
func (cache *Cache) Count() int {
|
||||||
cache.mutex.RLock()
|
cache.mutex.RLock()
|
||||||
|
|||||||
Vendored
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
# github.com/TwiN/g8 v1.3.0
|
# github.com/TwiN/g8 v1.3.0
|
||||||
## explicit; go 1.17
|
## explicit; go 1.17
|
||||||
github.com/TwiN/g8
|
github.com/TwiN/g8
|
||||||
# github.com/TwiN/gocache/v2 v2.0.0
|
# github.com/TwiN/gocache/v2 v2.1.0
|
||||||
## explicit; go 1.17
|
## explicit; go 1.18
|
||||||
github.com/TwiN/gocache/v2
|
github.com/TwiN/gocache/v2
|
||||||
# github.com/TwiN/health v1.4.0
|
# github.com/TwiN/health v1.4.0
|
||||||
## explicit; go 1.18
|
## explicit; go 1.18
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/TwiN/gatus/v4/alerting/provider/custom"
|
"github.com/TwiN/gatus/v4/alerting/provider/custom"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/discord"
|
"github.com/TwiN/gatus/v4/alerting/provider/discord"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/email"
|
"github.com/TwiN/gatus/v4/alerting/provider/email"
|
||||||
|
"github.com/TwiN/gatus/v4/alerting/provider/matrix"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/mattermost"
|
"github.com/TwiN/gatus/v4/alerting/provider/mattermost"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/messagebird"
|
"github.com/TwiN/gatus/v4/alerting/provider/messagebird"
|
||||||
"github.com/TwiN/gatus/v4/alerting/provider/pagerduty"
|
"github.com/TwiN/gatus/v4/alerting/provider/pagerduty"
|
||||||
@@ -312,6 +313,19 @@ func TestHandleAlertingWithProviderThatReturnsAnError(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: "matrix",
|
||||||
|
AlertType: alert.TypeMatrix,
|
||||||
|
AlertingConfig: &alerting.Config{
|
||||||
|
Matrix: &matrix.AlertProvider{
|
||||||
|
MatrixProviderConfig: matrix.MatrixProviderConfig{
|
||||||
|
ServerURL: "https://example.com",
|
||||||
|
AccessToken: "1",
|
||||||
|
InternalRoomID: "!a:example.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, scenario := range scenarios {
|
for _, scenario := range scenarios {
|
||||||
|
|||||||
Generated
+2678
-2512
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "gatus",
|
"name": "gatus",
|
||||||
"version": "3.8.0",
|
"version": "4.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"serve": "vue-cli-service serve --mode development",
|
"serve": "vue-cli-service serve --mode development",
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
"eslint": "7.32.0",
|
"eslint": "7.32.0",
|
||||||
"eslint-plugin-vue": "7.20.0",
|
"eslint-plugin-vue": "7.20.0",
|
||||||
"postcss": "8.4.14",
|
"postcss": "8.4.14",
|
||||||
"tailwindcss": "3.1.2"
|
"tailwindcss": "^3.1.8"
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"eslintConfig": {
|
||||||
"root": true,
|
"root": true,
|
||||||
|
|||||||
@@ -65,29 +65,27 @@
|
|||||||
<div v-if="endpointStatus && endpointStatus.key">
|
<div v-if="endpointStatus && endpointStatus.key">
|
||||||
<h1 class="text-xl xl:text-3xl font-mono text-gray-400 mt-4">EVENTS</h1>
|
<h1 class="text-xl xl:text-3xl font-mono text-gray-400 mt-4">EVENTS</h1>
|
||||||
<hr />
|
<hr />
|
||||||
<div>
|
<ul role="list" class="px-0 xl:px-24 divide-y divide-gray-200 dark:divide-gray-600">
|
||||||
<slot v-for="event in events" :key="event">
|
<li v-for="event in events" :key="event" class="p-3 my-4">
|
||||||
<div class="p-3 my-4">
|
<h2 class="text-lg">
|
||||||
<h2 class="text-lg">
|
<img v-if="event.type === 'HEALTHY'" src="../assets/arrow-up-green.png" alt="Healthy"
|
||||||
<img v-if="event.type === 'HEALTHY'" src="../assets/arrow-up-green.png" alt="Healthy"
|
class="border border-green-600 rounded-full opacity-75 bg-green-100 mr-2 inline" width="26"/>
|
||||||
class="border border-green-600 rounded-full opacity-75 bg-green-100 mr-2 inline" width="26"/>
|
<img v-else-if="event.type === 'UNHEALTHY'" src="../assets/arrow-down-red.png" alt="Unhealthy"
|
||||||
<img v-else-if="event.type === 'UNHEALTHY'" src="../assets/arrow-down-red.png" alt="Unhealthy"
|
class="border border-red-500 rounded-full opacity-75 bg-red-100 mr-2 inline" width="26"/>
|
||||||
class="border border-red-500 rounded-full opacity-75 bg-red-100 mr-2 inline" width="26"/>
|
<img v-else-if="event.type === 'START'" src="../assets/arrow-right-black.png" alt="Start"
|
||||||
<img v-else-if="event.type === 'START'" src="../assets/arrow-right-black.png" alt="Start"
|
class="border border-gray-500 rounded-full opacity-75 bg-gray-100 mr-2 inline" width="26"/>
|
||||||
class="border border-gray-500 rounded-full opacity-75 bg-gray-100 mr-2 inline" width="26"/>
|
{{ event.fancyText }}
|
||||||
{{ event.fancyText }}
|
</h2>
|
||||||
</h2>
|
<div class="flex mt-1 text-sm text-gray-400">
|
||||||
<div class="flex mt-1 text-sm text-gray-400">
|
<div class="flex-1 text-left pl-10">
|
||||||
<div class="flex-1 text-left pl-10">
|
{{ prettifyTimestamp(event.timestamp) }}
|
||||||
{{ prettifyTimestamp(event.timestamp) }}
|
</div>
|
||||||
</div>
|
<div class="flex-1 text-right">
|
||||||
<div class="flex-1 text-right">
|
{{ event.fancyTimeAgo }}
|
||||||
{{ event.fancyTimeAgo }}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</slot>
|
</li>
|
||||||
</div>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Settings @refreshData="fetchData"/>
|
<Settings @refreshData="fetchData"/>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
#social[data-v-a4b3d200]{position:fixed;right:5px;bottom:5px;padding:5px;margin:0;z-index:100}#social img[data-v-a4b3d200]{opacity:.3}#social img[data-v-a4b3d200]:hover{opacity:1}#tooltip{position:fixed;background-color:#fff;border:1px solid #d3d3d3;border-radius:4px;padding:6px;font-size:13px}#tooltip code{color:#212529;line-height:1}#tooltip .tooltip-title{font-weight:700;margin-bottom:0;display:block;margin-top:8px}#tooltip>.tooltip-title:first-child{margin-top:0}
|
#social[data-v-a4b3d200]{position:fixed;right:5px;bottom:5px;padding:5px;margin:0;z-index:100}#social img[data-v-a4b3d200]{opacity:.3}#social img[data-v-a4b3d200]:hover{opacity:1}#tooltip{position:fixed;background-color:#fff;border:1px solid #d3d3d3;border-radius:4px;padding:6px;font-size:13px}#tooltip code{color:#212529;line-height:1}#tooltip .tooltip-title{font-weight:700;margin-bottom:0;display:block;margin-top:8px}#tooltip>.tooltip-title:first-child{margin-top:0}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
! tailwindcss v3.1.2 | 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:-ms-input-placeholder,textarea:-ms-input-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-Line 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 @@
|
|||||||
<!doctype html><html lang="en"><head><meta charset="utf-8"/><script>window.config = {logo: "{{ .Logo }}", header: "{{ .Header }}", link: "{{ .Link }}", buttons: []};{{- range .Buttons}}window.config.buttons.push({name:"{{ .Name }}",link:"{{ .Link }}"});{{end}}</script><title>{{ .Title }}</title><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"/><link rel="shortcut icon" href="/favicon.ico"/><meta property="description" content="Gatus is an advanced automated status page that lets you monitor your applications and configure alerts to notify you if there's an issue"/><script defer="defer" type="module" src="/js/chunk-vendors.js"></script><script defer="defer" type="module" src="/js/app.js"></script><link href="/css/app.css" rel="stylesheet"><script defer="defer" src="/js/chunk-vendors-legacy.js" nomodule></script><script defer="defer" src="/js/app-legacy.js" nomodule></script></head><body class="dark:bg-gray-900"><noscript><strong>Enable JavaScript to view this page.</strong></noscript><div id="app"></div></body></html>
|
<!doctype html><html lang="en"><head><meta charset="utf-8"/><script>window.config = {logo: "{{ .Logo }}", header: "{{ .Header }}", link: "{{ .Link }}", buttons: []};{{- range .Buttons}}window.config.buttons.push({name:"{{ .Name }}",link:"{{ .Link }}"});{{end}}</script><title>{{ .Title }}</title><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"/><link rel="shortcut icon" href="/favicon.ico"/><meta property="description" content="Gatus is an advanced automated status page that lets you monitor your applications and configure alerts to notify you if there's an issue"/><script defer="defer" src="/js/chunk-vendors.js"></script><script defer="defer" src="/js/app.js"></script><link href="/css/app.css" rel="stylesheet"></head><body class="dark:bg-gray-900"><noscript><strong>Enable JavaScript to view this page.</strong></noscript><div id="app"></div></body></html>
|
||||||
@@ -1 +0,0 @@
|
|||||||
(function(){"use strict";var e={5034:function(e,t,n){n.d(t,{L:function(){return mn}});n(6992),n(8674),n(9601),n(7727);var o=n(9963),s=(n(9254),n(8309),n(6252)),r=n(3577),a=n(9574),i={class:"mb-2"},l={class:"flex flex-wrap"},u={class:"w-3/4 text-left my-auto"},g={class:"text-3xl xl:text-5xl lg:text-4xl font-light"},c={class:"w-1/4 flex justify-end"},d=["href"],h=["src"],p={key:1,src:a,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},f={key:0,class:"flex flex-wrap"},m=["href"],A={key:2,class:"mx-auto max-w-md pt-12"},v=(0,s._)("img",{src:a,alt:"Gatus",class:"mx-auto",style:{"max-width":"160px","min-width":"50px","min-height":"50px"}},null,-1),w=(0,s._)("h2",{class:"mt-4 text-center text-4xl font-extrabold text-gray-800 dark:text-gray-200"}," Gatus ",-1),x={class:"mt-8 py-7 px-4 rounded-sm sm:bg-gray-100 sm:border sm:border-gray-300 sm:shadow-2xl sm:px-10"},y=(0,s._)("div",{class:"sm:mx-auto sm:w-full"},[(0,s._)("h2",{class:"mb-4 text-center text-xl font-bold text-gray-600 dark:text-gray-200 dark:sm:text-gray-600"}," Sign in ")],-1),k={key:0,class:"text-red-500 text-center my-2"},T={class:"text-xl"},b={key:0,class:"text-red-500"},R={key:1,class:"text-red-500"},I=["href"];function D(e,t,n,o,a,D){var C=(0,s.up)("Loading"),S=(0,s.up)("router-view"),E=(0,s.up)("Tooltip"),B=(0,s.up)("Social");return(0,s.wg)(),(0,s.iD)(s.HY,null,[a.retrievedConfig?((0,s.wg)(),(0,s.iD)("div",{key:1,class:(0,r.C_)([a.config&&a.config.oidc&&!a.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,s._)("div",i,[(0,s._)("div",l,[(0,s._)("div",u,[(0,s._)("div",g,(0,r.zw)(D.header),1)]),(0,s._)("div",c,[(0,s._)("a",{href:D.link,target:"_blank",style:{width:"100px"}},[D.logo?((0,s.wg)(),(0,s.iD)("img",{key:0,src:D.logo,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},null,8,h)):((0,s.wg)(),(0,s.iD)("img",p))],8,d)])]),D.buttons?((0,s.wg)(),(0,s.iD)("div",f,[((0,s.wg)(!0),(0,s.iD)(s.HY,null,(0,s.Ko)(D.buttons,(function(e){return(0,s.wg)(),(0,s.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,r.zw)(e.name),9,m)})),128))])):(0,s.kq)("",!0)]),(0,s.Wm)(S,{onShowTooltip:D.showTooltip},null,8,["onShowTooltip"])],2)):((0,s.wg)(),(0,s.j4)(C,{key:0,class:"h-64 w-64 px-4"})),a.config&&a.config.oidc&&!a.config.authenticated?((0,s.wg)(),(0,s.iD)("div",A,[v,w,(0,s._)("div",x,[y,e.$route&&e.$route.query.error?((0,s.wg)(),(0,s.iD)("div",k,[(0,s._)("div",T,["access_denied"===e.$route.query.error?((0,s.wg)(),(0,s.iD)("span",b,"You do not have access to this status page")):((0,s.wg)(),(0,s.iD)("span",R,(0,r.zw)(e.$route.query.error),1))])])):(0,s.kq)("",!0),(0,s._)("div",null,[(0,s._)("a",{href:"".concat(a.SERVER_URL,"/oidc/login"),class:"max-w-lg mx-auto w-full flex justify-center py-3 px-4 border border-green-800 rounded-md shadow-lg text-sm text-white bg-green-700 hover:bg-green-800"}," Login with OIDC ",8,I)])])])):(0,s.kq)("",!0),(0,s.Wm)(E,{result:a.tooltip.result,event:a.tooltip.event},null,8,["result","event"]),(0,s.Wm)(B)],64)}n(1539);var C=function(e){return(0,s.dD)("data-v-a4b3d200"),e=e(),(0,s.Cn)(),e},S={id:"social"},E=C((function(){return(0,s._)("a",{href:"https://github.com/TwiN/gatus",target:"_blank",title:"Gatus on GitHub"},[(0,s._)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"32",height:"32",viewBox:"0 0 16 16",class:"hover:scale-110"},[(0,s._)("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)})),B=[E];function P(e,t,n,o,r,a){return(0,s.wg)(),(0,s.iD)("div",S,B)}var H={name:"Social"},U=n(3744);const O=(0,U.Z)(H,[["render",P],["__scopeId","data-v-a4b3d200"]]);var z=O,M=(n(6977),(0,s._)("div",{class:"tooltip-title"},"Timestamp:",-1)),Q={id:"tooltip-timestamp"},W=(0,s._)("div",{class:"tooltip-title"},"Response time:",-1),q={id:"tooltip-response-time"},X=(0,s._)("div",{class:"tooltip-title"},"Conditions:",-1),Y={id:"tooltip-conditions"},K=(0,s._)("br",null,null,-1),G={key:0,id:"tooltip-errors-container"},F=(0,s._)("div",{class:"tooltip-title"},"Errors:",-1),j={id:"tooltip-errors"},L=(0,s._)("br",null,null,-1);function Z(e,t,n,o,a,i){return(0,s.wg)(),(0,s.iD)("div",{id:"tooltip",ref:"toLine truncated
|
|
||||||
@@ -1 +1 @@
|
|||||||
(function(){"use strict";var e={5034:function(e,t,s){s.d(t,{L:function(){return ms}});s(7727);var n=s(9963),o=s(6252),a=s(3577),r=s(9574);const i={class:"mb-2"},l={class:"flex flex-wrap"},g={class:"w-3/4 text-left my-auto"},d={class:"text-3xl xl:text-5xl lg:text-4xl font-light"},h={class:"w-1/4 flex justify-end"},u=["href"],c=["src"],p={key:1,src:r,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},m={key:0,class:"flex flex-wrap"},A=["href"],f={key:2,class:"mx-auto max-w-md pt-12"},v=(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:"mt-8 py-7 px-4 rounded-sm sm:bg-gray-100 sm:border sm:border-gray-300 sm:shadow-2xl sm:px-10"},y=(0,o._)("div",{class:"sm:mx-auto sm:w-full"},[(0,o._)("h2",{class:"mb-4 text-center text-xl font-bold text-gray-600 dark:text-gray-200 dark:sm:text-gray-600"}," Sign in ")],-1),k={key:0,class:"text-red-500 text-center my-2"},T={class:"text-xl"},b={key:0,class:"text-red-500"},R={key:1,class:"text-red-500"},I=["href"];function D(e,t,s,n,r,D){const C=(0,o.up)("Loading"),S=(0,o.up)("router-view"),E=(0,o.up)("Tooltip"),B=(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",g,[(0,o._)("div",d,(0,a.zw)(D.header),1)]),(0,o._)("div",h,[(0,o._)("a",{href:D.link,target:"_blank",style:{width:"100px"}},[D.logo?((0,o.wg)(),(0,o.iD)("img",{key:0,src:D.logo,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},null,8,c)):((0,o.wg)(),(0,o.iD)("img",p))],8,u)])]),D.buttons?((0,o.wg)(),(0,o.iD)("div",m,[((0,o.wg)(!0),(0,o.iD)(o.HY,null,(0,o.Ko)(D.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,A)))),128))])):(0,o.kq)("",!0)]),(0,o.Wm)(S,{onShowTooltip:D.showTooltip},null,8,["onShowTooltip"])],2)):((0,o.wg)(),(0,o.j4)(C,{key:0,class:"h-64 w-64 px-4"})),r.config&&r.config.oidc&&!r.config.authenticated?((0,o.wg)(),(0,o.iD)("div",f,[v,w,(0,o._)("div",x,[y,e.$route&&e.$route.query.error?((0,o.wg)(),(0,o.iD)("div",k,[(0,o._)("div",T,["access_denied"===e.$route.query.error?((0,o.wg)(),(0,o.iD)("span",b,"You do not have access to this status page")):((0,o.wg)(),(0,o.iD)("span",R,(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 hover:bg-green-800"}," Login with OIDC ",8,I)])])])):(0,o.kq)("",!0),(0,o.Wm)(E,{result:r.tooltip.result,event:r.tooltip.event},null,8,["result","event"]),(0,o.Wm)(B)],64)}const C=e=>((0,o.dD)("data-v-a4b3d200"),e=e(),(0,o.Cn)(),e),S={id:"social"},E=C((()=>(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))),B=[E];function P(e,t,s,n,a,r){return(0,o.wg)(),(0,o.iD)("div",S,B)}var H={name:"Social"},U=s(3744);const O=(0,U.Z)(H,[["render",P],["__scopeId","data-v-a4b3d200"]]);var z=O;const M=(0,o._)("div",{class:"tooltip-title"},"Timestamp:",-1),Q={id:"tooltip-timestamp"},W=(0,o._)("div",{class:"tooltip-title"},"Response time:",-1),q={id:"tooltip-response-time"},X=(0,o._)("div",{class:"tooltip-title"},"Conditions:",-1),Y={id:"tooltip-conditions"},K=(0,o._)("br",null,null,-1),G={key:0,id:"tooltip-errors-container"},F=(0,o._)("div",{class:"tooltip-title"},"Errors:",-1),j={id:"tooltip-errors"},L=(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+"Line truncated
|
(function(){"use strict";var e={9928:function(e,t,s){s.d(t,{L:function(){return ms}});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"},g={class:"w-3/4 text-left my-auto"},d={class:"text-3xl xl:text-5xl lg:text-4xl font-light"},h={class:"w-1/4 flex justify-end"},u=["href"],c=["src"],p={key:1,src:r,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},m={key:0,class:"flex flex-wrap"},A=["href"],f={key:2,class:"mx-auto max-w-md pt-12"},v=(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:"mt-8 py-7 px-4 rounded-sm sm:bg-gray-100 sm:border sm:border-gray-300 sm:shadow-2xl sm:px-10"},y=(0,o._)("div",{class:"sm:mx-auto sm:w-full"},[(0,o._)("h2",{class:"mb-4 text-center text-xl font-bold text-gray-600 dark:text-gray-200 dark:sm:text-gray-600"}," Sign in ")],-1),k={key:0,class:"text-red-500 text-center my-2"},T={class:"text-xl"},b={key:0,class:"text-red-500"},R={key:1,class:"text-red-500"},I=["href"];function D(e,t,s,n,r,D){const C=(0,o.up)("Loading"),S=(0,o.up)("router-view"),E=(0,o.up)("Tooltip"),B=(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",g,[(0,o._)("div",d,(0,a.zw)(D.header),1)]),(0,o._)("div",h,[(0,o._)("a",{href:D.link,target:"_blank",style:{width:"100px"}},[D.logo?((0,o.wg)(),(0,o.iD)("img",{key:0,src:D.logo,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}},null,8,c)):((0,o.wg)(),(0,o.iD)("img",p))],8,u)])]),D.buttons?((0,o.wg)(),(0,o.iD)("div",m,[((0,o.wg)(!0),(0,o.iD)(o.HY,null,(0,o.Ko)(D.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,A)))),128))])):(0,o.kq)("",!0)]),(0,o.Wm)(S,{onShowTooltip:D.showTooltip},null,8,["onShowTooltip"])],2)):((0,o.wg)(),(0,o.j4)(C,{key:0,class:"h-64 w-64 px-4"})),r.config&&r.config.oidc&&!r.config.authenticated?((0,o.wg)(),(0,o.iD)("div",f,[v,w,(0,o._)("div",x,[y,e.$route&&e.$route.query.error?((0,o.wg)(),(0,o.iD)("div",k,[(0,o._)("div",T,["access_denied"===e.$route.query.error?((0,o.wg)(),(0,o.iD)("span",b,"You do not have access to this status page")):((0,o.wg)(),(0,o.iD)("span",R,(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 hover:bg-green-800"}," Login with OIDC ",8,I)])])])):(0,o.kq)("",!0),(0,o.Wm)(E,{result:r.tooltip.result,event:r.tooltip.event},null,8,["result","event"]),(0,o.Wm)(B)],64)}const C=e=>((0,o.dD)("data-v-a4b3d200"),e=e(),(0,o.Cn)(),e),S={id:"social"},E=C((()=>(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))),B=[E];function P(e,t,s,n,a,r){return(0,o.wg)(),(0,o.iD)("div",S,B)}var H={name:"Social"},U=s(3744);const O=(0,U.Z)(H,[["render",P],["__scopeId","data-v-a4b3d200"]]);var z=O;const M=(0,o._)("div",{class:"tooltip-title"},"Timestamp:",-1),Q={id:"tooltip-timestamp"},W=(0,o._)("div",{class:"tooltip-title"},"Response time:",-1),q={id:"tooltip-response-time"},X=(0,o._)("div",{class:"tooltip-title"},"Conditions:",-1),Y={id:"tooltip-conditions"},K=(0,o._)("br",null,null,-1),G={key:0,id:"tooltip-errors-container"},F=(0,o._)("div",{class:"tooltip-title"},"Errors:",-1),j={id:"tooltip-errors"},L=(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; leftLine truncated
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
(self["webpackChunkgatus"]=self["webpackChunkgatus"]||[]).push([[998],{2262:function(t,e,n){"use strict";n.d(e,{Bj:function(){return i},qq:function(){return b},Fl:function(){return Gt},X3:function(){return Ct},PG:function(){return kt},dq:function(){return Ft},yT:function(){return Ot},Xl:function(){return At},Jd:function(){return S},WL:function(){return Jt},qj:function(){return xt},iH:function(){return Nt},lk:function(){return k},Um:function(){return _t},XI:function(){return Mt},IU:function(){return Rt},j:function(){return E},X$:function(){return C},SU:function(){return Lt}});var r=n(3577);let o;class i{constructor(t=!1){this.active=!0,this.effects=[],this.cleanups=[],!t&&o&&(this.parent=o,this.index=(o.scopes||(o.scopes=[])).push(this)-1)}run(t){if(this.active){const e=o;try{return o=this,t()}finally{o=e}}else 0}on(){o=this}off(){o=this.parent}stop(t){if(this.active){let e,n;for(e=0,n=this.effects.length;e<n;e++)this.effects[e].stop();for(e=0,n=this.cleanups.length;e<n;e++)this.cleanups[e]();if(this.scopes)for(e=0,n=this.scopes.length;e<n;e++)this.scopes[e].stop(!0);if(this.parent&&!t){const t=this.parent.scopes.pop();t&&t!==this&&(this.parent.scopes[this.index]=t,t.index=this.index)}this.active=!1}}}function c(t,e=o){e&&e.active&&e.effects.push(t)}const s=t=>{const e=new Set(t);return e.w=0,e.n=0,e},u=t=>(t.w&h)>0,a=t=>(t.n&h)>0,l=({deps:t})=>{if(t.length)for(let e=0;e<t.length;e++)t[e].w|=h},f=t=>{const{deps:e}=t;if(e.length){let n=0;for(let r=0;r<e.length;r++){const o=e[r];u(o)&&!a(o)?o.delete(t):e[n++]=o,o.w&=~h,o.n&=~h}e.length=n}},p=new WeakMap;let d=0,h=1;const v=30;let g;const m=Symbol(""),y=Symbol("");class b{constructor(t,e=null,n){this.fn=t,this.scheduler=e,this.active=!0,this.deps=[],this.parent=void 0,c(this,n)}run(){if(!this.active)return this.fn();let t=g,e=_;while(t){if(t===this)return;t=t.parent}try{return this.parent=g,g=this,_=!0,h=1<<++d,d<=v?l(this):x(this),this.fn()}finally{d<=v&&f(this),h=1<<--d,g=this.parent,_=e,this.parent=void 0,this.deferStop&&this.stop()}}stop(){g===this?this.deferStop=!0:this.active&&(x(this),this.onStop&&this.onStop(),this.active=!1)}}function x(t){const{deps:e}=t;if(e.length){for(let n=0;n<e.length;n++)e[n].delete(t);e.length=0}}let _=!0;const w=[];function S(){w.push(_),_=!1}function k(){const t=w.pop();_=void 0===t||t}function E(t,e,n){if(_&&g){let e=p.get(t);e||p.set(t,e=new Map);let r=e.get(n);r||e.set(n,r=s());const o=void 0;O(r,o)}}function O(t,e){let n=!1;d<=v?a(t)||(t.n|=h,n=!u(t)):n=!t.has(g),n&&(t.add(g),g.deps.push(t))}function C(t,e,n,o,i,c){const u=p.get(t);if(!u)return;let a=[];if("clear"===e)a=[...u.values()];else if("length"===n&&(0,r.kJ)(t))u.forEach(((t,e)=>{("length"===e||e>=o)&&a.push(t)}));else switch(void 0!==n&&a.push(u.get(n)),e){case"add":(0,r.kJ)(t)?(0,r.S0)(n)&&a.push(u.get("length")):(a.push(u.get(m)),(0,r._N)(t)&&a.push(u.get(y)));break;case"delete":(0,r.kJ)(t)||(a.push(u.get(m)),(0,r._N)(t)&&a.push(u.get(y)));break;case"set":(0,r._N)(t)&&a.push(u.get(m));break}if(1===a.length)a[0]&&R(a[0]);else{const t=[];for(const e of a)e&&t.push(...e);R(s(t))}}function R(t,e){const n=(0,r.kJ)(t)?t:[...t];for(const r of n)r.computed&&A(r,e);for(const r of n)r.computed||A(r,e)}function A(t,e){(t!==g||t.allowRecurse)&&(t.scheduler?t.scheduler():t.run())}const I=(0,r.fY)("__proto__,__v_isRef,__isVue"),j=new Set(Object.getOwnPropertyNames(Symbol).filter((t=>"arguments"!==t&&"caller"!==t)).map((t=>Symbol[t])).filter(r.yk)),T=$(),P=$(!1,!0),F=$(!0),N=M();function M(){const t={};return["includes","indexOf","lastIndexOf"].forEach((e=>{t[e]=function(...t){const n=Rt(this);for(let e=0,o=this.length;e<o;e++)E(n,"get",e+"");const r=n[e](...t);return-1===r||!1===r?n[e](...t.map(Rt)):r}})),["push","pop","shift","unshift","splice"].forEach((e=>{t[e]=function(...t){S();const n=Rt(this)[e].apply(this,t);return k(),n}})),t}function $(t=!1,e=!1){return function(n,o,i){if("__v_isReactive"===o)return!t;if("__v_isReadonly"===o)return t;if("__v_isShallow"===o)return e;if("__v_raw"===o&&i===(t?e?mt:gt:e?vt:ht).get(n))return n;const c=(0,r.kJ)(n);if(!t&&c&&(0,r.RI)(N,o))return Reflect.get(N,o,i);const s=Reflect.get(n,o,i);return((0,r.yk)(o)?j.has(o):I(o))?s:(t||E(n,"get",o),e?s:Ft(s)?c&&(0,r.S0)(o)?s:s.value:(0,r.Kn)(s)?t?wt(s):xt(s):s)}}const U=D(),L=D(!0);function D(t=!1){return function(e,n,o,i){let c=e[n];if(Et(c)&&Ft(c)&&!Ft(o))return!1;if(!t&&!Et(o)&&(Ot(o)||(o=Rt(o),c=Rt(c)),!(0,r.kJ)(e)&&Ft(c)&&!Ft(o)))return c.value=o,!0;const s=(0,r.kJ)(e)&&(0,r.S0)(n)?Number(n)<e.length:(0,r.RI)(e,n),u=Reflect.set(e,n,o,i);return e===Rt(i)&&(s?(0,r.aU)(o,c)&&C(e,"set",n,o,c):C(e,"add",n,o)),u}}function J(t,e){const n=(0,r.RI)(t,e),o=t[e],i=Reflect.deleteProperty(t,e);return i&&n&&C(t,"delete",e,void 0,o),i}function B(t,e){const n=Reflect.has(t,e);return(0,r.yk)(e)&&j.has(e)||E(t,"has",e),n}function G(t){return E(t,"iterate",(0,r.kJ)(t)?"length":m),Reflect.ownKeys(t)}const q={get:T,set:U,deleteProperty:J,has:B,ownKeys:G},V={get:F,set(t,e){return!0},deleteProperty(t,e){return!Line truncated
|
|
||||||
/*!
|
|
||||||
* vue-router v4.0.16
|
|
||||||
* (c) 2022 Eduardo San Martin Morote
|
|
||||||
* @license MIT
|
|
||||||
*/
|
|
||||||
const i="function"===typeof Symbol&&"symbol"===typeof Symbol.toStringTag,c=t=>i?Symbol(t):"_vr_"+t,s=c("rvlm"),u=c("rvd"),a=c("r"),l=c("rl"),f=c("rvl"),p="undefined"!==typeof window;function d(t){return t.__esModule||i&&"Module"===t[Symbol.toStringTag]}const h=Object.assign;function v(t,e){const n={};for(const r in e){const o=e[r];n[r]=Array.isArray(o)?o.map(t):t(o)}return n}const g=()=>{};const m=/\/$/,y=t=>t.replace(m,"");function b(t,e,n="/"){let r,o={},i="",c="";const s=e.indexOf("?"),u=e.indexOf("#",s>-1?s:0);return s>-1&&(r=e.slice(0,s),i=e.slice(s+1,u>-1?u:e.length),o=t(i)),u>-1&&(r=r||e.slice(0,u),c=e.slice(u,e.length)),r=C(null!=r?r:e,n),{fullPath:r+(i&&"?")+i+c,path:r,query:o,hash:c}}function x(t,e){const n=e.query?t(e.query):"";return e.path+(n&&"?")+n+(e.hash||"")}function _(t,e){return e&&t.toLowerCase().startsWith(e.toLowerCase())?t.slice(e.length)||"/":t}function w(t,e,n){const r=e.matched.length-1,o=n.matched.length-1;return r>-1&&r===o&&S(e.matched[r],n.matched[o])&&k(e.params,n.params)&&t(e.query)===t(n.query)&&e.hash===n.hash}function S(t,e){return(t.aliasOf||t)===(e.aliasOf||e)}function k(t,e){if(Object.keys(t).length!==Object.keys(e).length)return!1;for(const n in t)if(!E(t[n],e[n]))return!1;return!0}function E(t,e){return Array.isArray(t)?O(t,e):Array.isArray(e)?O(e,t):t===e}function O(t,e){return Array.isArray(e)?t.length===e.length&&t.every(((t,n)=>t===e[n])):1===t.length&&t[0]===e}function C(t,e){if(t.startsWith("/"))return t;if(!t)return e;const n=e.split("/"),r=t.split("/");let o,i,c=n.length-1;for(o=0;o<r.length;o++)if(i=r[o],1!==c&&"."!==i){if(".."!==i)break;c--}return n.slice(0,c).join("/")+"/"+r.slice(o-(o===r.length?1:0)).join("/")}var R,A;(function(t){t["pop"]="pop",t["push"]="push"})(R||(R={})),function(t){t["back"]="back",t["forward"]="forward",t["unknown"]=""}(A||(A={}));function I(t){if(!t)if(p){const e=document.querySelector("base");t=e&&e.getAttribute("href")||"/",t=t.replace(/^\w+:\/\/[^\/]+/,"")}else t="/";return"/"!==t[0]&&"#"!==t[0]&&(t="/"+t),y(t)}const j=/^[^#]+#/;function T(t,e){return t.replace(j,"#")+e}function P(t,e){const n=document.documentElement.getBoundingClientRect(),r=t.getBoundingClientRect();return{behavior:e.behavior,left:r.left-n.left-(e.left||0),top:r.top-n.top-(e.top||0)}}const F=()=>({left:window.pageXOffset,top:window.pageYOffset});function N(t){let e;if("el"in t){const n=t.el,r="string"===typeof n&&n.startsWith("#");0;const o="string"===typeof n?r?document.getElementById(n.slice(1)):document.querySelector(n):n;if(!o)return;e=P(o,t)}else e=t;"scrollBehavior"in document.documentElement.style?window.scrollTo(e):window.scrollTo(null!=e.left?e.left:window.pageXOffset,null!=e.top?e.top:window.pageYOffset)}function M(t,e){const n=history.state?history.state.position-e:-1;return n+t}const $=new Map;function U(t,e){$.set(t,e)}function L(t){const e=$.get(t);return $.delete(t),e}let D=()=>location.protocol+"//"+location.host;function J(t,e){const{pathname:n,search:r,hash:o}=e,i=t.indexOf("#");if(i>-1){let e=o.includes(t.slice(i))?t.slice(i).length:1,n=o.slice(e);return"/"!==n[0]&&(n="/"+n),_(n,"")}const c=_(n,t);return c+r+o}function B(t,e,n,r){let o=[],i=[],c=null;const s=({state:i})=>{const s=J(t,location),u=n.value,a=e.value;let l=0;if(i){if(n.value=s,e.value=i,c&&c===u)return void(c=null);l=a?i.position-a.position:0}else r(s);o.forEach((t=>{t(n.value,u,{delta:l,type:R.pop,direction:l?l>0?A.forward:A.back:A.unknown})}))};function u(){c=n.value}function a(t){o.push(t);const e=()=>{const e=o.indexOf(t);e>-1&&o.splice(e,1)};return i.push(e),e}function l(){const{history:t}=window;t.state&&t.replaceState(h({},t.state,{scroll:F()}),"")}function f(){for(const t of i)t();i=[],window.removeEventListener("popstate",s),window.removeEventListener("beforeunload",l)}return window.addEventListener("popstate",s),window.addEventListener("beforeunload",l),{pauseListeners:u,listen:a,destroy:f}}function G(t,e,n,r=!1,o=!1){return{back:t,current:e,forward:n,replaced:r,position:window.history.length,scroll:o?F():null}}function q(t){const{history:e,location:n}=window,r={value:J(t,n)},o={value:e.state};function i(r,i,c){const s=t.indexOf("#"),u=s>-1?(n.host&&document.querySelector("base")?t:t.slice(s))+r:D()+t+r;try{e[c?"replaceState":"pushState"](i,"",u),o.value=i}catch(a){console.error(a),n[c?"replace":"assign"](u)}}function c(t,n){const c=h({},e.state,G(o.value.back,t,o.value.forward,!0),n,{position:o.value.position});i(t,c,!0),r.value=t}function s(t,n){const c=h({},o.value,e.state,{forward:t,scroll:F()});i(c.current,c,!0);const s=h({},G(r.value,t,null),{position:c.position+1},n);i(t,s,!1),r.value=t}return o.value||i(r.value,{back:null,current:r.value,forward:null,position:e.length-1,replaced:!0,scroll:null},!0),{location:r,state:o,push:s,replace:c}}function V(t){t=I(t);const e=q(t),n=B(t,e.state,e.location,e.replace);function r(t,e=!0){e||n.pauseListeners(),history.go(t)}const o=h({location:"",base:t,go:r,createHref:T.bind(null,t)},e,n);return Object.defineProperty(o,"loLine truncated
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
(self["webpackChunkgatus"]=self["webpackChunkgatus"]||[]).push([[998],{2262:function(e,t,n){"use strict";n.d(t,{Bj:function(){return i},qq:function(){return b},Fl:function(){return Ge},X3:function(){return Ee},PG:function(){return Se},dq:function(){return Fe},yT:function(){return Oe},Xl:function(){return Ae},Jd:function(){return k},WL:function(){return Je},qj:function(){return _e},iH:function(){return Le},lk:function(){return S},Um:function(){return xe},XI:function(){return Me},IU:function(){return Re},j:function(){return C},X$:function(){return E},SU:function(){return Ue}});var r=n(3577);let o;class i{constructor(e=!1){this.active=!0,this.effects=[],this.cleanups=[],!e&&o&&(this.parent=o,this.index=(o.scopes||(o.scopes=[])).push(this)-1)}run(e){if(this.active){const t=o;try{return o=this,e()}finally{o=t}}else 0}on(){o=this}off(){o=this.parent}stop(e){if(this.active){let t,n;for(t=0,n=this.effects.length;t<n;t++)this.effects[t].stop();for(t=0,n=this.cleanups.length;t<n;t++)this.cleanups[t]();if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].stop(!0);if(this.parent&&!e){const e=this.parent.scopes.pop();e&&e!==this&&(this.parent.scopes[this.index]=e,e.index=this.index)}this.active=!1}}}function s(e,t=o){t&&t.active&&t.effects.push(e)}const c=e=>{const t=new Set(e);return t.w=0,t.n=0,t},u=e=>(e.w&h)>0,l=e=>(e.n&h)>0,a=({deps:e})=>{if(e.length)for(let t=0;t<e.length;t++)e[t].w|=h},f=e=>{const{deps:t}=e;if(t.length){let n=0;for(let r=0;r<t.length;r++){const o=t[r];u(o)&&!l(o)?o.delete(e):t[n++]=o,o.w&=~h,o.n&=~h}t.length=n}},p=new WeakMap;let d=0,h=1;const v=30;let g;const m=Symbol(""),y=Symbol("");class b{constructor(e,t=null,n){this.fn=e,this.scheduler=t,this.active=!0,this.deps=[],this.parent=void 0,s(this,n)}run(){if(!this.active)return this.fn();let e=g,t=x;while(e){if(e===this)return;e=e.parent}try{return this.parent=g,g=this,x=!0,h=1<<++d,d<=v?a(this):_(this),this.fn()}finally{d<=v&&f(this),h=1<<--d,g=this.parent,x=t,this.parent=void 0,this.deferStop&&this.stop()}}stop(){g===this?this.deferStop=!0:this.active&&(_(this),this.onStop&&this.onStop(),this.active=!1)}}function _(e){const{deps:t}=e;if(t.length){for(let n=0;n<t.length;n++)t[n].delete(e);t.length=0}}let x=!0;const w=[];function k(){w.push(x),x=!1}function S(){const e=w.pop();x=void 0===e||e}function C(e,t,n){if(x&&g){let t=p.get(e);t||p.set(e,t=new Map);let r=t.get(n);r||t.set(n,r=c());const o=void 0;O(r,o)}}function O(e,t){let n=!1;d<=v?l(e)||(e.n|=h,n=!u(e)):n=!e.has(g),n&&(e.add(g),g.deps.push(e))}function E(e,t,n,o,i,s){const u=p.get(e);if(!u)return;let l=[];if("clear"===t)l=[...u.values()];else if("length"===n&&(0,r.kJ)(e))u.forEach(((e,t)=>{("length"===t||t>=o)&&l.push(e)}));else switch(void 0!==n&&l.push(u.get(n)),t){case"add":(0,r.kJ)(e)?(0,r.S0)(n)&&l.push(u.get("length")):(l.push(u.get(m)),(0,r._N)(e)&&l.push(u.get(y)));break;case"delete":(0,r.kJ)(e)||(l.push(u.get(m)),(0,r._N)(e)&&l.push(u.get(y)));break;case"set":(0,r._N)(e)&&l.push(u.get(m));break}if(1===l.length)l[0]&&R(l[0]);else{const e=[];for(const t of l)t&&e.push(...t);R(c(e))}}function R(e,t){const n=(0,r.kJ)(e)?e:[...e];for(const r of n)r.computed&&A(r,t);for(const r of n)r.computed||A(r,t)}function A(e,t){(e!==g||e.allowRecurse)&&(e.scheduler?e.scheduler():e.run())}const I=(0,r.fY)("__proto__,__v_isRef,__isVue"),P=new Set(Object.getOwnPropertyNames(Symbol).filter((e=>"arguments"!==e&&"caller"!==e)).map((e=>Symbol[e])).filter(r.yk)),T=$(),j=$(!1,!0),F=$(!0),L=M();function M(){const e={};return["includes","indexOf","lastIndexOf"].forEach((t=>{e[t]=function(...e){const n=Re(this);for(let t=0,o=this.length;t<o;t++)C(n,"get",t+"");const r=n[t](...e);return-1===r||!1===r?n[t](...e.map(Re)):r}})),["push","pop","shift","unshift","splice"].forEach((t=>{e[t]=function(...e){k();const n=Re(this)[t].apply(this,e);return S(),n}})),e}function $(e=!1,t=!1){return function(n,o,i){if("__v_isReactive"===o)return!e;if("__v_isReadonly"===o)return e;if("__v_isShallow"===o)return t;if("__v_raw"===o&&i===(e?t?me:ge:t?ve:he).get(n))return n;const s=(0,r.kJ)(n);if(!e&&s&&(0,r.RI)(L,o))return Reflect.get(L,o,i);const c=Reflect.get(n,o,i);return((0,r.yk)(o)?P.has(o):I(o))?c:(e||C(n,"get",o),t?c:Fe(c)?s&&(0,r.S0)(o)?c:c.value:(0,r.Kn)(c)?e?we(c):_e(c):c)}}const N=D(),U=D(!0);function D(e=!1){return function(t,n,o,i){let s=t[n];if(Ce(s)&&Fe(s)&&!Fe(o))return!1;if(!e&&!Ce(o)&&(Oe(o)||(o=Re(o),s=Re(s)),!(0,r.kJ)(t)&&Fe(s)&&!Fe(o)))return s.value=o,!0;const c=(0,r.kJ)(t)&&(0,r.S0)(n)?Number(n)<t.length:(0,r.RI)(t,n),u=Reflect.set(t,n,o,i);return t===Re(i)&&(c?(0,r.aU)(o,s)&&E(t,"set",n,o,s):E(t,"add",n,o)),u}}function J(e,t){const n=(0,r.RI)(e,t),o=e[t],i=Reflect.deleteProperty(e,t);return i&&n&&E(e,"delete",t,void 0,o),i}function B(e,t){const n=Reflect.has(e,t);return(0,r.yk)(t)&&P.has(t)||C(e,"has",t),n}function G(e){return C(e,"iterate",(0,r.kJ)(e)?"length":m),Reflect.ownKeys(e)}const V={get:T,set:N,deleteProperty:J,has:B,ownKeys:G},q={get:F,set(e,t){return!0},deleteProperty(e,t){return!Line truncated
|
(self["webpackChunkgatus"]=self["webpackChunkgatus"]||[]).push([[998],{2262:function(e,t,n){"use strict";n.d(t,{Bj:function(){return i},Fl:function(){return Ge},IU:function(){return Re},Jd:function(){return k},PG:function(){return Se},SU:function(){return Ue},Um:function(){return xe},WL:function(){return Je},X$:function(){return E},X3:function(){return Ee},XI:function(){return Me},Xl:function(){return Ae},dq:function(){return Fe},iH:function(){return Le},j:function(){return C},lk:function(){return S},qj:function(){return _e},qq:function(){return b},yT:function(){return Oe}});var r=n(3577);let o;class i{constructor(e=!1){this.active=!0,this.effects=[],this.cleanups=[],!e&&o&&(this.parent=o,this.index=(o.scopes||(o.scopes=[])).push(this)-1)}run(e){if(this.active){const t=o;try{return o=this,e()}finally{o=t}}else 0}on(){o=this}off(){o=this.parent}stop(e){if(this.active){let t,n;for(t=0,n=this.effects.length;t<n;t++)this.effects[t].stop();for(t=0,n=this.cleanups.length;t<n;t++)this.cleanups[t]();if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].stop(!0);if(this.parent&&!e){const e=this.parent.scopes.pop();e&&e!==this&&(this.parent.scopes[this.index]=e,e.index=this.index)}this.active=!1}}}function s(e,t=o){t&&t.active&&t.effects.push(e)}const c=e=>{const t=new Set(e);return t.w=0,t.n=0,t},u=e=>(e.w&h)>0,l=e=>(e.n&h)>0,a=({deps:e})=>{if(e.length)for(let t=0;t<e.length;t++)e[t].w|=h},f=e=>{const{deps:t}=e;if(t.length){let n=0;for(let r=0;r<t.length;r++){const o=t[r];u(o)&&!l(o)?o.delete(e):t[n++]=o,o.w&=~h,o.n&=~h}t.length=n}},p=new WeakMap;let d=0,h=1;const v=30;let g;const m=Symbol(""),y=Symbol("");class b{constructor(e,t=null,n){this.fn=e,this.scheduler=t,this.active=!0,this.deps=[],this.parent=void 0,s(this,n)}run(){if(!this.active)return this.fn();let e=g,t=x;while(e){if(e===this)return;e=e.parent}try{return this.parent=g,g=this,x=!0,h=1<<++d,d<=v?a(this):_(this),this.fn()}finally{d<=v&&f(this),h=1<<--d,g=this.parent,x=t,this.parent=void 0,this.deferStop&&this.stop()}}stop(){g===this?this.deferStop=!0:this.active&&(_(this),this.onStop&&this.onStop(),this.active=!1)}}function _(e){const{deps:t}=e;if(t.length){for(let n=0;n<t.length;n++)t[n].delete(e);t.length=0}}let x=!0;const w=[];function k(){w.push(x),x=!1}function S(){const e=w.pop();x=void 0===e||e}function C(e,t,n){if(x&&g){let t=p.get(e);t||p.set(e,t=new Map);let r=t.get(n);r||t.set(n,r=c());const o=void 0;O(r,o)}}function O(e,t){let n=!1;d<=v?l(e)||(e.n|=h,n=!u(e)):n=!e.has(g),n&&(e.add(g),g.deps.push(e))}function E(e,t,n,o,i,s){const u=p.get(e);if(!u)return;let l=[];if("clear"===t)l=[...u.values()];else if("length"===n&&(0,r.kJ)(e))u.forEach(((e,t)=>{("length"===t||t>=o)&&l.push(e)}));else switch(void 0!==n&&l.push(u.get(n)),t){case"add":(0,r.kJ)(e)?(0,r.S0)(n)&&l.push(u.get("length")):(l.push(u.get(m)),(0,r._N)(e)&&l.push(u.get(y)));break;case"delete":(0,r.kJ)(e)||(l.push(u.get(m)),(0,r._N)(e)&&l.push(u.get(y)));break;case"set":(0,r._N)(e)&&l.push(u.get(m));break}if(1===l.length)l[0]&&R(l[0]);else{const e=[];for(const t of l)t&&e.push(...t);R(c(e))}}function R(e,t){const n=(0,r.kJ)(e)?e:[...e];for(const r of n)r.computed&&A(r,t);for(const r of n)r.computed||A(r,t)}function A(e,t){(e!==g||e.allowRecurse)&&(e.scheduler?e.scheduler():e.run())}const I=(0,r.fY)("__proto__,__v_isRef,__isVue"),P=new Set(Object.getOwnPropertyNames(Symbol).filter((e=>"arguments"!==e&&"caller"!==e)).map((e=>Symbol[e])).filter(r.yk)),T=$(),j=$(!1,!0),F=$(!0),L=M();function M(){const e={};return["includes","indexOf","lastIndexOf"].forEach((t=>{e[t]=function(...e){const n=Re(this);for(let t=0,o=this.length;t<o;t++)C(n,"get",t+"");const r=n[t](...e);return-1===r||!1===r?n[t](...e.map(Re)):r}})),["push","pop","shift","unshift","splice"].forEach((t=>{e[t]=function(...e){k();const n=Re(this)[t].apply(this,e);return S(),n}})),e}function $(e=!1,t=!1){return function(n,o,i){if("__v_isReactive"===o)return!e;if("__v_isReadonly"===o)return e;if("__v_isShallow"===o)return t;if("__v_raw"===o&&i===(e?t?me:ge:t?ve:he).get(n))return n;const s=(0,r.kJ)(n);if(!e&&s&&(0,r.RI)(L,o))return Reflect.get(L,o,i);const c=Reflect.get(n,o,i);return((0,r.yk)(o)?P.has(o):I(o))?c:(e||C(n,"get",o),t?c:Fe(c)?s&&(0,r.S0)(o)?c:c.value:(0,r.Kn)(c)?e?we(c):_e(c):c)}}const N=D(),U=D(!0);function D(e=!1){return function(t,n,o,i){let s=t[n];if(Ce(s)&&Fe(s)&&!Fe(o))return!1;if(!e&&!Ce(o)&&(Oe(o)||(o=Re(o),s=Re(s)),!(0,r.kJ)(t)&&Fe(s)&&!Fe(o)))return s.value=o,!0;const c=(0,r.kJ)(t)&&(0,r.S0)(n)?Number(n)<t.length:(0,r.RI)(t,n),u=Reflect.set(t,n,o,i);return t===Re(i)&&(c?(0,r.aU)(o,s)&&E(t,"set",n,o,s):E(t,"add",n,o)),u}}function J(e,t){const n=(0,r.RI)(e,t),o=e[t],i=Reflect.deleteProperty(e,t);return i&&n&&E(e,"delete",t,void 0,o),i}function B(e,t){const n=Reflect.has(e,t);return(0,r.yk)(t)&&P.has(t)||C(e,"has",t),n}function G(e){return C(e,"iterate",(0,r.kJ)(e)?"length":m),Reflect.ownKeys(e)}const V={get:T,set:N,deleteProperty:J,has:B,ownKeys:G},q={get:F,set(e,t){return!0},deleteProperty(e,t){return!Line truncated
|
||||||
/*!
|
/*!
|
||||||
* vue-router v4.0.16
|
* vue-router v4.0.16
|
||||||
* (c) 2022 Eduardo San Martin Morote
|
* (c) 2022 Eduardo San Martin Morote
|
||||||
|
|||||||
Reference in new issue
Block a user