Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd1430f043 | ||
|
|
79bef8d391 | ||
|
|
9196f57487 | ||
|
|
1e0d9e184c | ||
|
|
bc42497cb7 | ||
|
|
b0b0ab574d | ||
|
|
e369484e5f | ||
|
|
d18618449f | ||
|
|
9186049589 | ||
|
|
4362831f71 | ||
|
|
99f558d43e | ||
|
|
4a3d5944b6 | ||
|
|
688456d7cf | ||
|
|
431fb3e9f2 | ||
|
|
a1679ddc5e | ||
|
|
d8d8e8720b | ||
|
|
4a0d9d058a | ||
|
|
c8ccf9b352 | ||
|
|
45c966fbca | ||
|
|
d8d4756ef3 | ||
|
|
1e9c54cc0f | ||
|
|
80570688e1 | ||
|
|
43e6e3e8f5 | ||
|
|
8b4c5c20f3 | ||
|
|
6f6db36b0f | ||
|
|
467874de10 | ||
|
|
8337f41425 | ||
|
|
601d676e34 | ||
|
|
fbb5d48bf7 | ||
|
|
119b80edc0 | ||
|
|
99e8cfb1ce | ||
|
|
dcbbec7931 | ||
|
|
2ccd656386 | ||
|
|
5755f3a699 | ||
|
|
911d809376 | ||
|
|
752c872d3b | ||
|
|
67a3e4e330 | ||
|
|
668ed3b1a2 | ||
|
|
dc6cb8fc1d | ||
|
|
f1aa5191bf | ||
|
|
bc6ca2ebd0 | ||
|
|
30801938b2 | ||
|
|
ddddd405bb | ||
|
|
2207dd9c32 | ||
|
|
3204a79eb6 | ||
|
|
e9ac115a95 | ||
|
|
c90c786f39 | ||
|
|
f10e2ac639 | ||
|
|
c2d899f2a3 | ||
|
|
7415d8e361 | ||
|
|
298dcc4790 | ||
|
|
2f2890c093 | ||
|
|
e463aec5f6 | ||
|
|
6b3e11a47c | ||
|
|
0985e3bed8 | ||
|
|
6d8fd267de | ||
|
|
e89bb932ea | ||
|
|
77737dbab6 | ||
|
|
271c3dc91d | ||
|
|
5860a27ab5 | ||
|
|
819093cb7e |
No files matched your search
@@ -3,3 +3,4 @@ Dockerfile
|
|||||||
.github
|
.github
|
||||||
.idea
|
.idea
|
||||||
.git
|
.git
|
||||||
|
web/app
|
||||||
@@ -15,16 +15,18 @@ jobs:
|
|||||||
timeout-minutes: 5
|
timeout-minutes: 5
|
||||||
steps:
|
steps:
|
||||||
- name: Set up Go 1.15
|
- name: Set up Go 1.15
|
||||||
uses: actions/setup-go@v1
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
go-version: 1.15
|
go-version: 1.15
|
||||||
id: go
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
- name: Build binary to make sure it works
|
- name: Build binary to make sure it works
|
||||||
run: go build -mod vendor
|
run: go build -mod vendor
|
||||||
- name: Test
|
- name: Test
|
||||||
run: sudo go test -mod vendor ./... -race -coverprofile=coverage.txt -covermode=atomic
|
# We're using "sudo" because one of the tests leverages ping, which requires super-user privileges.
|
||||||
|
# As for the 'env "PATH=$PATH" "GOROOT=$GOROOT"', we need it to use the same "go" executable that
|
||||||
|
# was configured by the "Set up Go 1.15" step (otherwise, it'd use sudo's "go" executable)
|
||||||
|
run: sudo env "PATH=$PATH" "GOROOT=$GOROOT" go test -mod vendor ./... -race -coverprofile=coverage.txt -covermode=atomic
|
||||||
- name: Codecov
|
- name: Codecov
|
||||||
uses: codecov/codecov-action@v1.0.14
|
uses: codecov/codecov-action@v1.0.14
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
bin
|
|
||||||
.idea
|
.idea
|
||||||
.vscode
|
.vscode
|
||||||
gatus
|
gatus
|
||||||
@@ -13,7 +13,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -a -installsuffix cgo -o gatus
|
|||||||
FROM scratch
|
FROM scratch
|
||||||
COPY --from=builder /app/gatus .
|
COPY --from=builder /app/gatus .
|
||||||
COPY --from=builder /app/config.yaml ./config/config.yaml
|
COPY --from=builder /app/config.yaml ./config/config.yaml
|
||||||
COPY --from=builder /app/static static/
|
COPY --from=builder /app/web/static ./web/static
|
||||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||||
ENV PORT=8080
|
ENV PORT=8080
|
||||||
EXPOSE ${PORT}
|
EXPOSE ${PORT}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
docker-build:
|
||||||
|
docker build -t twinproduction/gatus:latest .
|
||||||
|
|
||||||
|
docker-build-and-run:
|
||||||
|
docker build -t twinproduction/gatus:latest . && docker run -p 8080:8080 --name gatus twinproduction/gatus:latest
|
||||||
|
|
||||||
|
build-frontend:
|
||||||
|
npm --prefix web/app run build
|
||||||
|
|
||||||
|
run-frontend:
|
||||||
|
npm --prefix web/app run serve
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test -mod=vendor ./... -cover
|
||||||
@@ -1,4 +1,4 @@
|
|||||||

|

|
||||||
|
|
||||||

|

|
||||||
[](https://goreportcard.com/report/github.com/TwinProduction/gatus)
|
[](https://goreportcard.com/report/github.com/TwinProduction/gatus)
|
||||||
@@ -58,7 +58,7 @@ The main features of Gatus are:
|
|||||||
- **Alerting**: While having a pretty visual dashboard is useful to keep track of the state of your application(s), you probably don't want to stare at it all day. Thus, notifications via Slack, Mattermost, Messagebird, PagerDuty and Twilio are supported out of the box with the ability to configure a custom alerting provider for any needs you might have, whether it be a different provider or a custom application that manages automated rollbacks.
|
- **Alerting**: While having a pretty visual dashboard is useful to keep track of the state of your application(s), you probably don't want to stare at it all day. Thus, notifications via Slack, Mattermost, Messagebird, PagerDuty and Twilio are supported out of the box with the ability to configure a custom alerting provider for any needs you might have, whether it be a different provider or a custom application that manages automated rollbacks.
|
||||||
- **Metrics**
|
- **Metrics**
|
||||||
- **Low resource consumption**: As with most Go applications, the resource footprint that this application requires is negligibly small.
|
- **Low resource consumption**: As with most Go applications, the resource footprint that this application requires is negligibly small.
|
||||||
- **GitHub uptime badges** (ALPHA):   
|
- **GitHub uptime badges**:   
|
||||||
- **Service auto discovery in Kubernetes** (ALPHA)
|
- **Service auto discovery in Kubernetes** (ALPHA)
|
||||||
|
|
||||||
|
|
||||||
@@ -100,6 +100,8 @@ Note that you can also add environment variables in the configuration file (i.e.
|
|||||||
|:---------------------------------------- |:----------------------------------------------------------------------------- |:-------------- |
|
|:---------------------------------------- |:----------------------------------------------------------------------------- |:-------------- |
|
||||||
| `debug` | Whether to enable debug logs | `false` |
|
| `debug` | Whether to enable debug logs | `false` |
|
||||||
| `metrics` | Whether to expose metrics at /metrics | `false` |
|
| `metrics` | Whether to expose metrics at /metrics | `false` |
|
||||||
|
| `storage` | Storage configuration | `{}` |
|
||||||
|
| `storage.file` | File to persist the data in. If not set, storage is in-memory only. | `""` |
|
||||||
| `services` | List of services to monitor | Required `[]` |
|
| `services` | List of services to monitor | Required `[]` |
|
||||||
| `services[].name` | Name of the service. Can be anything. | Required `""` |
|
| `services[].name` | Name of the service. Can be anything. | Required `""` |
|
||||||
| `services[].group` | Group name. Used to group multiple services together on the dashboard. See [Service groups](#service-groups). | `""` |
|
| `services[].group` | Group name. Used to group multiple services together on the dashboard. See [Service groups](#service-groups). | `""` |
|
||||||
@@ -151,7 +153,6 @@ Note that you can also add environment variables in the configuration file (i.e.
|
|||||||
| `web` | Web configuration | `{}` |
|
| `web` | Web configuration | `{}` |
|
||||||
| `web.address` | Address to listen on | `0.0.0.0` |
|
| `web.address` | Address to listen on | `0.0.0.0` |
|
||||||
| `web.port` | Port to listen on | `8080` |
|
| `web.port` | Port to listen on | `8080` |
|
||||||
| `web.context-root` | Context root at which Gatus will be exposed (frontend and backend) | `/` |
|
|
||||||
|
|
||||||
For Kubernetes configuration, see [Kubernetes](#kubernetes-alpha)
|
For Kubernetes configuration, see [Kubernetes](#kubernetes-alpha)
|
||||||
|
|
||||||
@@ -166,6 +167,7 @@ Here are some examples of conditions you can use:
|
|||||||
| `[STATUS] < 300` | Status must lower than 300 | 200, 201, 299 | 301, 302, ... |
|
| `[STATUS] < 300` | Status must lower than 300 | 200, 201, 299 | 301, 302, ... |
|
||||||
| `[STATUS] <= 299` | Status must be less than or equal to 299 | 200, 201, 299 | 301, 302, ... |
|
| `[STATUS] <= 299` | Status must be less than or equal to 299 | 200, 201, 299 | 301, 302, ... |
|
||||||
| `[STATUS] > 400` | Status must be greater than 400 | 401, 402, 403, 404 | 400, 200, ... |
|
| `[STATUS] > 400` | Status must be greater than 400 | 401, 402, 403, 404 | 400, 200, ... |
|
||||||
|
| `[STATUS] == any(200, 429)` | Status must be either 200 or 420 | 200, 429 | 201, 400, ... |
|
||||||
| `[CONNECTED] == true` | Connection to host must've been successful | true, false | |
|
| `[CONNECTED] == true` | Connection to host must've been successful | true, false | |
|
||||||
| `[RESPONSE_TIME] < 500` | Response time must be below 500ms | 100ms, 200ms, 300ms | 500ms, 501ms |
|
| `[RESPONSE_TIME] < 500` | Response time must be below 500ms | 100ms, 200ms, 300ms | 500ms, 501ms |
|
||||||
| `[IP] == 127.0.0.1` | Target IP must be 127.0.0.1 | 127.0.0.1 | 0.0.0.0 |
|
| `[IP] == 127.0.0.1` | Target IP must be 127.0.0.1 | 127.0.0.1 | 0.0.0.0 |
|
||||||
@@ -176,6 +178,7 @@ Here are some examples of conditions you can use:
|
|||||||
| `len([BODY].data) < 5` | Array at JSONPath `$.data` has less than 5 elements | `{"data":[{"id":1}]}` | |
|
| `len([BODY].data) < 5` | Array at JSONPath `$.data` has less than 5 elements | `{"data":[{"id":1}]}` | |
|
||||||
| `len([BODY].name) == 8` | String at JSONPath `$.name` has a length of 8 | `{"name":"john.doe"}` | `{"name":"bob"}` |
|
| `len([BODY].name) == 8` | String at JSONPath `$.name` has a length of 8 | `{"name":"john.doe"}` | `{"name":"bob"}` |
|
||||||
| `[BODY].name == pat(john*)` | String at JSONPath `$.name` matches pattern `john*` | `{"name":"john.doe"}` | `{"name":"bob"}` |
|
| `[BODY].name == pat(john*)` | String at JSONPath `$.name` matches pattern `john*` | `{"name":"john.doe"}` | `{"name":"bob"}` |
|
||||||
|
| `[BODY].id == any(1, 2)` | Value at JSONPath `$.id` is equal to `1` or `2` | 1, 2 | 3, 4, 5 |
|
||||||
| `[CERTIFICATE_EXPIRATION] > 48h` | Certificate expiration is more than 48h away | 49h, 50h, 123h | 1h, 24h, ... |
|
| `[CERTIFICATE_EXPIRATION] > 48h` | Certificate expiration is more than 48h away | 49h, 50h, 123h | 1h, 24h, ... |
|
||||||
|
|
||||||
|
|
||||||
@@ -198,6 +201,7 @@ Here are some examples of conditions you can use:
|
|||||||
|:-----------|:---------------------------------------------------------------------------------------------------------------- |:-------------------------- |
|
|:-----------|:---------------------------------------------------------------------------------------------------------------- |:-------------------------- |
|
||||||
| `len` | Returns the length of the object/slice. Works only with the `[BODY]` placeholder. | `len([BODY].username) > 8`
|
| `len` | Returns the length of the object/slice. Works only with the `[BODY]` placeholder. | `len([BODY].username) > 8`
|
||||||
| `pat` | Specifies that the string passed as parameter should be evaluated as a pattern. Works only with `==` and `!=`. | `[IP] == pat(192.168.*)`
|
| `pat` | Specifies that the string passed as parameter should be evaluated as a pattern. Works only with `==` and `!=`. | `[IP] == pat(192.168.*)`
|
||||||
|
| `any` | Specifies that any one of the values passed as parameters is a valid value. Works only with `==` and `!=`. | `[BODY].ip == any(127.0.0.1, ::1)`
|
||||||
|
|
||||||
**NOTE**: Use `pat` only when you need to. `[STATUS] == pat(2*)` is a lot more expensive than `[STATUS] < 300`.
|
**NOTE**: Use `pat` only when you need to. `[STATUS] == pat(2*)` is a lot more expensive than `[STATUS] < 300`.
|
||||||
|
|
||||||
@@ -705,11 +709,9 @@ web:
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Uptime badges
|
### Uptime badges
|
||||||

|

|
||||||

|

|
||||||

|

|
||||||
|
|
||||||
> **NOTE**: This feature is currently in ALPHA
|
|
||||||
|
|
||||||
Gatus can automatically generate a SVG badge for one of your monitored services.
|
Gatus can automatically generate a SVG badge for one of your monitored services.
|
||||||
This allows you to put badges in your individual services' README or even create your own status page, if you
|
This allows you to put badges in your individual services' README or even create your own status page, if you
|
||||||
@@ -721,21 +723,22 @@ The endpoint to generate a badge is the following:
|
|||||||
```
|
```
|
||||||
Where:
|
Where:
|
||||||
- `{duration}` is `7d`, `24h` or `1h`
|
- `{duration}` is `7d`, `24h` or `1h`
|
||||||
- `{identifier}` has the following pattern: `group-<GROUP_NAME>-service-<SERVICE_NAME>.svg`
|
- `{identifier}` has the pattern `<GROUP_NAME>_<SERVICE_NAME>.svg` in which both variables have ` `, `/`, `_`, `,` and `.` replaced by `-`.
|
||||||
|
|
||||||
For instance, if you want the uptime during the last 24 hours from the service `frontend` in the group `core`,
|
For instance, if you want the uptime during the last 24 hours from the service `frontend` in the group `core`,
|
||||||
the URL would look like this:
|
the URL would look like this:
|
||||||
```
|
```
|
||||||
http://example.com/api/v1/badges/uptime/7d/group-core-service-frontend.svg
|
http://example.com/api/v1/badges/uptime/7d/core_frontend.svg
|
||||||
```
|
```
|
||||||
|
|
||||||
If you want to display a service that is not part of a group, you must leave the group value empty:
|
If you want to display a service that is not part of a group, you must leave the group value empty:
|
||||||
```
|
```
|
||||||
http://example.com/api/v1/badges/uptime/7d/group--service-frontend.svg
|
http://example.com/api/v1/badges/uptime/7d/_frontend.svg
|
||||||
```
|
```
|
||||||
|
|
||||||
Example: 
|
Example: 
|
||||||
```
|
```
|
||||||

|

|
||||||
```
|
```
|
||||||
|
|
||||||
|
If you'd like to see a visual example of each badges available, you can simply navigate to the service's detail page.
|
||||||
@@ -2,6 +2,7 @@ package custom
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -76,6 +77,9 @@ func (provider *AlertProvider) buildHTTPRequest(serviceName, alertDescription st
|
|||||||
// Send a request to the alert provider and return the body
|
// Send a request to the alert provider and return the body
|
||||||
func (provider *AlertProvider) Send(serviceName, alertDescription string, resolved bool) ([]byte, error) {
|
func (provider *AlertProvider) Send(serviceName, alertDescription string, resolved bool) ([]byte, error) {
|
||||||
if os.Getenv("MOCK_ALERT_PROVIDER") == "true" {
|
if os.Getenv("MOCK_ALERT_PROVIDER") == "true" {
|
||||||
|
if os.Getenv("MOCK_ALERT_PROVIDER_ERROR") == "true" {
|
||||||
|
return nil, errors.New("error")
|
||||||
|
}
|
||||||
return []byte("{}"), nil
|
return []byte("{}"), nil
|
||||||
}
|
}
|
||||||
request := provider.buildHTTPRequest(serviceName, alertDescription, resolved)
|
request := provider.buildHTTPRequest(serviceName, alertDescription, resolved)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ func (provider *AlertProvider) ToCustomAlertProvider(service *core.Service, aler
|
|||||||
for _, conditionResult := range result.ConditionResults {
|
for _, conditionResult := range result.ConditionResults {
|
||||||
var prefix string
|
var prefix string
|
||||||
if conditionResult.Success {
|
if conditionResult.Success {
|
||||||
prefix = ":heavy_check_mark:"
|
prefix = ":white_check_mark:"
|
||||||
} else {
|
} else {
|
||||||
prefix = ":x:"
|
prefix = ":x:"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
services:
|
services:
|
||||||
- name: frontend
|
- name: front-end
|
||||||
group: core
|
group: core
|
||||||
url: "https://twinnation.org/health"
|
url: "https://twinnation.org/health"
|
||||||
interval: 1m
|
interval: 1m
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
- "[BODY].status == UP"
|
- "[BODY].status == UP"
|
||||||
- "[RESPONSE_TIME] < 70"
|
- "[RESPONSE_TIME] < 150"
|
||||||
|
|
||||||
- name: backend
|
- name: back-end
|
||||||
group: core
|
group: core
|
||||||
url: "http://example.org/"
|
url: "http://example.org/"
|
||||||
interval: 5m
|
interval: 5m
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import (
|
|||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwinProduction/gatus/core"
|
||||||
"github.com/TwinProduction/gatus/k8s"
|
"github.com/TwinProduction/gatus/k8s"
|
||||||
"github.com/TwinProduction/gatus/security"
|
"github.com/TwinProduction/gatus/security"
|
||||||
|
"github.com/TwinProduction/gatus/storage"
|
||||||
|
"github.com/TwinProduction/gatus/util"
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -28,9 +30,6 @@ const (
|
|||||||
|
|
||||||
// DefaultPort is the default port the service will listen on
|
// DefaultPort is the default port the service will listen on
|
||||||
DefaultPort = 8080
|
DefaultPort = 8080
|
||||||
|
|
||||||
// DefaultContextRoot is the default context root of the web application
|
|
||||||
DefaultContextRoot = "/"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -74,8 +73,11 @@ type Config struct {
|
|||||||
// Kubernetes is the Kubernetes configuration
|
// Kubernetes is the Kubernetes configuration
|
||||||
Kubernetes *k8s.Config `yaml:"kubernetes"`
|
Kubernetes *k8s.Config `yaml:"kubernetes"`
|
||||||
|
|
||||||
|
// Storage is the configuration for how the data is stored
|
||||||
|
Storage *storage.Config `yaml:"storage"`
|
||||||
|
|
||||||
// Web is the configuration for the web listener
|
// Web is the configuration for the web listener
|
||||||
Web *webConfig `yaml:"web"`
|
Web *WebConfig `yaml:"web"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the configuration, or panics if the configuration hasn't loaded yet
|
// Get returns the configuration, or panics if the configuration hasn't loaded yet
|
||||||
@@ -147,13 +149,33 @@ func parseAndValidateConfigBytes(yamlBytes []byte) (config *Config, err error) {
|
|||||||
validateServicesConfig(config)
|
validateServicesConfig(config)
|
||||||
validateKubernetesConfig(config)
|
validateKubernetesConfig(config)
|
||||||
validateWebConfig(config)
|
validateWebConfig(config)
|
||||||
|
validateStorageConfig(config)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateStorageConfig(config *Config) {
|
||||||
|
if config.Storage == nil {
|
||||||
|
config.Storage = &storage.Config{}
|
||||||
|
}
|
||||||
|
err := storage.Initialize(config.Storage)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
// Remove all ServiceStatus that represent services which no longer exist in the configuration
|
||||||
|
var keys []string
|
||||||
|
for _, service := range config.Services {
|
||||||
|
keys = append(keys, util.ConvertGroupAndServiceToKey(service.Group, service.Name))
|
||||||
|
}
|
||||||
|
numberOfServiceStatusesDeleted := storage.Get().DeleteAllServiceStatusesNotInKeys(keys)
|
||||||
|
if numberOfServiceStatusesDeleted > 0 {
|
||||||
|
log.Printf("[config][validateStorageConfig] Deleted %d service statuses because their matching services no longer existed", numberOfServiceStatusesDeleted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func validateWebConfig(config *Config) {
|
func validateWebConfig(config *Config) {
|
||||||
if config.Web == nil {
|
if config.Web == nil {
|
||||||
config.Web = &webConfig{Address: DefaultAddress, Port: DefaultPort, ContextRoot: DefaultContextRoot}
|
config.Web = &WebConfig{Address: DefaultAddress, Port: DefaultPort}
|
||||||
} else {
|
} else {
|
||||||
config.Web.validateAndSetDefaults()
|
config.Web.validateAndSetDefaults()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,10 @@ func TestLoadDefaultConfigurationFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytes(t *testing.T) {
|
func TestParseAndValidateConfigBytes(t *testing.T) {
|
||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
file := t.TempDir() + "/test.db"
|
||||||
|
config, err := parseAndValidateConfigBytes([]byte(fmt.Sprintf(`
|
||||||
|
storage:
|
||||||
|
file: %s
|
||||||
services:
|
services:
|
||||||
- name: twinnation
|
- name: twinnation
|
||||||
url: https://twinnation.org/health
|
url: https://twinnation.org/health
|
||||||
@@ -54,9 +57,9 @@ services:
|
|||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] != 400"
|
- "[STATUS] != 400"
|
||||||
- "[STATUS] != 500"
|
- "[STATUS] != 500"
|
||||||
`))
|
`, file)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -99,7 +102,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -119,9 +122,6 @@ services:
|
|||||||
if config.Web.Port != DefaultPort {
|
if config.Web.Port != DefaultPort {
|
||||||
t.Errorf("Port should have been %d, because it is the default value", DefaultPort)
|
t.Errorf("Port should have been %d, because it is the default value", DefaultPort)
|
||||||
}
|
}
|
||||||
if config.Web.ContextRoot != DefaultContextRoot {
|
|
||||||
t.Errorf("ContextRoot should have been %s, because it is the default value", DefaultContextRoot)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesWithAddress(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithAddress(t *testing.T) {
|
||||||
@@ -135,7 +135,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -165,12 +165,12 @@ web:
|
|||||||
port: 12345
|
port: 12345
|
||||||
services:
|
services:
|
||||||
- name: twinnation
|
- name: twinnation
|
||||||
url: https://twinnation.org/actuator/health
|
url: https://twinnation.org/health
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -178,17 +178,15 @@ services:
|
|||||||
if config.Metrics {
|
if config.Metrics {
|
||||||
t.Error("Metrics should've been false by default")
|
t.Error("Metrics should've been false by default")
|
||||||
}
|
}
|
||||||
if config.Services[0].URL != "https://twinnation.org/actuator/health" {
|
if config.Services[0].URL != "https://twinnation.org/health" {
|
||||||
t.Errorf("URL should have been %s", "https://twinnation.org/actuator/health")
|
t.Errorf("URL should have been %s", "https://twinnation.org/health")
|
||||||
}
|
}
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
if config.Services[0].Interval != 60*time.Second {
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Web.Address != DefaultAddress {
|
if config.Web.Address != DefaultAddress {
|
||||||
t.Errorf("Bind address should have been %s, because it is the default value", DefaultAddress)
|
t.Errorf("Bind address should have been %s, because it is the default value", DefaultAddress)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Web.Port != 12345 {
|
if config.Web.Port != 12345 {
|
||||||
t.Errorf("Port should have been %d, because it is specified in config", 12345)
|
t.Errorf("Port should have been %d, because it is specified in config", 12345)
|
||||||
}
|
}
|
||||||
@@ -206,7 +204,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -228,44 +226,6 @@ services:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesWithPortAndHostAndContextRoot(t *testing.T) {
|
|
||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
|
||||||
web:
|
|
||||||
port: 12345
|
|
||||||
address: 127.0.0.1
|
|
||||||
context-root: /deeply/nested/down=/their
|
|
||||||
services:
|
|
||||||
- name: twinnation
|
|
||||||
url: https://twinnation.org/health
|
|
||||||
conditions:
|
|
||||||
- "[STATUS] == 200"
|
|
||||||
`))
|
|
||||||
if err != nil {
|
|
||||||
t.Error("No error should've been returned")
|
|
||||||
}
|
|
||||||
if config == nil {
|
|
||||||
t.Fatal("Config shouldn't have been nil")
|
|
||||||
}
|
|
||||||
if config.Metrics {
|
|
||||||
t.Error("Metrics should've been false by default")
|
|
||||||
}
|
|
||||||
if config.Services[0].URL != "https://twinnation.org/health" {
|
|
||||||
t.Errorf("URL should have been %s", "https://twinnation.org/health")
|
|
||||||
}
|
|
||||||
if config.Services[0].Interval != 60*time.Second {
|
|
||||||
t.Errorf("Interval should have been %s, because it is the default value", 60*time.Second)
|
|
||||||
}
|
|
||||||
if config.Web.Address != "127.0.0.1" {
|
|
||||||
t.Errorf("Bind address should have been %s, because it is specified in config", "127.0.0.1")
|
|
||||||
}
|
|
||||||
if config.Web.Port != 12345 {
|
|
||||||
t.Errorf("Port should have been %d, because it is specified in config", 12345)
|
|
||||||
}
|
|
||||||
if config.Web.ContextRoot != "/deeply/nested/down=/their/" {
|
|
||||||
t.Errorf("Port should have been %s, because it is specified in config", "/deeply/nested/down=/their/")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParseAndValidateConfigBytesWithInvalidPort(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithInvalidPort(t *testing.T) {
|
||||||
defer func() { recover() }()
|
defer func() { recover() }()
|
||||||
_, _ = parseAndValidateConfigBytes([]byte(`
|
_, _ = parseAndValidateConfigBytes([]byte(`
|
||||||
@@ -293,7 +253,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -313,9 +273,6 @@ services:
|
|||||||
if config.Web.Port != DefaultPort {
|
if config.Web.Port != DefaultPort {
|
||||||
t.Errorf("Port should have been %d, because it is the default value", DefaultPort)
|
t.Errorf("Port should have been %d, because it is the default value", DefaultPort)
|
||||||
}
|
}
|
||||||
if config.Web.ContextRoot != DefaultContextRoot {
|
|
||||||
t.Errorf("ContextRoot should have been %s, because it is the default value", DefaultContextRoot)
|
|
||||||
}
|
|
||||||
if userAgent := config.Services[0].Headers["User-Agent"]; userAgent != "Test/2.0" {
|
if userAgent := config.Services[0].Headers["User-Agent"]; userAgent != "Test/2.0" {
|
||||||
t.Errorf("User-Agent should've been %s, got %s", "Test/2.0", userAgent)
|
t.Errorf("User-Agent should've been %s, got %s", "Test/2.0", userAgent)
|
||||||
}
|
}
|
||||||
@@ -334,7 +291,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -378,7 +335,6 @@ badconfig:
|
|||||||
func TestParseAndValidateConfigBytesWithAlerting(t *testing.T) {
|
func TestParseAndValidateConfigBytesWithAlerting(t *testing.T) {
|
||||||
config, err := parseAndValidateConfigBytes([]byte(`
|
config, err := parseAndValidateConfigBytes([]byte(`
|
||||||
debug: true
|
debug: true
|
||||||
|
|
||||||
alerting:
|
alerting:
|
||||||
slack:
|
slack:
|
||||||
webhook-url: "http://example.com"
|
webhook-url: "http://example.com"
|
||||||
@@ -405,7 +361,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -498,7 +454,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -532,7 +488,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -571,7 +527,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -624,7 +580,7 @@ services:
|
|||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
`, expectedUsername, expectedPasswordHash)))
|
`, expectedUsername, expectedPasswordHash)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
@@ -691,7 +647,7 @@ kubernetes:
|
|||||||
target-path: "/health"
|
target-path: "/health"
|
||||||
`))
|
`))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("No error should've been returned")
|
t.Error("expected no error, got", err.Error())
|
||||||
}
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
t.Fatal("Config shouldn't have been nil")
|
t.Fatal("Config shouldn't have been nil")
|
||||||
|
|||||||
@@ -3,25 +3,20 @@ package config
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// webConfig is the structure which supports the configuration of the endpoint
|
// WebConfig is the structure which supports the configuration of the endpoint
|
||||||
// which provides access to the web frontend
|
// which provides access to the web frontend
|
||||||
type webConfig struct {
|
type WebConfig struct {
|
||||||
// Address to listen on (defaults to 0.0.0.0 specified by DefaultAddress)
|
// Address to listen on (defaults to 0.0.0.0 specified by DefaultAddress)
|
||||||
Address string `yaml:"address"`
|
Address string `yaml:"address"`
|
||||||
|
|
||||||
// Port to listen on (default to 8080 specified by DefaultPort)
|
// Port to listen on (default to 8080 specified by DefaultPort)
|
||||||
Port int `yaml:"port"`
|
Port int `yaml:"port"`
|
||||||
|
|
||||||
// ContextRoot set the root context for the web application
|
|
||||||
ContextRoot string `yaml:"context-root"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateAndSetDefaults checks and sets the default values for fields that are not set
|
// validateAndSetDefaults checks and sets the default values for fields that are not set
|
||||||
func (web *webConfig) validateAndSetDefaults() {
|
func (web *WebConfig) validateAndSetDefaults() {
|
||||||
// Validate the Address
|
// Validate the Address
|
||||||
if len(web.Address) == 0 {
|
if len(web.Address) == 0 {
|
||||||
web.Address = DefaultAddress
|
web.Address = DefaultAddress
|
||||||
@@ -32,32 +27,9 @@ func (web *webConfig) validateAndSetDefaults() {
|
|||||||
} else if web.Port < 0 || web.Port > math.MaxUint16 {
|
} else if web.Port < 0 || web.Port > math.MaxUint16 {
|
||||||
panic(fmt.Sprintf("invalid port: value should be between %d and %d", 0, math.MaxUint16))
|
panic(fmt.Sprintf("invalid port: value should be between %d and %d", 0, math.MaxUint16))
|
||||||
}
|
}
|
||||||
// Validate the ContextRoot
|
|
||||||
if len(web.ContextRoot) == 0 {
|
|
||||||
web.ContextRoot = DefaultContextRoot
|
|
||||||
} else {
|
|
||||||
trimmedContextRoot := strings.Trim(web.ContextRoot, "/")
|
|
||||||
if len(trimmedContextRoot) == 0 {
|
|
||||||
web.ContextRoot = DefaultContextRoot
|
|
||||||
return
|
|
||||||
}
|
|
||||||
rootContextURL, err := url.Parse(trimmedContextRoot)
|
|
||||||
if err != nil {
|
|
||||||
panic("invalid context root:" + err.Error())
|
|
||||||
}
|
|
||||||
if rootContextURL.Path != trimmedContextRoot {
|
|
||||||
panic("invalid context root: too complex")
|
|
||||||
}
|
|
||||||
web.ContextRoot = "/" + strings.Trim(rootContextURL.Path, "/") + "/"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SocketAddress returns the combination of the Address and the Port
|
// SocketAddress returns the combination of the Address and the Port
|
||||||
func (web *webConfig) SocketAddress() string {
|
func (web *WebConfig) SocketAddress() string {
|
||||||
return fmt.Sprintf("%s:%d", web.Address, web.Port)
|
return fmt.Sprintf("%s:%d", web.Address, web.Port)
|
||||||
}
|
}
|
||||||
|
|
||||||
// PrependWithContextRoot appends the given path to the ContextRoot
|
|
||||||
func (web *webConfig) PrependWithContextRoot(path string) string {
|
|
||||||
return web.ContextRoot + strings.Trim(path, "/")
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestWebConfig_SocketAddress(t *testing.T) {
|
func TestWebConfig_SocketAddress(t *testing.T) {
|
||||||
web := &webConfig{
|
web := &WebConfig{
|
||||||
Address: "0.0.0.0",
|
Address: "0.0.0.0",
|
||||||
Port: 8081,
|
Port: 8081,
|
||||||
}
|
}
|
||||||
@@ -14,86 +13,3 @@ func TestWebConfig_SocketAddress(t *testing.T) {
|
|||||||
t.Errorf("expected %s, got %s", "0.0.0.0:8081", web.SocketAddress())
|
t.Errorf("expected %s, got %s", "0.0.0.0:8081", web.SocketAddress())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWebConfig_PrependWithContextRoot(t *testing.T) {
|
|
||||||
web := &webConfig{ContextRoot: "/status/"}
|
|
||||||
if result := web.PrependWithContextRoot("/api/v1/results"); result != "/status/api/v1/results" {
|
|
||||||
t.Errorf("expected %s, got %s", "/status/api/v1/results", result)
|
|
||||||
}
|
|
||||||
if result := web.PrependWithContextRoot("/health"); result != "/status/health" {
|
|
||||||
t.Errorf("expected %s, got %s", "/status/health", result)
|
|
||||||
}
|
|
||||||
if result := web.PrependWithContextRoot("/health/"); result != "/status/health" {
|
|
||||||
t.Errorf("expected %s, got %s", "/status/health", result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// validContextRootTest specifies all test case which should end up in
|
|
||||||
// a valid context root used to bind the web interface to
|
|
||||||
var validContextRootTests = []struct {
|
|
||||||
name string
|
|
||||||
path string
|
|
||||||
expectedPath string
|
|
||||||
}{
|
|
||||||
{"Empty", "", "/"},
|
|
||||||
{"/", "/", "/"},
|
|
||||||
{"///", "///", "/"},
|
|
||||||
{"Single character 'a'", "a", "/a/"},
|
|
||||||
{"Slash at the beginning", "/status", "/status/"},
|
|
||||||
{"Slashes at start and end", "/status/", "/status/"},
|
|
||||||
{"Multiple slashes at start", "//status", "/status/"},
|
|
||||||
{"Multiple slashes at start and end", "///status////", "/status/"},
|
|
||||||
{"Contains '@' in path'", "me@/status/gatus", "/me@/status/gatus/"},
|
|
||||||
{"Nested context with trailing slash", "/status/gatus/", "/status/gatus/"},
|
|
||||||
{"Nested context without trailing slash", "/status/gatus/system", "/status/gatus/system/"},
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestWebConfig_ValidContextRoots(t *testing.T) {
|
|
||||||
for idx, test := range validContextRootTests {
|
|
||||||
t.Run(fmt.Sprintf("%d: %s", idx, test.name), func(t *testing.T) {
|
|
||||||
expectValidResultForContextRoot(t, test.path, test.expectedPath)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func expectValidResultForContextRoot(t *testing.T, path string, expected string) {
|
|
||||||
web := &webConfig{
|
|
||||||
ContextRoot: path,
|
|
||||||
}
|
|
||||||
web.validateAndSetDefaults()
|
|
||||||
if web.ContextRoot != expected {
|
|
||||||
t.Errorf("expected %s, got %s", expected, web.ContextRoot)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// invalidContextRootTests contains all tests for context root which are
|
|
||||||
// expected to fail and stop program execution
|
|
||||||
var invalidContextRootTests = []struct {
|
|
||||||
name string
|
|
||||||
path string
|
|
||||||
}{
|
|
||||||
{"Only a fragment identifier", "#"},
|
|
||||||
{"Invalid character in path", "/invalid" + string([]byte{0x7F})},
|
|
||||||
{"Starts with protocol", "http://status/gatus"},
|
|
||||||
{"Path with fragment", "/status/gatus#here"},
|
|
||||||
{"Starts with '://'", "://status"},
|
|
||||||
{"Contains query parameter", "/status/h?ello=world"},
|
|
||||||
{"Contains '?'", "/status?"},
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestWebConfig_InvalidContextRoots(t *testing.T) {
|
|
||||||
for idx, test := range invalidContextRootTests {
|
|
||||||
t.Run(fmt.Sprintf("%d: %s", idx, test.name), func(t *testing.T) {
|
|
||||||
expectInvalidResultForContextRoot(t, test.path)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func expectInvalidResultForContextRoot(t *testing.T, path string) {
|
|
||||||
defer func() { recover() }()
|
|
||||||
|
|
||||||
web := &webConfig{ContextRoot: path}
|
|
||||||
web.validateAndSetDefaults()
|
|
||||||
|
|
||||||
t.Fatal(fmt.Sprintf("Should've panicked because the configuration specifies an invalid context root: %s", path))
|
|
||||||
}
|
|
||||||
@@ -14,26 +14,18 @@ import (
|
|||||||
// badgeHandler handles the automatic generation of badge based on the group name and service name passed.
|
// badgeHandler handles the automatic generation of badge based on the group name and service name passed.
|
||||||
//
|
//
|
||||||
// Valid values for {duration}: 7d, 24h, 1h
|
// Valid values for {duration}: 7d, 24h, 1h
|
||||||
// Pattern for {identifier}: group-<GROUP_NAME>-service-<SERVICE_NAME>.svg
|
// Pattern for {identifier}: <KEY>.svg
|
||||||
func badgeHandler(writer http.ResponseWriter, request *http.Request) {
|
func badgeHandler(writer http.ResponseWriter, request *http.Request) {
|
||||||
variables := mux.Vars(request)
|
variables := mux.Vars(request)
|
||||||
duration := variables["duration"]
|
duration := variables["duration"]
|
||||||
// group-<GROUP_NAME>-service-<SERVICE_NAME>.svg
|
|
||||||
identifier := variables["identifier"]
|
|
||||||
if duration != "7d" && duration != "24h" && duration != "1h" {
|
if duration != "7d" && duration != "24h" && duration != "1h" {
|
||||||
writer.WriteHeader(http.StatusBadRequest)
|
writer.WriteHeader(http.StatusBadRequest)
|
||||||
_, _ = writer.Write([]byte("Durations supported: 7d, 24h, 1h"))
|
_, _ = writer.Write([]byte("Durations supported: 7d, 24h, 1h"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
parts := strings.Split(identifier, "-service-")
|
identifier := variables["identifier"]
|
||||||
if len(parts) != 2 || !strings.HasPrefix(identifier, "group-") || !strings.HasSuffix(identifier, ".svg") {
|
key := strings.TrimSuffix(identifier, ".svg")
|
||||||
writer.WriteHeader(http.StatusBadRequest)
|
uptime := watchdog.GetUptimeByKey(key)
|
||||||
_, _ = writer.Write([]byte("Invalid path: Pattern should look like /group-<GROUP_NAME>-service-<SERVICE_NAME>.svg"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
groupName := strings.TrimPrefix(parts[0], "group-")
|
|
||||||
serviceName := strings.TrimSuffix(parts[1], ".svg")
|
|
||||||
uptime := watchdog.GetUptimeByServiceGroupAndName(groupName, serviceName)
|
|
||||||
if uptime == nil {
|
if uptime == nil {
|
||||||
writer.WriteHeader(http.StatusNotFound)
|
writer.WriteHeader(http.StatusNotFound)
|
||||||
_, _ = writer.Write([]byte("Requested service not found"))
|
_, _ = writer.Write([]byte("Requested service not found"))
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ package controller
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -23,6 +25,14 @@ const (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
cache = gocache.NewCache().WithMaxSize(100).WithEvictionPolicy(gocache.LeastRecentlyUsed)
|
cache = gocache.NewCache().WithMaxSize(100).WithEvictionPolicy(gocache.LeastRecentlyUsed)
|
||||||
|
|
||||||
|
// staticFolder is the path to the location of the static folder from the root path of the project
|
||||||
|
// The only reason this is exposed is to allow running tests from a different path than the root path of the project
|
||||||
|
staticFolder = "./web/static"
|
||||||
|
|
||||||
|
// server is the http.Server created by Handle.
|
||||||
|
// The only reason it exists is for testing purposes.
|
||||||
|
server *http.Server
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@@ -34,36 +44,52 @@ func init() {
|
|||||||
// Handle creates the router and starts the server
|
// Handle creates the router and starts the server
|
||||||
func Handle() {
|
func Handle() {
|
||||||
cfg := config.Get()
|
cfg := config.Get()
|
||||||
router := CreateRouter(cfg)
|
var router http.Handler = CreateRouter(cfg)
|
||||||
server := &http.Server{
|
if os.Getenv("ENVIRONMENT") == "dev" {
|
||||||
|
router = developmentCorsHandler(router)
|
||||||
|
}
|
||||||
|
server = &http.Server{
|
||||||
Addr: fmt.Sprintf("%s:%d", cfg.Web.Address, cfg.Web.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.Printf("[controller][Handle] Listening on %s%s\n", cfg.Web.SocketAddress(), cfg.Web.ContextRoot)
|
log.Println("[controller][Handle] Listening on " + cfg.Web.SocketAddress())
|
||||||
|
if os.Getenv("ROUTER_TEST") == "true" {
|
||||||
|
return
|
||||||
|
}
|
||||||
log.Fatal(server.ListenAndServe())
|
log.Fatal(server.ListenAndServe())
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateRouter creates the router for the http server
|
// CreateRouter creates the router for the http server
|
||||||
func CreateRouter(cfg *config.Config) *mux.Router {
|
func CreateRouter(cfg *config.Config) *mux.Router {
|
||||||
router := mux.NewRouter()
|
router := mux.NewRouter()
|
||||||
statusesHandler := serviceStatusesHandler
|
|
||||||
if cfg.Security != nil && cfg.Security.IsValid() {
|
|
||||||
statusesHandler = security.Handler(serviceStatusesHandler, cfg.Security)
|
|
||||||
}
|
|
||||||
router.HandleFunc("/favicon.ico", favIconHandler).Methods("GET") // favicon needs to be always served from the root
|
|
||||||
router.HandleFunc(cfg.Web.PrependWithContextRoot("/api/v1/statuses"), statusesHandler).Methods("GET")
|
|
||||||
router.HandleFunc(cfg.Web.PrependWithContextRoot("/api/v1/badges/uptime/{duration}/{identifier}"), badgeHandler).Methods("GET")
|
|
||||||
router.HandleFunc(cfg.Web.PrependWithContextRoot("/health"), healthHandler).Methods("GET")
|
|
||||||
router.PathPrefix(cfg.Web.ContextRoot).Handler(GzipHandler(http.StripPrefix(cfg.Web.ContextRoot, http.FileServer(http.Dir("./static")))))
|
|
||||||
if cfg.Metrics {
|
if cfg.Metrics {
|
||||||
router.Handle(cfg.Web.PrependWithContextRoot("/metrics"), promhttp.Handler()).Methods("GET")
|
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
||||||
}
|
}
|
||||||
|
router.HandleFunc("/favicon.ico", favIconHandler).Methods("GET")
|
||||||
|
router.HandleFunc("/health", healthHandler).Methods("GET")
|
||||||
|
router.HandleFunc("/api/v1/statuses", secureIfNecessary(cfg, serviceStatusesHandler)).Methods("GET") // No GzipHandler for this one, because we cache the content
|
||||||
|
router.HandleFunc("/api/v1/statuses/{key}", secureIfNecessary(cfg, GzipHandlerFunc(serviceStatusHandler))).Methods("GET")
|
||||||
|
router.HandleFunc("/api/v1/badges/uptime/{duration}/{identifier}", badgeHandler).Methods("GET")
|
||||||
|
// SPA
|
||||||
|
router.HandleFunc("/services/{service}", spaHandler).Methods("GET")
|
||||||
|
// Everything else falls back on static content
|
||||||
|
router.PathPrefix("/").Handler(GzipHandler(http.FileServer(http.Dir(staticFolder))))
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func secureIfNecessary(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc {
|
||||||
|
if cfg.Security != nil && cfg.Security.IsValid() {
|
||||||
|
return security.Handler(handler, cfg.Security)
|
||||||
|
}
|
||||||
|
return handler
|
||||||
|
}
|
||||||
|
|
||||||
|
// serviceStatusesHandler handles requests to retrieve all service statuses
|
||||||
|
// Due to the size of the response, this function leverages a cache.
|
||||||
|
// Must not be wrapped by GzipHandler
|
||||||
func serviceStatusesHandler(writer http.ResponseWriter, r *http.Request) {
|
func serviceStatusesHandler(writer http.ResponseWriter, r *http.Request) {
|
||||||
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
|
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
|
||||||
var exists bool
|
var exists bool
|
||||||
@@ -81,7 +107,7 @@ func serviceStatusesHandler(writer http.ResponseWriter, r *http.Request) {
|
|||||||
gzipWriter := gzip.NewWriter(buffer)
|
gzipWriter := gzip.NewWriter(buffer)
|
||||||
data, err = watchdog.GetServiceStatusesAsJSON()
|
data, err = watchdog.GetServiceStatusesAsJSON()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[main][serviceStatusesHandler] Unable to marshal object to JSON: %s", err.Error())
|
log.Printf("[controller][serviceStatusesHandler] Unable to marshal object to JSON: %s", err.Error())
|
||||||
writer.WriteHeader(http.StatusInternalServerError)
|
writer.WriteHeader(http.StatusInternalServerError)
|
||||||
_, _ = writer.Write([]byte("Unable to marshal object to JSON"))
|
_, _ = writer.Write([]byte("Unable to marshal object to JSON"))
|
||||||
return
|
return
|
||||||
@@ -102,6 +128,36 @@ func serviceStatusesHandler(writer http.ResponseWriter, r *http.Request) {
|
|||||||
_, _ = writer.Write(data)
|
_, _ = writer.Write(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// serviceStatusHandler retrieves a single ServiceStatus by group name and service name
|
||||||
|
func serviceStatusHandler(writer http.ResponseWriter, r *http.Request) {
|
||||||
|
vars := mux.Vars(r)
|
||||||
|
serviceStatus := watchdog.GetServiceStatusByKey(vars["key"])
|
||||||
|
if serviceStatus == nil {
|
||||||
|
log.Printf("[controller][serviceStatusHandler] Service with key=%s not found", vars["key"])
|
||||||
|
writer.WriteHeader(http.StatusNotFound)
|
||||||
|
_, _ = writer.Write([]byte("not found"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data := map[string]interface{}{
|
||||||
|
"serviceStatus": serviceStatus,
|
||||||
|
// The following fields, while present on core.ServiceStatus, are annotated to remain hidden so that we can
|
||||||
|
// expose only the necessary data on /api/v1/statuses.
|
||||||
|
// Since the /api/v1/statuses/{key} endpoint does need this data, however, we explicitly expose it here
|
||||||
|
"events": serviceStatus.Events,
|
||||||
|
"uptime": serviceStatus.Uptime,
|
||||||
|
}
|
||||||
|
output, err := json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[controller][serviceStatusHandler] Unable to marshal object to JSON: %s", err.Error())
|
||||||
|
writer.WriteHeader(http.StatusInternalServerError)
|
||||||
|
_, _ = writer.Write([]byte("Unable to marshal object to JSON"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writer.Header().Add("Content-Type", "application/json")
|
||||||
|
writer.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = writer.Write(output)
|
||||||
|
}
|
||||||
|
|
||||||
func healthHandler(writer http.ResponseWriter, _ *http.Request) {
|
func healthHandler(writer http.ResponseWriter, _ *http.Request) {
|
||||||
writer.Header().Add("Content-Type", "application/json")
|
writer.Header().Add("Content-Type", "application/json")
|
||||||
writer.WriteHeader(http.StatusOK)
|
writer.WriteHeader(http.StatusOK)
|
||||||
@@ -110,5 +166,10 @@ func healthHandler(writer http.ResponseWriter, _ *http.Request) {
|
|||||||
|
|
||||||
// favIconHandler handles requests for /favicon.ico
|
// favIconHandler handles requests for /favicon.ico
|
||||||
func favIconHandler(writer http.ResponseWriter, request *http.Request) {
|
func favIconHandler(writer http.ResponseWriter, request *http.Request) {
|
||||||
http.ServeFile(writer, request, "./static/favicon.ico")
|
http.ServeFile(writer, request, staticFolder+"/favicon.ico")
|
||||||
|
}
|
||||||
|
|
||||||
|
// spaHandler handles requests for /favicon.ico
|
||||||
|
func spaHandler(writer http.ResponseWriter, request *http.Request) {
|
||||||
|
http.ServeFile(writer, request, staticFolder+"/index.html")
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwinProduction/gatus/config"
|
||||||
|
"github.com/TwinProduction/gatus/core"
|
||||||
|
"github.com/TwinProduction/gatus/watchdog"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateRouter(t *testing.T) {
|
||||||
|
staticFolder = "../web/static"
|
||||||
|
cfg := &config.Config{
|
||||||
|
Metrics: true,
|
||||||
|
Services: []*core.Service{
|
||||||
|
{
|
||||||
|
Name: "frontend",
|
||||||
|
Group: "core",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "backend",
|
||||||
|
Group: "core",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
watchdog.UpdateServiceStatuses(cfg.Services[0], &core.Result{Success: true, Duration: time.Millisecond, Timestamp: time.Now()})
|
||||||
|
watchdog.UpdateServiceStatuses(cfg.Services[1], &core.Result{Success: false, Duration: time.Second, Timestamp: time.Now()})
|
||||||
|
router := CreateRouter(cfg)
|
||||||
|
type Scenario struct {
|
||||||
|
Name string
|
||||||
|
Path string
|
||||||
|
ExpectedCode int
|
||||||
|
Gzip bool
|
||||||
|
}
|
||||||
|
scenarios := []Scenario{
|
||||||
|
{
|
||||||
|
Name: "health",
|
||||||
|
Path: "/health",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "metrics",
|
||||||
|
Path: "/metrics",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "badges-1h",
|
||||||
|
Path: "/api/v1/badges/uptime/1h/core_frontend.svg",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "badges-24h",
|
||||||
|
Path: "/api/v1/badges/uptime/24h/core_backend.svg",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "badges-7d",
|
||||||
|
Path: "/api/v1/badges/uptime/7d/core_frontend.svg",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "badges-with-invalid-duration",
|
||||||
|
Path: "/api/v1/badges/uptime/3d/core_backend.svg",
|
||||||
|
ExpectedCode: http.StatusBadRequest,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "badges-for-invalid-key",
|
||||||
|
Path: "/api/v1/badges/uptime/7d/invalid_key.svg",
|
||||||
|
ExpectedCode: http.StatusNotFound,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "service-statuses",
|
||||||
|
Path: "/api/v1/statuses",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "service-statuses-gzip",
|
||||||
|
Path: "/api/v1/statuses",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
Gzip: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "service-status",
|
||||||
|
Path: "/api/v1/statuses/core_frontend",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "service-status-gzip",
|
||||||
|
Path: "/api/v1/statuses/core_frontend",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
Gzip: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "service-status-for-invalid-key",
|
||||||
|
Path: "/api/v1/statuses/invalid_key",
|
||||||
|
ExpectedCode: http.StatusNotFound,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "favicon",
|
||||||
|
Path: "/favicon.ico",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "frontend-home",
|
||||||
|
Path: "/",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "frontend-assets",
|
||||||
|
Path: "/js/app.js",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "frontend-service",
|
||||||
|
Path: "/services/core_frontend",
|
||||||
|
ExpectedCode: http.StatusOK,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.Name, func(t *testing.T) {
|
||||||
|
request, _ := http.NewRequest("GET", scenario.Path, nil)
|
||||||
|
if scenario.Gzip {
|
||||||
|
request.Header.Set("Accept-Encoding", "gzip")
|
||||||
|
}
|
||||||
|
responseRecorder := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(responseRecorder, request)
|
||||||
|
if responseRecorder.Code != scenario.ExpectedCode {
|
||||||
|
t.Errorf("%s %s should have returned %d, but returned %d instead", request.Method, request.URL, scenario.ExpectedCode, responseRecorder.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandle(t *testing.T) {
|
||||||
|
cfg := &config.Config{
|
||||||
|
Web: &config.WebConfig{
|
||||||
|
Address: "0.0.0.0",
|
||||||
|
Port: rand.Intn(65534),
|
||||||
|
},
|
||||||
|
Services: []*core.Service{
|
||||||
|
{
|
||||||
|
Name: "frontend",
|
||||||
|
Group: "core",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "backend",
|
||||||
|
Group: "core",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
config.Set(cfg)
|
||||||
|
_ = os.Setenv("ROUTER_TEST", "true")
|
||||||
|
_ = os.Setenv("ENVIRONMENT", "dev")
|
||||||
|
Handle()
|
||||||
|
request, _ := http.NewRequest("GET", "/health", nil)
|
||||||
|
responseRecorder := httptest.NewRecorder()
|
||||||
|
server.Handler.ServeHTTP(responseRecorder, request)
|
||||||
|
if responseRecorder.Code != http.StatusOK {
|
||||||
|
t.Error("expected GET /health to return status code 200")
|
||||||
|
}
|
||||||
|
if server == nil {
|
||||||
|
t.Fatal("server should've been set (but because we set ROUTER_TEST, it shouldn't have been started)")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import "net/http"
|
||||||
|
|
||||||
|
func developmentCorsHandler(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8081")
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -32,10 +32,18 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {
|
|||||||
return w.Writer.Write(b)
|
return w.Writer.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GzipHandler compresses the response of a given handler if the request's headers specify that the client
|
// GzipHandler compresses the response of a given http.Handler if the request's headers specify that the client
|
||||||
// supports gzip encoding
|
// supports gzip encoding
|
||||||
func GzipHandler(next http.Handler) http.Handler {
|
func GzipHandler(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(writer http.ResponseWriter, r *http.Request) {
|
return GzipHandlerFunc(func(writer http.ResponseWriter, r *http.Request) {
|
||||||
|
next.ServeHTTP(writer, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GzipHandlerFunc compresses the response of a given http.HandlerFunc if the request's headers specify that the client
|
||||||
|
// supports gzip encoding
|
||||||
|
func GzipHandlerFunc(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(writer http.ResponseWriter, r *http.Request) {
|
||||||
// If the request doesn't specify that it supports gzip, then don't compress it
|
// If the request doesn't specify that it supports gzip, then don't compress it
|
||||||
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||||
next.ServeHTTP(writer, r)
|
next.ServeHTTP(writer, r)
|
||||||
@@ -47,5 +55,5 @@ func GzipHandler(next http.Handler) http.Handler {
|
|||||||
gz.Reset(writer)
|
gz.Reset(writer)
|
||||||
defer gz.Close()
|
defer gz.Close()
|
||||||
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: writer, Writer: gz}, r)
|
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: writer, Writer: gz}, r)
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
@@ -26,6 +26,12 @@ type Alert struct {
|
|||||||
|
|
||||||
// Triggered is used to determine whether an alert has been triggered. When an alert is resolved, this value
|
// Triggered is used to determine whether an alert has been triggered. When an alert is resolved, this value
|
||||||
// should be set back to false. It is used to prevent the same alert from going out twice.
|
// should be set back to false. It is used to prevent the same alert from going out twice.
|
||||||
|
//
|
||||||
|
// This value should only be modified if the provider.AlertProvider's Send function does not return an error for an
|
||||||
|
// alert that hasn't been triggered yet. This doubles as a lazy retry. The reason why this behavior isn't also
|
||||||
|
// applied for alerts that are already triggered and has become "healthy" again is to prevent a case where, for
|
||||||
|
// some reason, the alert provider always returns errors when trying to send the resolved notification
|
||||||
|
// (SendOnResolved).
|
||||||
Triggered bool
|
Triggered bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package core
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -48,11 +47,20 @@ const (
|
|||||||
CertificateExpirationPlaceholder = "[CERTIFICATE_EXPIRATION]"
|
CertificateExpirationPlaceholder = "[CERTIFICATE_EXPIRATION]"
|
||||||
|
|
||||||
// LengthFunctionPrefix is the prefix for the length function
|
// LengthFunctionPrefix is the prefix for the length function
|
||||||
|
//
|
||||||
|
// Usage: len([BODY].articles) == 10, len([BODY].name) > 5
|
||||||
LengthFunctionPrefix = "len("
|
LengthFunctionPrefix = "len("
|
||||||
|
|
||||||
// PatternFunctionPrefix is the prefix for the pattern function
|
// PatternFunctionPrefix is the prefix for the pattern function
|
||||||
|
//
|
||||||
|
// Usage: pat(192.168.*.*)
|
||||||
PatternFunctionPrefix = "pat("
|
PatternFunctionPrefix = "pat("
|
||||||
|
|
||||||
|
// AnyFunctionPrefix is the prefix for the any function
|
||||||
|
//
|
||||||
|
// Usage: any(1.1.1.1, 1.0.0.1)
|
||||||
|
AnyFunctionPrefix = "any("
|
||||||
|
|
||||||
// FunctionSuffix is the suffix for all functions
|
// FunctionSuffix is the suffix for all functions
|
||||||
FunctionSuffix = ")"
|
FunctionSuffix = ")"
|
||||||
|
|
||||||
@@ -64,51 +72,52 @@ const (
|
|||||||
type Condition string
|
type Condition string
|
||||||
|
|
||||||
// evaluate the Condition with the Result of the health check
|
// evaluate the Condition with the Result of the health check
|
||||||
func (c *Condition) evaluate(result *Result) bool {
|
func (c Condition) evaluate(result *Result) bool {
|
||||||
condition := string(*c)
|
condition := string(c)
|
||||||
success := false
|
success := false
|
||||||
var resolvedCondition string
|
conditionToDisplay := condition
|
||||||
if strings.Contains(condition, "==") {
|
if strings.Contains(condition, "==") {
|
||||||
parts := sanitizeAndResolve(strings.Split(condition, "=="), result)
|
parameters, resolvedParameters := sanitizeAndResolve(strings.Split(condition, "=="), result)
|
||||||
success = isEqual(parts[0], parts[1])
|
success = isEqual(resolvedParameters[0], resolvedParameters[1])
|
||||||
resolvedCondition = fmt.Sprintf("%v == %v", parts[0], parts[1])
|
if !success {
|
||||||
|
conditionToDisplay = prettify(parameters, resolvedParameters, "==")
|
||||||
|
}
|
||||||
} else if strings.Contains(condition, "!=") {
|
} else if strings.Contains(condition, "!=") {
|
||||||
parts := sanitizeAndResolve(strings.Split(condition, "!="), result)
|
parameters, resolvedParameters := sanitizeAndResolve(strings.Split(condition, "!="), result)
|
||||||
success = !isEqual(parts[0], parts[1])
|
success = !isEqual(resolvedParameters[0], resolvedParameters[1])
|
||||||
resolvedCondition = fmt.Sprintf("%v != %v", parts[0], parts[1])
|
if !success {
|
||||||
|
conditionToDisplay = prettify(parameters, resolvedParameters, "!=")
|
||||||
|
}
|
||||||
} else if strings.Contains(condition, "<=") {
|
} else if strings.Contains(condition, "<=") {
|
||||||
parts := sanitizeAndResolveNumerical(strings.Split(condition, "<="), result)
|
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, "<="), result)
|
||||||
success = parts[0] <= parts[1]
|
success = resolvedParameters[0] <= resolvedParameters[1]
|
||||||
resolvedCondition = fmt.Sprintf("%v <= %v", parts[0], parts[1])
|
if !success {
|
||||||
|
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, "<=")
|
||||||
|
}
|
||||||
} else if strings.Contains(condition, ">=") {
|
} else if strings.Contains(condition, ">=") {
|
||||||
parts := sanitizeAndResolveNumerical(strings.Split(condition, ">="), result)
|
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, ">="), result)
|
||||||
success = parts[0] >= parts[1]
|
success = resolvedParameters[0] >= resolvedParameters[1]
|
||||||
resolvedCondition = fmt.Sprintf("%v >= %v", parts[0], parts[1])
|
if !success {
|
||||||
|
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, ">=")
|
||||||
|
}
|
||||||
} else if strings.Contains(condition, ">") {
|
} else if strings.Contains(condition, ">") {
|
||||||
parts := sanitizeAndResolveNumerical(strings.Split(condition, ">"), result)
|
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, ">"), result)
|
||||||
success = parts[0] > parts[1]
|
success = resolvedParameters[0] > resolvedParameters[1]
|
||||||
resolvedCondition = fmt.Sprintf("%v > %v", parts[0], parts[1])
|
if !success {
|
||||||
|
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, ">")
|
||||||
|
}
|
||||||
} else if strings.Contains(condition, "<") {
|
} else if strings.Contains(condition, "<") {
|
||||||
parts := sanitizeAndResolveNumerical(strings.Split(condition, "<"), result)
|
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, "<"), result)
|
||||||
success = parts[0] < parts[1]
|
success = resolvedParameters[0] < resolvedParameters[1]
|
||||||
resolvedCondition = fmt.Sprintf("%v < %v", parts[0], parts[1])
|
if !success {
|
||||||
|
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, "<")
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
result.Errors = append(result.Errors, fmt.Sprintf("invalid condition '%s' has been provided", condition))
|
result.Errors = append(result.Errors, fmt.Sprintf("invalid condition '%s' has been provided", condition))
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
conditionToDisplay := condition
|
|
||||||
// If the condition isn't a success, return what the resolved condition was too
|
|
||||||
if !success {
|
if !success {
|
||||||
log.Printf("[Condition][evaluate] Condition '%s' did not succeed because '%s' is false", condition, resolvedCondition)
|
//log.Printf("[Condition][evaluate] Condition '%s' did not succeed because '%s' is false", condition, condition)
|
||||||
// Check if the resolved condition was an invalid path
|
|
||||||
isResolvedConditionInvalidPath := strings.ReplaceAll(resolvedCondition, fmt.Sprintf("%s ", InvalidConditionElementSuffix), "") == condition
|
|
||||||
if isResolvedConditionInvalidPath {
|
|
||||||
// Since, in the event of an invalid path, the resolvedCondition contains the condition itself,
|
|
||||||
// we'll only display the resolvedCondition
|
|
||||||
conditionToDisplay = resolvedCondition
|
|
||||||
} else {
|
|
||||||
conditionToDisplay = fmt.Sprintf("%s (%s)", condition, resolvedCondition)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
result.ConditionResults = append(result.ConditionResults, &ConditionResult{Condition: conditionToDisplay, Success: success})
|
result.ConditionResults = append(result.ConditionResults, &ConditionResult{Condition: conditionToDisplay, Success: success})
|
||||||
return success
|
return success
|
||||||
@@ -116,33 +125,66 @@ func (c *Condition) evaluate(result *Result) bool {
|
|||||||
|
|
||||||
// isEqual compares two strings.
|
// isEqual compares two strings.
|
||||||
//
|
//
|
||||||
// It also supports the pattern function. That is to say, if one of the strings starts with PatternFunctionPrefix
|
// Supports the pattern and the any functions.
|
||||||
// and ends with FunctionSuffix, it will be treated like a pattern.
|
// i.e. if one of the parameters starts with PatternFunctionPrefix and ends with FunctionSuffix, it will be treated like
|
||||||
|
// a pattern.
|
||||||
func isEqual(first, second string) bool {
|
func isEqual(first, second string) bool {
|
||||||
var isFirstPattern, isSecondPattern bool
|
firstHasFunctionSuffix := strings.HasSuffix(first, FunctionSuffix)
|
||||||
if strings.HasPrefix(first, PatternFunctionPrefix) && strings.HasSuffix(first, FunctionSuffix) {
|
secondHasFunctionSuffix := strings.HasSuffix(second, FunctionSuffix)
|
||||||
isFirstPattern = true
|
if firstHasFunctionSuffix || secondHasFunctionSuffix {
|
||||||
first = strings.TrimSuffix(strings.TrimPrefix(first, PatternFunctionPrefix), FunctionSuffix)
|
var isFirstPattern, isSecondPattern bool
|
||||||
}
|
if strings.HasPrefix(first, PatternFunctionPrefix) && firstHasFunctionSuffix {
|
||||||
if strings.HasPrefix(second, PatternFunctionPrefix) && strings.HasSuffix(second, FunctionSuffix) {
|
isFirstPattern = true
|
||||||
isSecondPattern = true
|
first = strings.TrimSuffix(strings.TrimPrefix(first, PatternFunctionPrefix), FunctionSuffix)
|
||||||
second = strings.TrimSuffix(strings.TrimPrefix(second, PatternFunctionPrefix), FunctionSuffix)
|
}
|
||||||
}
|
if strings.HasPrefix(second, PatternFunctionPrefix) && secondHasFunctionSuffix {
|
||||||
if isFirstPattern && !isSecondPattern {
|
isSecondPattern = true
|
||||||
return pattern.Match(first, second)
|
second = strings.TrimSuffix(strings.TrimPrefix(second, PatternFunctionPrefix), FunctionSuffix)
|
||||||
} else if !isFirstPattern && isSecondPattern {
|
}
|
||||||
return pattern.Match(second, first)
|
if isFirstPattern && !isSecondPattern {
|
||||||
} else {
|
return pattern.Match(first, second)
|
||||||
return first == second
|
} else if !isFirstPattern && isSecondPattern {
|
||||||
|
return pattern.Match(second, first)
|
||||||
|
}
|
||||||
|
var isFirstAny, isSecondAny bool
|
||||||
|
if strings.HasPrefix(first, AnyFunctionPrefix) && firstHasFunctionSuffix {
|
||||||
|
isFirstAny = true
|
||||||
|
first = strings.TrimSuffix(strings.TrimPrefix(first, AnyFunctionPrefix), FunctionSuffix)
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(second, AnyFunctionPrefix) && secondHasFunctionSuffix {
|
||||||
|
isSecondAny = true
|
||||||
|
second = strings.TrimSuffix(strings.TrimPrefix(second, AnyFunctionPrefix), FunctionSuffix)
|
||||||
|
}
|
||||||
|
if isFirstAny && !isSecondAny {
|
||||||
|
options := strings.Split(first, ",")
|
||||||
|
for _, option := range options {
|
||||||
|
if strings.TrimSpace(option) == second {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
} else if !isFirstAny && isSecondAny {
|
||||||
|
options := strings.Split(second, ",")
|
||||||
|
for _, option := range options {
|
||||||
|
if strings.TrimSpace(option) == first {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return first == second
|
||||||
}
|
}
|
||||||
|
|
||||||
// sanitizeAndResolve sanitizes and resolves a list of element and returns the list of resolved elements
|
// sanitizeAndResolve sanitizes and resolves a list of elements and returns the list of parameters as well as a list
|
||||||
func sanitizeAndResolve(list []string, result *Result) []string {
|
// of resolved parameters
|
||||||
var sanitizedList []string
|
func sanitizeAndResolve(elements []string, result *Result) ([]string, []string) {
|
||||||
|
parameters := make([]string, len(elements))
|
||||||
|
resolvedParameters := make([]string, len(elements))
|
||||||
body := strings.TrimSpace(string(result.Body))
|
body := strings.TrimSpace(string(result.Body))
|
||||||
for _, element := range list {
|
for i, element := range elements {
|
||||||
element = strings.TrimSpace(element)
|
element = strings.TrimSpace(element)
|
||||||
|
parameters[i] = element
|
||||||
switch strings.ToUpper(element) {
|
switch strings.ToUpper(element) {
|
||||||
case StatusPlaceholder:
|
case StatusPlaceholder:
|
||||||
element = strconv.Itoa(result.HTTPStatus)
|
element = strconv.Itoa(result.HTTPStatus)
|
||||||
@@ -166,42 +208,68 @@ func sanitizeAndResolve(list []string, result *Result) []string {
|
|||||||
wantLength = true
|
wantLength = true
|
||||||
element = strings.TrimSuffix(strings.TrimPrefix(element, LengthFunctionPrefix), FunctionSuffix)
|
element = strings.TrimSuffix(strings.TrimPrefix(element, LengthFunctionPrefix), FunctionSuffix)
|
||||||
}
|
}
|
||||||
resolvedElement, resolvedElementLength, err := jsonpath.Eval(strings.Replace(element, fmt.Sprintf("%s.", BodyPlaceholder), "", 1), result.Body)
|
resolvedElement, resolvedElementLength, err := jsonpath.Eval(strings.TrimPrefix(element, BodyPlaceholder+"."), result.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err.Error() != "unexpected end of JSON input" {
|
if err.Error() != "unexpected end of JSON input" {
|
||||||
result.Errors = append(result.Errors, err.Error())
|
result.Errors = append(result.Errors, err.Error())
|
||||||
}
|
}
|
||||||
if wantLength {
|
if wantLength {
|
||||||
element = fmt.Sprintf("%s%s%s %s", LengthFunctionPrefix, element, FunctionSuffix, InvalidConditionElementSuffix)
|
element = LengthFunctionPrefix + element + FunctionSuffix + " " + InvalidConditionElementSuffix
|
||||||
} else {
|
} else {
|
||||||
element = fmt.Sprintf("%s %s", element, InvalidConditionElementSuffix)
|
element = element + " " + InvalidConditionElementSuffix
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if wantLength {
|
if wantLength {
|
||||||
element = fmt.Sprintf("%d", resolvedElementLength)
|
element = strconv.Itoa(resolvedElementLength)
|
||||||
} else {
|
} else {
|
||||||
element = resolvedElement
|
element = resolvedElement
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sanitizedList = append(sanitizedList, element)
|
resolvedParameters[i] = element
|
||||||
}
|
}
|
||||||
return sanitizedList
|
return parameters, resolvedParameters
|
||||||
}
|
}
|
||||||
|
|
||||||
func sanitizeAndResolveNumerical(list []string, result *Result) []int64 {
|
func sanitizeAndResolveNumerical(list []string, result *Result) (parameters []string, resolvedNumericalParameters []int64) {
|
||||||
var sanitizedNumbers []int64
|
parameters, resolvedParameters := sanitizeAndResolve(list, result)
|
||||||
sanitizedList := sanitizeAndResolve(list, result)
|
for _, element := range resolvedParameters {
|
||||||
for _, element := range sanitizedList {
|
|
||||||
if duration, err := time.ParseDuration(element); duration != 0 && err == nil {
|
if duration, err := time.ParseDuration(element); duration != 0 && err == nil {
|
||||||
sanitizedNumbers = append(sanitizedNumbers, duration.Milliseconds())
|
resolvedNumericalParameters = append(resolvedNumericalParameters, duration.Milliseconds())
|
||||||
} else if number, err := strconv.ParseInt(element, 10, 64); err != nil {
|
} else if number, err := strconv.ParseInt(element, 10, 64); err != nil {
|
||||||
// Default to 0 if the string couldn't be converted to an integer
|
// Default to 0 if the string couldn't be converted to an integer
|
||||||
sanitizedNumbers = append(sanitizedNumbers, 0)
|
resolvedNumericalParameters = append(resolvedNumericalParameters, 0)
|
||||||
} else {
|
} else {
|
||||||
sanitizedNumbers = append(sanitizedNumbers, number)
|
resolvedNumericalParameters = append(resolvedNumericalParameters, number)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return sanitizedNumbers
|
return parameters, resolvedNumericalParameters
|
||||||
|
}
|
||||||
|
|
||||||
|
func prettifyNumericalParameters(parameters []string, resolvedParameters []int64, operator string) string {
|
||||||
|
return prettify(parameters, []string{strconv.Itoa(int(resolvedParameters[0])), strconv.Itoa(int(resolvedParameters[1]))}, operator)
|
||||||
|
}
|
||||||
|
|
||||||
|
// XXX: make this configurable? i.e. show-resolved-conditions-on-failure
|
||||||
|
func prettify(parameters []string, resolvedParameters []string, operator string) string {
|
||||||
|
// Since, in the event of an invalid path, the resolvedParameters also contain the condition itself,
|
||||||
|
// we'll return the resolvedParameters as-is.
|
||||||
|
if strings.HasSuffix(resolvedParameters[0], InvalidConditionElementSuffix) || strings.HasSuffix(resolvedParameters[1], InvalidConditionElementSuffix) {
|
||||||
|
return resolvedParameters[0] + " " + operator + " " + resolvedParameters[1]
|
||||||
|
}
|
||||||
|
// First element is a placeholder
|
||||||
|
if parameters[0] != resolvedParameters[0] && parameters[1] == resolvedParameters[1] {
|
||||||
|
return parameters[0] + " (" + resolvedParameters[0] + ") " + operator + " " + parameters[1]
|
||||||
|
}
|
||||||
|
// Second element is a placeholder
|
||||||
|
if parameters[0] == resolvedParameters[0] && parameters[1] != resolvedParameters[1] {
|
||||||
|
return parameters[0] + " " + operator + " " + parameters[1] + " (" + resolvedParameters[1] + ")"
|
||||||
|
}
|
||||||
|
// Both elements are placeholders...?
|
||||||
|
if parameters[0] != resolvedParameters[0] && parameters[1] != resolvedParameters[1] {
|
||||||
|
return parameters[0] + " (" + resolvedParameters[0] + ") " + operator + " " + parameters[1] + " (" + resolvedParameters[1] + ")"
|
||||||
|
}
|
||||||
|
// Neither elements are placeholders
|
||||||
|
return parameters[0] + " " + operator + " " + parameters[1]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithBodyStringAny(b *testing.B) {
|
||||||
|
condition := Condition("[BODY].name == any(john.doe, jane.doe)")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"john.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithBodyStringAnyFailure(b *testing.B) {
|
||||||
|
condition := Condition("[BODY].name == any(john.doe, jane.doe)")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"bob.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithBodyString(b *testing.B) {
|
||||||
|
condition := Condition("[BODY].name == john.doe")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"john.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithBodyStringFailure(b *testing.B) {
|
||||||
|
condition := Condition("[BODY].name == john.doe")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"bob.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithBodyStringLen(b *testing.B) {
|
||||||
|
condition := Condition("len([BODY].name) == 8")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"john.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithBodyStringLenFailure(b *testing.B) {
|
||||||
|
condition := Condition("len([BODY].name) == 8")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"bob.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithStatus(b *testing.B) {
|
||||||
|
condition := Condition("[STATUS] == 200")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{HTTPStatus: 200}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCondition_evaluateWithStatusFailure(b *testing.B) {
|
||||||
|
condition := Condition("[STATUS] == 200")
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
result := &Result{HTTPStatus: 400}
|
||||||
|
condition.evaluate(result)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package core
|
package core
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -22,6 +23,9 @@ func TestCondition_evaluateWithStatus(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
if result.ConditionResults[0].Condition != string(condition) {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, condition, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithStatusFailure(t *testing.T) {
|
func TestCondition_evaluateWithStatusFailure(t *testing.T) {
|
||||||
@@ -31,6 +35,10 @@ func TestCondition_evaluateWithStatusFailure(t *testing.T) {
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[STATUS] (500) == 200"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithStatusUsingLessThan(t *testing.T) {
|
func TestCondition_evaluateWithStatusUsingLessThan(t *testing.T) {
|
||||||
@@ -40,6 +48,10 @@ func TestCondition_evaluateWithStatusUsingLessThan(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[STATUS] < 300"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithStatusFailureUsingLessThan(t *testing.T) {
|
func TestCondition_evaluateWithStatusFailureUsingLessThan(t *testing.T) {
|
||||||
@@ -49,6 +61,10 @@ func TestCondition_evaluateWithStatusFailureUsingLessThan(t *testing.T) {
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[STATUS] (404) < 300"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithResponseTimeUsingLessThan(t *testing.T) {
|
func TestCondition_evaluateWithResponseTimeUsingLessThan(t *testing.T) {
|
||||||
@@ -58,6 +74,10 @@ func TestCondition_evaluateWithResponseTimeUsingLessThan(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[RESPONSE_TIME] < 500"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithResponseTimeUsingLessThanDuration(t *testing.T) {
|
func TestCondition_evaluateWithResponseTimeUsingLessThanDuration(t *testing.T) {
|
||||||
@@ -67,6 +87,10 @@ func TestCondition_evaluateWithResponseTimeUsingLessThanDuration(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[RESPONSE_TIME] < 1s"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithResponseTimeUsingLessThanInvalid(t *testing.T) {
|
func TestCondition_evaluateWithResponseTimeUsingLessThanInvalid(t *testing.T) {
|
||||||
@@ -76,6 +100,10 @@ func TestCondition_evaluateWithResponseTimeUsingLessThanInvalid(t *testing.T) {
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have failed because the condition has an invalid numerical value that should've automatically resolved to 0", condition)
|
t.Errorf("Condition '%s' should have failed because the condition has an invalid numerical value that should've automatically resolved to 0", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[RESPONSE_TIME] (50) < potato (0)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithResponseTimeUsingGreaterThan(t *testing.T) {
|
func TestCondition_evaluateWithResponseTimeUsingGreaterThan(t *testing.T) {
|
||||||
@@ -87,6 +115,10 @@ func TestCondition_evaluateWithResponseTimeUsingGreaterThan(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[RESPONSE_TIME] > 500"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithResponseTimeUsingGreaterThanDuration(t *testing.T) {
|
func TestCondition_evaluateWithResponseTimeUsingGreaterThanDuration(t *testing.T) {
|
||||||
@@ -96,6 +128,10 @@ func TestCondition_evaluateWithResponseTimeUsingGreaterThanDuration(t *testing.T
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[RESPONSE_TIME] > 1s"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithResponseTimeUsingGreaterThanOrEqualTo(t *testing.T) {
|
func TestCondition_evaluateWithResponseTimeUsingGreaterThanOrEqualTo(t *testing.T) {
|
||||||
@@ -105,6 +141,10 @@ func TestCondition_evaluateWithResponseTimeUsingGreaterThanOrEqualTo(t *testing.
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[RESPONSE_TIME] >= 500"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithResponseTimeUsingLessThanOrEqualTo(t *testing.T) {
|
func TestCondition_evaluateWithResponseTimeUsingLessThanOrEqualTo(t *testing.T) {
|
||||||
@@ -114,6 +154,10 @@ func TestCondition_evaluateWithResponseTimeUsingLessThanOrEqualTo(t *testing.T)
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[RESPONSE_TIME] <= 500"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBody(t *testing.T) {
|
func TestCondition_evaluateWithBody(t *testing.T) {
|
||||||
@@ -123,6 +167,10 @@ func TestCondition_evaluateWithBody(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY] == test"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPath(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPath(t *testing.T) {
|
||||||
@@ -132,6 +180,10 @@ func TestCondition_evaluateWithBodyJSONPath(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].status == UP"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathComplex(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathComplex(t *testing.T) {
|
||||||
@@ -141,31 +193,35 @@ func TestCondition_evaluateWithBodyJSONPathComplex(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].data.name == john"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithInvalidBodyJSONPathComplex(t *testing.T) {
|
func TestCondition_evaluateWithInvalidBodyJSONPathComplex(t *testing.T) {
|
||||||
expectedResolvedCondition := "[BODY].data.name (INVALID) == john"
|
|
||||||
condition := Condition("[BODY].data.name == john")
|
condition := Condition("[BODY].data.name == john")
|
||||||
result := &Result{Body: []byte("{\"data\": {\"id\": 1}}")}
|
result := &Result{Body: []byte("{\"data\": {\"id\": 1}}")}
|
||||||
condition.evaluate(result)
|
condition.evaluate(result)
|
||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure, because the path was invalid", condition)
|
t.Errorf("Condition '%s' should have been a failure, because the path was invalid", condition)
|
||||||
}
|
}
|
||||||
if result.ConditionResults[0].Condition != expectedResolvedCondition {
|
expectedConditionDisplayed := "[BODY].data.name (INVALID) == john"
|
||||||
t.Errorf("Condition '%s' should have resolved to '%s', but resolved to '%s' instead", condition, expectedResolvedCondition, result.ConditionResults[0].Condition)
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithInvalidBodyJSONPathComplexWithLengthFunction(t *testing.T) {
|
func TestCondition_evaluateWithInvalidBodyJSONPathComplexWithLengthFunction(t *testing.T) {
|
||||||
expectedResolvedCondition := "len([BODY].data.name) (INVALID) == john"
|
|
||||||
condition := Condition("len([BODY].data.name) == john")
|
condition := Condition("len([BODY].data.name) == john")
|
||||||
result := &Result{Body: []byte("{\"data\": {\"id\": 1}}")}
|
result := &Result{Body: []byte("{\"data\": {\"id\": 1}}")}
|
||||||
condition.evaluate(result)
|
condition.evaluate(result)
|
||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure, because the path was invalid", condition)
|
t.Errorf("Condition '%s' should have been a failure, because the path was invalid", condition)
|
||||||
}
|
}
|
||||||
if result.ConditionResults[0].Condition != expectedResolvedCondition {
|
expectedConditionDisplayed := "len([BODY].data.name) (INVALID) == john"
|
||||||
t.Errorf("Condition '%s' should have resolved to '%s', but resolved to '%s' instead", condition, expectedResolvedCondition, result.ConditionResults[0].Condition)
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,6 +232,10 @@ func TestCondition_evaluateWithBodyJSONPathDoublePlaceholders(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].user.firstName != [BODY].user.lastName"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathDoublePlaceholdersFailure(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathDoublePlaceholdersFailure(t *testing.T) {
|
||||||
@@ -185,6 +245,10 @@ func TestCondition_evaluateWithBodyJSONPathDoublePlaceholdersFailure(t *testing.
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].user.firstName (john) == [BODY].user.lastName (doe)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathLongInt(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathLongInt(t *testing.T) {
|
||||||
@@ -194,6 +258,10 @@ func TestCondition_evaluateWithBodyJSONPathLongInt(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].data.id == 1"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathComplexInt(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathComplexInt(t *testing.T) {
|
||||||
@@ -203,6 +271,10 @@ func TestCondition_evaluateWithBodyJSONPathComplexInt(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].data[1].id == 2"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathComplexIntUsingGreaterThan(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathComplexIntUsingGreaterThan(t *testing.T) {
|
||||||
@@ -212,6 +284,10 @@ func TestCondition_evaluateWithBodyJSONPathComplexIntUsingGreaterThan(t *testing
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].data.id > 0"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathComplexIntFailureUsingGreaterThan(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathComplexIntFailureUsingGreaterThan(t *testing.T) {
|
||||||
@@ -221,6 +297,10 @@ func TestCondition_evaluateWithBodyJSONPathComplexIntFailureUsingGreaterThan(t *
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].data.id (1) > 5"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathComplexIntUsingLessThan(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathComplexIntUsingLessThan(t *testing.T) {
|
||||||
@@ -230,6 +310,10 @@ func TestCondition_evaluateWithBodyJSONPathComplexIntUsingLessThan(t *testing.T)
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].data.id < 5"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyJSONPathComplexIntFailureUsingLessThan(t *testing.T) {
|
func TestCondition_evaluateWithBodyJSONPathComplexIntFailureUsingLessThan(t *testing.T) {
|
||||||
@@ -239,6 +323,10 @@ func TestCondition_evaluateWithBodyJSONPathComplexIntFailureUsingLessThan(t *tes
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].data.id (10) < 5"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodySliceLength(t *testing.T) {
|
func TestCondition_evaluateWithBodySliceLength(t *testing.T) {
|
||||||
@@ -248,6 +336,10 @@ func TestCondition_evaluateWithBodySliceLength(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "len([BODY].data) == 3"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyStringLength(t *testing.T) {
|
func TestCondition_evaluateWithBodyStringLength(t *testing.T) {
|
||||||
@@ -257,6 +349,36 @@ func TestCondition_evaluateWithBodyStringLength(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "len([BODY].name) == 8"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithBodyPattern(t *testing.T) {
|
||||||
|
condition := Condition("[BODY] == pat(*john*)")
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"john.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if !result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY] == pat(*john*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithReverseBodyPattern(t *testing.T) {
|
||||||
|
condition := Condition("pat(*john*) == [BODY]")
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"john.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if !result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := "pat(*john*) == [BODY]"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyStringPattern(t *testing.T) {
|
func TestCondition_evaluateWithBodyStringPattern(t *testing.T) {
|
||||||
@@ -266,6 +388,24 @@ func TestCondition_evaluateWithBodyStringPattern(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].name == pat(*ohn*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithBodyHTMLPattern(t *testing.T) {
|
||||||
|
var html = `<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><div id="user">john.doe</div></body></html>`
|
||||||
|
condition := Condition("[BODY] == pat(*<div id=\"user\">john.doe</div>*)")
|
||||||
|
result := &Result{Body: []byte(html)}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if !result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY] == pat(*<div id=\"user\">john.doe</div>*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithBodyStringPatternFailure(t *testing.T) {
|
func TestCondition_evaluateWithBodyStringPatternFailure(t *testing.T) {
|
||||||
@@ -275,14 +415,9 @@ func TestCondition_evaluateWithBodyStringPatternFailure(t *testing.T) {
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
}
|
expectedConditionDisplayed := "[BODY].name (john.doe) == pat(bob*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
func TestCondition_evaluateWithBodyPatternFailure(t *testing.T) {
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
condition := Condition("[BODY] == pat(*john*)")
|
|
||||||
result := &Result{Body: []byte("{\"name\": \"john.doe\"}")}
|
|
||||||
condition.evaluate(result)
|
|
||||||
if !result.ConditionResults[0].Success {
|
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,6 +428,10 @@ func TestCondition_evaluateWithIPPattern(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[IP] == pat(10.*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithIPPatternFailure(t *testing.T) {
|
func TestCondition_evaluateWithIPPatternFailure(t *testing.T) {
|
||||||
@@ -302,6 +441,10 @@ func TestCondition_evaluateWithIPPatternFailure(t *testing.T) {
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[IP] (255.255.255.255) == pat(10.*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithStatusPattern(t *testing.T) {
|
func TestCondition_evaluateWithStatusPattern(t *testing.T) {
|
||||||
@@ -311,6 +454,10 @@ func TestCondition_evaluateWithStatusPattern(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[STATUS] == pat(4*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithStatusPatternFailure(t *testing.T) {
|
func TestCondition_evaluateWithStatusPatternFailure(t *testing.T) {
|
||||||
@@ -320,6 +467,105 @@ func TestCondition_evaluateWithStatusPatternFailure(t *testing.T) {
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[STATUS] (404) != pat(4*)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithBodyStringAny(t *testing.T) {
|
||||||
|
condition := Condition("[BODY].name == any(john.doe, jane.doe)")
|
||||||
|
expectedConditionDisplayed := "[BODY].name == any(john.doe, jane.doe)"
|
||||||
|
results := []*Result{
|
||||||
|
{Body: []byte("{\"name\": \"john.doe\"}")},
|
||||||
|
{Body: []byte("{\"name\": \"jane.doe\"}")},
|
||||||
|
}
|
||||||
|
for _, result := range results {
|
||||||
|
success := condition.evaluate(result)
|
||||||
|
if !success || !result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
|
}
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithBodyStringAnyFailure(t *testing.T) {
|
||||||
|
condition := Condition("[BODY].name == any(john.doe, jane.doe)")
|
||||||
|
result := &Result{Body: []byte("{\"name\": \"bob.doe\"}")}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := "[BODY].name (bob.doe) == any(john.doe, jane.doe)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithStatusAny(t *testing.T) {
|
||||||
|
condition := Condition("[STATUS] == any(200, 429)")
|
||||||
|
statuses := []int{200, 429}
|
||||||
|
for _, status := range statuses {
|
||||||
|
result := &Result{HTTPStatus: status}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if !result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := "[STATUS] == any(200, 429)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithReverseStatusAny(t *testing.T) {
|
||||||
|
condition := Condition("any(200, 429) == [STATUS]")
|
||||||
|
statuses := []int{200, 429}
|
||||||
|
for _, status := range statuses {
|
||||||
|
result := &Result{HTTPStatus: status}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if !result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := "any(200, 429) == [STATUS]"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithStatusAnyFailure(t *testing.T) {
|
||||||
|
condition := Condition("[STATUS] == any(200, 429)")
|
||||||
|
statuses := []int{201, 400, 404, 500}
|
||||||
|
for _, status := range statuses {
|
||||||
|
result := &Result{HTTPStatus: status}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := fmt.Sprintf("[STATUS] (%d) == any(200, 429)", status)
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCondition_evaluateWithReverseStatusAnyFailure(t *testing.T) {
|
||||||
|
condition := Condition("any(200, 429) == [STATUS]")
|
||||||
|
statuses := []int{201, 400, 404, 500}
|
||||||
|
for _, status := range statuses {
|
||||||
|
result := &Result{HTTPStatus: status}
|
||||||
|
condition.evaluate(result)
|
||||||
|
if result.ConditionResults[0].Success {
|
||||||
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
|
}
|
||||||
|
expectedConditionDisplayed := fmt.Sprintf("any(200, 429) == [STATUS] (%d)", status)
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithConnected(t *testing.T) {
|
func TestCondition_evaluateWithConnected(t *testing.T) {
|
||||||
@@ -329,6 +575,10 @@ func TestCondition_evaluateWithConnected(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[CONNECTED] == true"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithConnectedFailure(t *testing.T) {
|
func TestCondition_evaluateWithConnectedFailure(t *testing.T) {
|
||||||
@@ -338,6 +588,10 @@ func TestCondition_evaluateWithConnectedFailure(t *testing.T) {
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[CONNECTED] (false) == true"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithUnsetCertificateExpiration(t *testing.T) {
|
func TestCondition_evaluateWithUnsetCertificateExpiration(t *testing.T) {
|
||||||
@@ -347,6 +601,10 @@ func TestCondition_evaluateWithUnsetCertificateExpiration(t *testing.T) {
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[CERTIFICATE_EXPIRATION] == 0"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithCertificateExpirationGreaterThanNumerical(t *testing.T) {
|
func TestCondition_evaluateWithCertificateExpirationGreaterThanNumerical(t *testing.T) {
|
||||||
@@ -357,6 +615,10 @@ func TestCondition_evaluateWithCertificateExpirationGreaterThanNumerical(t *test
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[CERTIFICATE_EXPIRATION] > 2419200000"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithCertificateExpirationGreaterThanNumericalFailure(t *testing.T) {
|
func TestCondition_evaluateWithCertificateExpirationGreaterThanNumericalFailure(t *testing.T) {
|
||||||
@@ -367,6 +629,10 @@ func TestCondition_evaluateWithCertificateExpirationGreaterThanNumericalFailure(
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[CERTIFICATE_EXPIRATION] (1209600000) > 2419200000"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithCertificateExpirationGreaterThanDuration(t *testing.T) {
|
func TestCondition_evaluateWithCertificateExpirationGreaterThanDuration(t *testing.T) {
|
||||||
@@ -376,6 +642,10 @@ func TestCondition_evaluateWithCertificateExpirationGreaterThanDuration(t *testi
|
|||||||
if !result.ConditionResults[0].Success {
|
if !result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a success", condition)
|
t.Errorf("Condition '%s' should have been a success", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[CERTIFICATE_EXPIRATION] > 12h"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCondition_evaluateWithCertificateExpirationGreaterThanDurationFailure(t *testing.T) {
|
func TestCondition_evaluateWithCertificateExpirationGreaterThanDurationFailure(t *testing.T) {
|
||||||
@@ -385,4 +655,8 @@ func TestCondition_evaluateWithCertificateExpirationGreaterThanDurationFailure(t
|
|||||||
if result.ConditionResults[0].Success {
|
if result.ConditionResults[0].Success {
|
||||||
t.Errorf("Condition '%s' should have been a failure", condition)
|
t.Errorf("Condition '%s' should have been a failure", condition)
|
||||||
}
|
}
|
||||||
|
expectedConditionDisplayed := "[CERTIFICATE_EXPIRATION] (86400000) > 48h (172800000)"
|
||||||
|
if result.ConditionResults[0].Condition != expectedConditionDisplayed {
|
||||||
|
t.Errorf("Condition '%s' should have resolved to '%s', got '%s'", condition, expectedConditionDisplayed, result.ConditionResults[0].Condition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// Event is something that happens at a specific time
|
||||||
|
type Event struct {
|
||||||
|
// Type is the kind of event
|
||||||
|
Type EventType `json:"type"`
|
||||||
|
|
||||||
|
// Timestamp is the moment at which the event happened
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// EventType is, uh, the types of events?
|
||||||
|
type EventType string
|
||||||
|
|
||||||
|
var (
|
||||||
|
// EventStart is a type of event that represents when a service starts being monitored
|
||||||
|
EventStart EventType = "START"
|
||||||
|
|
||||||
|
// EventHealthy is a type of event that represents a service passing all of its conditions
|
||||||
|
EventHealthy EventType = "HEALTHY"
|
||||||
|
|
||||||
|
// EventUnhealthy is a type of event that represents a service failing one or more of its conditions
|
||||||
|
EventUnhealthy EventType = "UNHEALTHY"
|
||||||
|
)
|
||||||
@@ -31,7 +31,7 @@ type Result struct {
|
|||||||
Errors []string `json:"errors"`
|
Errors []string `json:"errors"`
|
||||||
|
|
||||||
// ConditionResults results of the service's conditions
|
// ConditionResults results of the service's conditions
|
||||||
ConditionResults []*ConditionResult `json:"condition-results"`
|
ConditionResults []*ConditionResult `json:"conditionResults"`
|
||||||
|
|
||||||
// Success whether the result signifies a success or not
|
// Success whether the result signifies a success or not
|
||||||
Success bool `json:"success"`
|
Success bool `json:"success"`
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
package core
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwinProduction/gatus/util"
|
||||||
|
)
|
||||||
|
|
||||||
// ServiceStatus contains the evaluation Results of a Service
|
// ServiceStatus contains the evaluation Results of a Service
|
||||||
type ServiceStatus struct {
|
type ServiceStatus struct {
|
||||||
// Name of the service
|
// Name of the service
|
||||||
@@ -8,11 +14,25 @@ type ServiceStatus struct {
|
|||||||
// Group the service is a part of. Used for grouping multiple services together on the front end.
|
// Group the service is a part of. Used for grouping multiple services together on the front end.
|
||||||
Group string `json:"group,omitempty"`
|
Group string `json:"group,omitempty"`
|
||||||
|
|
||||||
|
// Key is the key representing the ServiceStatus
|
||||||
|
Key string `json:"key"`
|
||||||
|
|
||||||
// Results is the list of service evaluation results
|
// Results is the list of service evaluation results
|
||||||
Results []*Result `json:"results"`
|
Results []*Result `json:"results"`
|
||||||
|
|
||||||
|
// Events is a list of events
|
||||||
|
//
|
||||||
|
// We don't expose this through JSON, because the main dashboard doesn't need to have this data.
|
||||||
|
// However, the detailed service page does leverage this by including it to a map that will be
|
||||||
|
// marshalled alongside the ServiceStatus.
|
||||||
|
Events []*Event `json:"-"`
|
||||||
|
|
||||||
// Uptime information on the service's uptime
|
// Uptime information on the service's uptime
|
||||||
Uptime *Uptime `json:"uptime"`
|
//
|
||||||
|
// We don't expose this through JSON, because the main dashboard doesn't need to have this data.
|
||||||
|
// However, the detailed service page does leverage this by including it to a map that will be
|
||||||
|
// marshalled alongside the ServiceStatus.
|
||||||
|
Uptime *Uptime `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewServiceStatus creates a new ServiceStatus
|
// NewServiceStatus creates a new ServiceStatus
|
||||||
@@ -20,14 +40,35 @@ func NewServiceStatus(service *Service) *ServiceStatus {
|
|||||||
return &ServiceStatus{
|
return &ServiceStatus{
|
||||||
Name: service.Name,
|
Name: service.Name,
|
||||||
Group: service.Group,
|
Group: service.Group,
|
||||||
|
Key: util.ConvertGroupAndServiceToKey(service.Group, service.Name),
|
||||||
Results: make([]*Result, 0),
|
Results: make([]*Result, 0),
|
||||||
Uptime: NewUptime(),
|
Events: []*Event{{
|
||||||
|
Type: EventStart,
|
||||||
|
Timestamp: time.Now(),
|
||||||
|
}},
|
||||||
|
Uptime: NewUptime(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddResult adds a Result to ServiceStatus.Results and makes sure that there are
|
// AddResult adds a Result to ServiceStatus.Results and makes sure that there are
|
||||||
// no more than 20 results in the Results slice
|
// no more than 20 results in the Results slice
|
||||||
func (ss *ServiceStatus) AddResult(result *Result) {
|
func (ss *ServiceStatus) AddResult(result *Result) {
|
||||||
|
if len(ss.Results) > 0 {
|
||||||
|
// Check if there's any change since the last result
|
||||||
|
// OR there's only 1 event, which only happens when there's a start event
|
||||||
|
if ss.Results[len(ss.Results)-1].Success != result.Success || len(ss.Events) == 1 {
|
||||||
|
event := &Event{Timestamp: result.Timestamp}
|
||||||
|
if result.Success {
|
||||||
|
event.Type = EventHealthy
|
||||||
|
} else {
|
||||||
|
event.Type = EventUnhealthy
|
||||||
|
}
|
||||||
|
ss.Events = append(ss.Events, event)
|
||||||
|
if len(ss.Events) > 20 {
|
||||||
|
ss.Events = ss.Events[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
ss.Results = append(ss.Results, result)
|
ss.Results = append(ss.Results, result)
|
||||||
if len(ss.Results) > 20 {
|
if len(ss.Results) > 20 {
|
||||||
ss.Results = ss.Results[1:]
|
ss.Results = ss.Results[1:]
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ func TestNewServiceStatus(t *testing.T) {
|
|||||||
if serviceStatus.Group != service.Group {
|
if serviceStatus.Group != service.Group {
|
||||||
t.Errorf("expected %s, got %s", service.Group, serviceStatus.Group)
|
t.Errorf("expected %s, got %s", service.Group, serviceStatus.Group)
|
||||||
}
|
}
|
||||||
|
if serviceStatus.Key != "group_name" {
|
||||||
|
t.Errorf("expected %s, got %s", "group_name", serviceStatus.Key)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestServiceStatus_AddResult(t *testing.T) {
|
func TestServiceStatus_AddResult(t *testing.T) {
|
||||||
|
|||||||
@@ -25,15 +25,20 @@ type Uptime struct {
|
|||||||
// LastHour is the uptime percentage over the past hour
|
// LastHour is the uptime percentage over the past hour
|
||||||
LastHour float64 `json:"1h"`
|
LastHour float64 `json:"1h"`
|
||||||
|
|
||||||
successCountPerHour map[string]uint64
|
// SuccessCountPerHour is a map containing the number of successes per hour, per timestamp following the
|
||||||
totalCountPerHour map[string]uint64
|
// custom RFC3339WithoutMinutesAndSeconds format
|
||||||
|
SuccessCountPerHour map[string]uint64 `json:"-"`
|
||||||
|
|
||||||
|
// TotalCountPerHour is a map containing the total number of checks per hour, per timestamp following the
|
||||||
|
// custom RFC3339WithoutMinutesAndSeconds format
|
||||||
|
TotalCountPerHour map[string]uint64 `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewUptime creates a new Uptime
|
// NewUptime creates a new Uptime
|
||||||
func NewUptime() *Uptime {
|
func NewUptime() *Uptime {
|
||||||
return &Uptime{
|
return &Uptime{
|
||||||
successCountPerHour: make(map[string]uint64),
|
SuccessCountPerHour: make(map[string]uint64),
|
||||||
totalCountPerHour: make(map[string]uint64),
|
TotalCountPerHour: make(map[string]uint64),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,16 +47,16 @@ func NewUptime() *Uptime {
|
|||||||
func (uptime *Uptime) ProcessResult(result *Result) {
|
func (uptime *Uptime) ProcessResult(result *Result) {
|
||||||
timestampDateWithHour := result.Timestamp.Format(RFC3339WithoutMinutesAndSeconds)
|
timestampDateWithHour := result.Timestamp.Format(RFC3339WithoutMinutesAndSeconds)
|
||||||
if result.Success {
|
if result.Success {
|
||||||
uptime.successCountPerHour[timestampDateWithHour]++
|
uptime.SuccessCountPerHour[timestampDateWithHour]++
|
||||||
}
|
}
|
||||||
uptime.totalCountPerHour[timestampDateWithHour]++
|
uptime.TotalCountPerHour[timestampDateWithHour]++
|
||||||
// Clean up only when we're starting to have too many useless keys
|
// Clean up only when we're starting to have too many useless keys
|
||||||
// Note that this is only triggered when there are more entries than there should be after
|
// Note that this is only triggered when there are more entries than there should be after
|
||||||
// 10 days, despite the fact that we are deleting everything that's older than 7 days.
|
// 10 days, despite the fact that we are deleting everything that's older than 7 days.
|
||||||
// This is to prevent re-iterating on every `ProcessResult` as soon as the uptime has been logged for 7 days.
|
// This is to prevent re-iterating on every `ProcessResult` as soon as the uptime has been logged for 7 days.
|
||||||
if len(uptime.totalCountPerHour) > numberOfHoursInTenDays {
|
if len(uptime.TotalCountPerHour) > numberOfHoursInTenDays {
|
||||||
sevenDaysAgo := time.Now().Add(-(sevenDays + time.Hour))
|
sevenDaysAgo := time.Now().Add(-(sevenDays + time.Hour))
|
||||||
for k := range uptime.totalCountPerHour {
|
for k := range uptime.TotalCountPerHour {
|
||||||
dateWithHour, err := time.Parse(time.RFC3339, k)
|
dateWithHour, err := time.Parse(time.RFC3339, k)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// This shouldn't happen, but we'll log it in case it does happen
|
// This shouldn't happen, but we'll log it in case it does happen
|
||||||
@@ -59,8 +64,8 @@ func (uptime *Uptime) ProcessResult(result *Result) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if sevenDaysAgo.Unix() > dateWithHour.Unix() {
|
if sevenDaysAgo.Unix() > dateWithHour.Unix() {
|
||||||
delete(uptime.totalCountPerHour, k)
|
delete(uptime.TotalCountPerHour, k)
|
||||||
delete(uptime.successCountPerHour, k)
|
delete(uptime.SuccessCountPerHour, k)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,8 +93,8 @@ func (uptime *Uptime) recalculate() {
|
|||||||
timestamp := now.Add(-sevenDays)
|
timestamp := now.Add(-sevenDays)
|
||||||
for now.Sub(timestamp) >= 0 {
|
for now.Sub(timestamp) >= 0 {
|
||||||
timestampDateWithHour := timestamp.Format(RFC3339WithoutMinutesAndSeconds)
|
timestampDateWithHour := timestamp.Format(RFC3339WithoutMinutesAndSeconds)
|
||||||
successCountForTimestamp := uptime.successCountPerHour[timestampDateWithHour]
|
successCountForTimestamp := uptime.SuccessCountPerHour[timestampDateWithHour]
|
||||||
totalCountForTimestamp := uptime.totalCountPerHour[timestampDateWithHour]
|
totalCountForTimestamp := uptime.TotalCountPerHour[timestampDateWithHour]
|
||||||
uptimeBrackets["7d_success"] += successCountForTimestamp
|
uptimeBrackets["7d_success"] += successCountForTimestamp
|
||||||
uptimeBrackets["7d_total"] += totalCountForTimestamp
|
uptimeBrackets["7d_total"] += totalCountForTimestamp
|
||||||
if now.Sub(timestamp) <= 24*time.Hour {
|
if now.Sub(timestamp) <= 24*time.Hour {
|
||||||
|
|||||||
@@ -51,8 +51,8 @@ func TestServiceStatus_AddResultUptimeIsCleaningUpAfterItself(t *testing.T) {
|
|||||||
timestamp := now.Add(-12 * 24 * time.Hour)
|
timestamp := now.Add(-12 * 24 * time.Hour)
|
||||||
for timestamp.Unix() <= now.Unix() {
|
for timestamp.Unix() <= now.Unix() {
|
||||||
serviceStatus.AddResult(&Result{Timestamp: timestamp, Success: true})
|
serviceStatus.AddResult(&Result{Timestamp: timestamp, Success: true})
|
||||||
if len(serviceStatus.Uptime.successCountPerHour) > numberOfHoursInTenDays {
|
if len(serviceStatus.Uptime.SuccessCountPerHour) > numberOfHoursInTenDays {
|
||||||
t.Errorf("At no point in time should there be more than %d entries in serviceStatus.successCountPerHour", numberOfHoursInTenDays)
|
t.Errorf("At no point in time should there be more than %d entries in serviceStatus.SuccessCountPerHour", numberOfHoursInTenDays)
|
||||||
}
|
}
|
||||||
//fmt.Printf("timestamp=%s; uptimeDuringLastHour=%f; timeAgo=%s\n", timestamp.Format(time.RFC3339), serviceStatus.UptimeDuringLastHour, time.Since(timestamp))
|
//fmt.Printf("timestamp=%s; uptimeDuringLastHour=%f; timeAgo=%s\n", timestamp.Format(time.RFC3339), serviceStatus.UptimeDuringLastHour, time.Since(timestamp))
|
||||||
if now.Sub(timestamp) > time.Hour && serviceStatus.Uptime.LastHour != 0 {
|
if now.Sub(timestamp) > time.Hour && serviceStatus.Uptime.LastHour != 0 {
|
||||||
|
|||||||
@@ -1,6 +1,16 @@
|
|||||||
|
alerting:
|
||||||
|
mattermost:
|
||||||
|
webhook-url: "http://mattermost:8065/hooks/tokengoeshere"
|
||||||
|
insecure: true
|
||||||
|
|
||||||
services:
|
services:
|
||||||
- name: example
|
- name: example
|
||||||
url: http://example.org
|
url: http://example.org
|
||||||
interval: 30s
|
interval: 1m
|
||||||
|
alerts:
|
||||||
|
- type: mattermost
|
||||||
|
enabled: true
|
||||||
|
description: "healthcheck failed 3 times in a row"
|
||||||
|
send-on-resolved: true
|
||||||
conditions:
|
conditions:
|
||||||
- "[STATUS] == 200"
|
- "[STATUS] == 200"
|
||||||
@@ -1,13 +1,24 @@
|
|||||||
version: "3.8"
|
version: "3.8"
|
||||||
services:
|
|
||||||
gatus:
|
|
||||||
image: twinproduction/gatus:latest
|
|
||||||
ports:
|
|
||||||
- 8080:8080
|
|
||||||
volumes:
|
|
||||||
- ./config.yaml:/config/config.yaml
|
|
||||||
|
|
||||||
mattermost-preview:
|
services:
|
||||||
image: mattermost/mattermost-preview:latest
|
gatus:
|
||||||
ports:
|
container_name: gatus
|
||||||
- 8065:8065
|
image: twinproduction/gatus:latest
|
||||||
|
ports:
|
||||||
|
- 8080:8080
|
||||||
|
volumes:
|
||||||
|
- ./config.yaml:/config/config.yaml
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
|
||||||
|
mattermost:
|
||||||
|
container_name: mattermost
|
||||||
|
image: mattermost/mattermost-preview:5.26.0
|
||||||
|
ports:
|
||||||
|
- 8065:8065
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
driver: bridge
|
||||||
@@ -4,7 +4,7 @@ go 1.15
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
cloud.google.com/go v0.74.0 // indirect
|
cloud.google.com/go v0.74.0 // indirect
|
||||||
github.com/TwinProduction/gocache v1.1.0
|
github.com/TwinProduction/gocache v1.2.0
|
||||||
github.com/go-ping/ping v0.0.0-20201115131931-3300c582a663
|
github.com/go-ping/ping v0.0.0-20201115131931-3300c582a663
|
||||||
github.com/google/gofuzz v1.2.0 // indirect
|
github.com/google/gofuzz v1.2.0 // indirect
|
||||||
github.com/gorilla/mux v1.8.0
|
github.com/gorilla/mux v1.8.0
|
||||||
|
|||||||
@@ -50,8 +50,8 @@ github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbt
|
|||||||
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
||||||
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
|
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
|
||||||
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
|
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
|
||||||
github.com/TwinProduction/gocache v1.1.0 h1:mibBUyccd8kGHlm5dXhTMDOvWBK4mjNqGyOOkG8mib8=
|
github.com/TwinProduction/gocache v1.2.0 h1:iZBUuri5VydxYhNkWEOZm/JzX/X2b3OZzfLrPaRWKjk=
|
||||||
github.com/TwinProduction/gocache v1.1.0/go.mod h1:+qH57V/K4oAcX9C7CvgJTwUX4lzfIUXQC/6XaRSOS1Y=
|
github.com/TwinProduction/gocache v1.2.0/go.mod h1:+qH57V/K4oAcX9C7CvgJTwUX4lzfIUXQC/6XaRSOS1Y=
|
||||||
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
|
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
|
||||||
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
|
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
|
||||||
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=
|
||||||
|
|||||||
@@ -10,10 +10,11 @@ func Match(pattern, s string) bool {
|
|||||||
if pattern == "*" {
|
if pattern == "*" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
// Backslashes break filepath.Match, so we'll remove all of them.
|
// Separators found in the string break filepath.Match, so we'll remove all of them.
|
||||||
// This has a pretty significant impact on performance when there
|
// This has a pretty significant impact on performance when there are separators in
|
||||||
// are backslashes, but at least it doesn't break filepath.Match.
|
// the strings, but at least it doesn't break filepath.Match.
|
||||||
s = strings.ReplaceAll(s, "\\", "")
|
s = strings.ReplaceAll(s, string(filepath.Separator), "")
|
||||||
|
pattern = strings.ReplaceAll(pattern, string(filepath.Separator), "")
|
||||||
matched, _ := filepath.Match(pattern, s)
|
matched, _ := filepath.Match(pattern, s)
|
||||||
return matched
|
return matched
|
||||||
}
|
}
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
/*!
|
|
||||||
* Bootstrap v4.3.1 (https://getbootstrap.com/)
|
|
||||||
* Copyright 2011-2019 The Bootstrap Authors
|
|
||||||
* Copyright 2011-2019 Twitter, Inc.
|
|
||||||
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
|
|
||||||
*/:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-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";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-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";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,Line truncated
|
|
||||||
@@ -1,414 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<title>Health Dashboard</title>
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<link rel="stylesheet" href="./bootstrap.min.css" />
|
|
||||||
<style>
|
|
||||||
html, body {
|
|
||||||
background-color: #f7f9fb;
|
|
||||||
}
|
|
||||||
html {
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
#results div.container:first-child {
|
|
||||||
border-top-left-radius: 3px;
|
|
||||||
border-top-right-radius: 3px;
|
|
||||||
}
|
|
||||||
#results div.container:last-child {
|
|
||||||
border-bottom-left-radius: 3px;
|
|
||||||
border-bottom-right-radius: 3px;
|
|
||||||
border-bottom-width: 1px;
|
|
||||||
border-color: #dee2e6;
|
|
||||||
border-style: solid;
|
|
||||||
}
|
|
||||||
.status {
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 500ms ease-in-out;
|
|
||||||
overflow-x: hidden;
|
|
||||||
padding: .25em 0;
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
.title {
|
|
||||||
font-size: 2.5rem;
|
|
||||||
}
|
|
||||||
.status:hover {
|
|
||||||
opacity: 0.7;
|
|
||||||
transition: opacity 100ms ease-in-out;
|
|
||||||
color: black;
|
|
||||||
}
|
|
||||||
.status-over-time {
|
|
||||||
overflow: auto;
|
|
||||||
}
|
|
||||||
.status-over-time>span:not(:last-child) {
|
|
||||||
margin-left: 2px;
|
|
||||||
}
|
|
||||||
.status-time-ago {
|
|
||||||
color: #6a737d;
|
|
||||||
opacity: 0.5;
|
|
||||||
margin-top: 5px;
|
|
||||||
}
|
|
||||||
.status-min-max-ms {
|
|
||||||
overflow-x: hidden;
|
|
||||||
}
|
|
||||||
#tooltip {
|
|
||||||
position: fixed;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
background-color: white;
|
|
||||||
border: 1px solid lightgray;
|
|
||||||
border-radius: 4px;
|
|
||||||
padding: 6px;
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
#tooltip code {
|
|
||||||
color: #212529;
|
|
||||||
line-height: 1;
|
|
||||||
}
|
|
||||||
#tooltip .tooltip-title {
|
|
||||||
font-weight: bold;
|
|
||||||
margin-bottom: 0;
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
#tooltip .tooltip-title {
|
|
||||||
margin-top: 8px;
|
|
||||||
}
|
|
||||||
#tooltip>.tooltip-title:first-child {
|
|
||||||
margin-top: 0;
|
|
||||||
}
|
|
||||||
#social {
|
|
||||||
position: fixed;
|
|
||||||
right: 5px;
|
|
||||||
bottom: 5px;
|
|
||||||
padding: 5px;
|
|
||||||
margin: 0;
|
|
||||||
z-index: 100;
|
|
||||||
}
|
|
||||||
#social img {
|
|
||||||
opacity: 0.3;
|
|
||||||
}
|
|
||||||
#social img:hover {
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
#settings {
|
|
||||||
position: fixed;
|
|
||||||
left: 5px;
|
|
||||||
bottom: 5px;
|
|
||||||
padding: 5px;
|
|
||||||
}
|
|
||||||
#settings select:focus {
|
|
||||||
box-shadow: none;
|
|
||||||
}
|
|
||||||
.service-group {
|
|
||||||
cursor: pointer;
|
|
||||||
user-select: none;
|
|
||||||
}
|
|
||||||
.service-group h5:hover {
|
|
||||||
color: #1b1e21 !important;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="container my-3 rounded p-3 border shadow">
|
|
||||||
<div class="mb-2">
|
|
||||||
<div class="row">
|
|
||||||
<div class="col-8 text-left my-auto">
|
|
||||||
<div class="title display-4">Health Status</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-4 text-right">
|
|
||||||
<img src="logo.png" alt="Gatus" style="position: relative; min-width: 50px; max-width: 200px; width: 20%;"/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div id="results"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="tooltip" style="display: none">
|
|
||||||
<div class="tooltip-title">Timestamp:</div>
|
|
||||||
<code id="tooltip-timestamp">...</code>
|
|
||||||
<div class="tooltip-title">Response time:</div>
|
|
||||||
<code id="tooltip-response-time">...</code>
|
|
||||||
<div class="tooltip-title">Conditions:</div>
|
|
||||||
<code id="tooltip-conditions">...</code>
|
|
||||||
<div id="tooltip-errors-container">
|
|
||||||
<div class="tooltip-title">Errors:</div>
|
|
||||||
<code id="tooltip-errors">...</code>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script src="./jquery.min.js"></script>
|
|
||||||
|
|
||||||
<div id="social">
|
|
||||||
<a href="https://github.com/TwinProduction/gatus" target="_blank" title="Gatus on GitHub">
|
|
||||||
<img src="./github.png" alt="GitHub" width="32" height="auto" />
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="settings">
|
|
||||||
<div class="input-group input-group-sm">
|
|
||||||
<div class="input-group-prepend">
|
|
||||||
<div class="input-group-text">↻</div>
|
|
||||||
</div>
|
|
||||||
<select class="form-control form-control-sm" id="refresh-rate">
|
|
||||||
<option value="10">10s</option>
|
|
||||||
<option value="30" selected>30s</option>
|
|
||||||
<option value="60">1m</option>
|
|
||||||
<option value="120">2m</option>
|
|
||||||
<option value="300">5m</option>
|
|
||||||
<option value="600">10m</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
let serviceStatuses = {};
|
|
||||||
let timerHandler = 0;
|
|
||||||
let refreshIntervalHandler = 0;
|
|
||||||
let userClickedStatus = false;
|
|
||||||
|
|
||||||
// TODO: make this variable configurable and persist the choice in localStorage
|
|
||||||
let showStatusOnHover = true;
|
|
||||||
|
|
||||||
function showTooltip(serviceName, index, element) {
|
|
||||||
//userClickedStatus = false;
|
|
||||||
clearTimeout(timerHandler);
|
|
||||||
let serviceResult = serviceStatuses[serviceName].results[index];
|
|
||||||
$("#tooltip-timestamp").text(prettifyTimestamp(serviceResult.timestamp));
|
|
||||||
$("#tooltip-response-time").text(parseInt(serviceResult.duration/1000000) + "ms");
|
|
||||||
// Populate the condition section
|
|
||||||
let conditions = "";
|
|
||||||
for (let i in serviceResult['condition-results']) {
|
|
||||||
let conditionResult = serviceResult['condition-results'][i];
|
|
||||||
conditions += (conditionResult.success ? "✓" : "X") + " ~ " + htmlEntities(conditionResult.condition) + "<br />";
|
|
||||||
}
|
|
||||||
$("#tooltip-conditions").html(conditions);
|
|
||||||
// Populate the error section only if there are errors
|
|
||||||
if (serviceResult.errors && serviceResult.errors.length > 0) {
|
|
||||||
let errors = "";
|
|
||||||
for (let i in serviceResult.errors) {
|
|
||||||
errors += "- " + htmlEntities(serviceResult.errors[i]) + "<br />";
|
|
||||||
}
|
|
||||||
$("#tooltip-errors").html(errors);
|
|
||||||
$("#tooltip-errors-container").show();
|
|
||||||
} else {
|
|
||||||
$("#tooltip-errors-container").hide();
|
|
||||||
}
|
|
||||||
// Position tooltip
|
|
||||||
$("#tooltip").css({top: "0px", left: "0px"}).show();
|
|
||||||
let targetTopPosition = element.getBoundingClientRect().y + 30;
|
|
||||||
let targetLeftPosition = element.getBoundingClientRect().x;
|
|
||||||
// Make adjustments if necessary
|
|
||||||
let tooltipBoundingClientRect = document.querySelector('#tooltip').getBoundingClientRect();
|
|
||||||
if (targetLeftPosition + window.scrollX + tooltipBoundingClientRect.width + 50 > document.body.getBoundingClientRect().width) {
|
|
||||||
targetLeftPosition = element.getBoundingClientRect().x - tooltipBoundingClientRect.width + element.getBoundingClientRect().width;
|
|
||||||
if (targetLeftPosition < 0) {
|
|
||||||
targetLeftPosition += -targetLeftPosition;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (targetTopPosition + window.scrollY + tooltipBoundingClientRect.height + 50 > document.body.getBoundingClientRect().height && targetTopPosition >= 0) {
|
|
||||||
targetTopPosition = element.getBoundingClientRect().y - (tooltipBoundingClientRect.height + 10);
|
|
||||||
if (targetTopPosition < 0) {
|
|
||||||
targetTopPosition = element.getBoundingClientRect().y + 30;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$("#tooltip").css({top: targetTopPosition + "px", left: targetLeftPosition + "px"});
|
|
||||||
}
|
|
||||||
|
|
||||||
function fadeTooltip() {
|
|
||||||
if (!userClickedStatus) {
|
|
||||||
timerHandler = setTimeout(function () {
|
|
||||||
$("#tooltip").hide();
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleTooltip(serviceName, index, element) {
|
|
||||||
console.log("userClickedStatus="+userClickedStatus);
|
|
||||||
if (!userClickedStatus) {
|
|
||||||
showTooltip(serviceName, index, element);
|
|
||||||
userClickedStatus = true;
|
|
||||||
} else {
|
|
||||||
$("#tooltip").hide();
|
|
||||||
userClickedStatus = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function createStatusBadge(serviceStatusIndex, index, success) {
|
|
||||||
if (success) {
|
|
||||||
if (showStatusOnHover) {
|
|
||||||
return "<span class='status badge badge-success' style='width: 5%' onmouseenter='showTooltip(\"" + serviceStatusIndex + "\", " + index + ", this)' onmouseleave='fadeTooltip()' onclick='userClickedStatus = !userClickedStatus;'>✓</span>";
|
|
||||||
} else {
|
|
||||||
return "<span class='status badge badge-success' style='width: 5%' onclick='toggleTooltip(\"" + serviceStatusIndex + "\", " + index + ", this)'>✓</span>";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (showStatusOnHover) {
|
|
||||||
return "<span class='status badge badge-danger' style='width: 5%' onmouseenter='showTooltip(\"" + serviceStatusIndex + "\", " + index + ", this)' onmouseleave='fadeTooltip()' onclick='userClickedStatus = !userClickedStatus;'>X</span>";
|
|
||||||
} else {
|
|
||||||
return "<span class='status badge badge-danger' style='width: 5%' onclick='toggleTooltip(\"" + serviceStatusIndex + "\", " + index + ", this)'>X</span>";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function refreshStatuses() {
|
|
||||||
$.getJSON("./api/v1/statuses", function (data) {
|
|
||||||
// Update the table only if there's a change
|
|
||||||
if (JSON.stringify(serviceStatuses) !== JSON.stringify(data)) {
|
|
||||||
serviceStatuses = data;
|
|
||||||
buildTable();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildTable() {
|
|
||||||
let outputByGroup = {};
|
|
||||||
for (let serviceStatusIndex in serviceStatuses) {
|
|
||||||
let serviceStatusOverTime = "";
|
|
||||||
let serviceStatus = serviceStatuses[serviceStatusIndex];
|
|
||||||
let hostname = serviceStatus.results[serviceStatus.results.length-1].hostname;
|
|
||||||
let minResponseTime = null;
|
|
||||||
let maxResponseTime = null;
|
|
||||||
let newestTimestamp = null;
|
|
||||||
let oldestTimestamp = null;
|
|
||||||
for (let resultIndex in serviceStatus.results) {
|
|
||||||
let serviceResult = serviceStatus.results[resultIndex];
|
|
||||||
serviceStatusOverTime = createStatusBadge(serviceStatusIndex, resultIndex, serviceResult.success) + serviceStatusOverTime;
|
|
||||||
const responseTime = parseInt(serviceResult.duration/1000000);
|
|
||||||
if (minResponseTime == null || minResponseTime > responseTime) {
|
|
||||||
minResponseTime = responseTime;
|
|
||||||
}
|
|
||||||
if (maxResponseTime == null || maxResponseTime < responseTime) {
|
|
||||||
maxResponseTime = responseTime;
|
|
||||||
}
|
|
||||||
const timestamp = new Date(serviceResult.timestamp);
|
|
||||||
if (newestTimestamp == null || newestTimestamp < timestamp) {
|
|
||||||
newestTimestamp = timestamp;
|
|
||||||
}
|
|
||||||
if (oldestTimestamp == null || oldestTimestamp > timestamp) {
|
|
||||||
oldestTimestamp = timestamp;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let output = ""
|
|
||||||
+ "<div class='container py-3 border-left border-right border-top border-black rounded-0'>"
|
|
||||||
+ " <div class='row mb-2'>"
|
|
||||||
+ " <div class='col-md-10'>"
|
|
||||||
+ " <span class='font-weight-bold'>" + serviceStatus.name + "</span> <span class='text-secondary font-weight-lighter'>- " + hostname + "</span>"
|
|
||||||
+ " </div>"
|
|
||||||
+ " <div class='col-md-2 text-right'>"
|
|
||||||
+ " <span class='font-weight-lighter status-min-max-ms'>" + (minResponseTime === maxResponseTime ? minResponseTime : (minResponseTime + "-" + maxResponseTime)) + "ms</span>"
|
|
||||||
+ " </div>"
|
|
||||||
+ " </div>"
|
|
||||||
+ " <div class='row'>"
|
|
||||||
+ " <div class='col-12 d-flex flex-row-reverse status-over-time'>"
|
|
||||||
+ " " + serviceStatusOverTime
|
|
||||||
+ " </div>"
|
|
||||||
+ " </div>"
|
|
||||||
+ " <div class='row status-time-ago'>"
|
|
||||||
+ " <div class='col-6'>"
|
|
||||||
+ " " + generatePrettyTimeAgo(oldestTimestamp)
|
|
||||||
+ " </div>"
|
|
||||||
+ " <div class='col-6 text-right'>"
|
|
||||||
+ " " + generatePrettyTimeAgo(newestTimestamp)
|
|
||||||
+ " </div>"
|
|
||||||
+ " </div>"
|
|
||||||
+ "</div>";
|
|
||||||
// create an empty entry if this group is new
|
|
||||||
if (!outputByGroup[serviceStatus.group]) {
|
|
||||||
outputByGroup[serviceStatus.group] = "";
|
|
||||||
}
|
|
||||||
outputByGroup[serviceStatus.group] += output;
|
|
||||||
}
|
|
||||||
let output = "";
|
|
||||||
for (let group in outputByGroup) {
|
|
||||||
// Services that don't have a group should be skipped and left for last
|
|
||||||
if (group === 'undefined') {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
let key = group.replace(/[^a-zA-Z0-9]/g, '');
|
|
||||||
let existingGroupContentSelector = $("#service-group-" + key + "-content");
|
|
||||||
let isCurrentlyHidden = existingGroupContentSelector.length && existingGroupContentSelector[0].style.display === 'none';
|
|
||||||
let groupStatus = "<span class='text-success'>✓</span>";
|
|
||||||
if (outputByGroup[group].includes("badge badge-danger")) {
|
|
||||||
groupStatus = "<span class='text-warning'>~</span>";
|
|
||||||
}
|
|
||||||
output += ""
|
|
||||||
+ "<div class='mt-" + (output.length ? '4' : '3') + "'>"
|
|
||||||
+ " <div class='container pt-2 border-left border-right border-top border-black border-bottom service-group' id='service-group-" + key + "' data-group='" + key + "' onclick='toggleGroup(this)'>"
|
|
||||||
+ " <h5 class='text-secondary text-monospace pb-0'>"
|
|
||||||
+ " " + groupStatus + " " + group
|
|
||||||
+ " <span class='float-right service-group-arrow' id='service-group-" + key + "-arrow'>" + (isCurrentlyHidden ? "▼" : "▲") + "</span>"
|
|
||||||
+ " </h5>"
|
|
||||||
+ " </div>"
|
|
||||||
+ " <div class='service-group-content' id='service-group-" + key + "-content' style='" + (isCurrentlyHidden ? "display: none;" : "") + "'>"
|
|
||||||
+ " " + outputByGroup[group]
|
|
||||||
+ " </div>"
|
|
||||||
+ "</div>";
|
|
||||||
}
|
|
||||||
// Add all services that don't have a group at the end
|
|
||||||
if (outputByGroup['undefined']) {
|
|
||||||
output += ""
|
|
||||||
+ "<div class='mt-" + (output.length ? '4' : '3') + "'>"
|
|
||||||
+ " " + outputByGroup['undefined']
|
|
||||||
+ "</div>"
|
|
||||||
}
|
|
||||||
$("#results").html(output);
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleGroup(element) {
|
|
||||||
let selector = $("#service-group-" + element.dataset.group + "-content");
|
|
||||||
selector.toggle("fast", function() {
|
|
||||||
if (selector.length && selector[0].style.display === 'none') {
|
|
||||||
$("#service-group-" + element.dataset.group + "-arrow").html("▼");
|
|
||||||
} else {
|
|
||||||
$("#service-group-" + element.dataset.group + "-arrow").html("▲");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function prettifyTimestamp(timestamp) {
|
|
||||||
let date = new Date(timestamp);
|
|
||||||
let YYYY = date.getFullYear();
|
|
||||||
let MM = ((date.getMonth()+1)<10?"0":"")+""+(date.getMonth()+1);
|
|
||||||
let DD = ((date.getDate())<10?"0":"")+""+(date.getDate());
|
|
||||||
let hh = ((date.getHours())<10?"0":"")+""+(date.getHours());
|
|
||||||
let mm = ((date.getMinutes())<10?"0":"")+""+(date.getMinutes());
|
|
||||||
let ss = ((date.getSeconds())<10?"0":"")+""+(date.getSeconds());
|
|
||||||
return YYYY + "-" + MM + "-" + DD + " " + hh + ":" + mm + ":" + ss;
|
|
||||||
}
|
|
||||||
|
|
||||||
function generatePrettyTimeAgo(t) {
|
|
||||||
let differenceInMs = new Date().getTime() - new Date(t).getTime();
|
|
||||||
if (differenceInMs > 3600000) {
|
|
||||||
let hours = (differenceInMs/3600000).toFixed(0);
|
|
||||||
return hours + " hour" + (hours !== "1" ? "s" : "") + " ago";
|
|
||||||
}
|
|
||||||
if (differenceInMs > 60000) {
|
|
||||||
let minutes = (differenceInMs/60000).toFixed(0);
|
|
||||||
return minutes + " minute" + (minutes !== "1" ? "s" : "") + " ago";
|
|
||||||
}
|
|
||||||
return (differenceInMs/1000).toFixed(0) + " seconds ago";
|
|
||||||
}
|
|
||||||
|
|
||||||
function htmlEntities(s) {
|
|
||||||
return String(s)
|
|
||||||
.replace(/&/g, '&')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, ''');
|
|
||||||
}
|
|
||||||
|
|
||||||
function setRefreshInterval(seconds) {
|
|
||||||
refreshStatuses();
|
|
||||||
refreshIntervalHandler = setInterval(function() {
|
|
||||||
refreshStatuses();
|
|
||||||
}, seconds * 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
$("#refresh-rate").change(function() {
|
|
||||||
clearInterval(refreshIntervalHandler);
|
|
||||||
setRefreshInterval($(this).val());
|
|
||||||
});
|
|
||||||
setRefreshInterval(30);
|
|
||||||
$("#refresh-rate").val(30);
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */
|
|
||||||
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:s,sort:n.sort,splice:n.splice},w.extend=w.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||g(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)n=a[t],a!==(r=e[t])&&(l&&r&&(w.isPlainObject(r)||(i=Array.isArray(r)))?(i?(i=!1,o=n&&Array.isArray(n)?n:[]):o=n&&w.isPlainObject(n)?n:{},a[t]=w.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},w.extend({expando:"jQuery"+("3.3.1"+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==c.call(e))&&(!(t=i(e))||"function"==typeof(n=f.call(t,"constructor")&&t.constructor)&&p.call(n)===d)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e){m(e)},each:function(e,t){var n,r=0;if(C(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(C(Object(e))?w.merge(n,"string"==typeof e?[e]:e):s.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:u.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;o<a;o++)(r=!t(e[o],o))!==s&&i.push(e[o]);return i},map:function(e,t,n){var r,i,o=0,s=[];if(C(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&s.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&s.push(i);return a.apply([],s)},guid:1,support:h}),"function"==typeof Symbol&&(w.fn[Symbol.iterator]=n[Symbol.iterator]),w.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function C(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!g(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",I="\\["+M+"*("+R+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+R+"))|)"+M+"*\\]",W=":("+R+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+I+")*)|.*)\\)|)",$=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),F=new RegExp("^"+M+"*,"+M+"*"),_=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)Line truncated
|
|
||||||
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 83 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
// Config is the configuration for alerting providers
|
||||||
|
type Config struct {
|
||||||
|
// File is the path of the file to use when using file.Store
|
||||||
|
File string `yaml:"file"`
|
||||||
|
}
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
package storage
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/core"
|
|
||||||
)
|
|
||||||
|
|
||||||
// InMemoryStore implements an in-memory store
|
|
||||||
type InMemoryStore struct {
|
|
||||||
serviceStatuses map[string]*core.ServiceStatus
|
|
||||||
serviceResultsMutex sync.RWMutex
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewInMemoryStore returns an in-memory store. Note that the store acts as a singleton, so although new-ing
|
|
||||||
// up in-memory stores will give you a unique reference to a struct each time, all structs returned
|
|
||||||
// by this function will act on the same in-memory store.
|
|
||||||
func NewInMemoryStore() *InMemoryStore {
|
|
||||||
return &InMemoryStore{
|
|
||||||
serviceStatuses: make(map[string]*core.ServiceStatus),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAllAsJSON returns the JSON encoding of all monitored core.ServiceStatus
|
|
||||||
func (ims *InMemoryStore) GetAllAsJSON() ([]byte, error) {
|
|
||||||
ims.serviceResultsMutex.RLock()
|
|
||||||
serviceStatuses, err := json.Marshal(ims.serviceStatuses)
|
|
||||||
ims.serviceResultsMutex.RUnlock()
|
|
||||||
return serviceStatuses, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetServiceStatus returns the service status for a given service name in the given group
|
|
||||||
func (ims *InMemoryStore) GetServiceStatus(group, name string) *core.ServiceStatus {
|
|
||||||
key := fmt.Sprintf("%s_%s", group, name)
|
|
||||||
ims.serviceResultsMutex.RLock()
|
|
||||||
serviceStatus := ims.serviceStatuses[key]
|
|
||||||
ims.serviceResultsMutex.RUnlock()
|
|
||||||
return serviceStatus
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert inserts the observed result for the specified service into the in memory store
|
|
||||||
func (ims *InMemoryStore) Insert(service *core.Service, result *core.Result) {
|
|
||||||
key := fmt.Sprintf("%s_%s", service.Group, service.Name)
|
|
||||||
ims.serviceResultsMutex.Lock()
|
|
||||||
serviceStatus, exists := ims.serviceStatuses[key]
|
|
||||||
if !exists {
|
|
||||||
serviceStatus = core.NewServiceStatus(service)
|
|
||||||
ims.serviceStatuses[key] = serviceStatus
|
|
||||||
}
|
|
||||||
serviceStatus.AddResult(result)
|
|
||||||
ims.serviceResultsMutex.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clear will empty all the results from the in memory store
|
|
||||||
func (ims *InMemoryStore) Clear() {
|
|
||||||
ims.serviceResultsMutex.Lock()
|
|
||||||
ims.serviceStatuses = make(map[string]*core.ServiceStatus)
|
|
||||||
ims.serviceResultsMutex.Unlock()
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwinProduction/gatus/storage/store"
|
||||||
|
"github.com/TwinProduction/gatus/storage/store/memory"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
provider store.Store
|
||||||
|
|
||||||
|
// initialized keeps track of whether the storage provider was initialized
|
||||||
|
// Because store.Store is an interface, a nil check wouldn't be sufficient, so instead of doing reflection
|
||||||
|
// every single time Get is called, we'll just lazily keep track of its existence through this variable
|
||||||
|
initialized bool
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get retrieves the storage provider
|
||||||
|
func Get() store.Store {
|
||||||
|
if !initialized {
|
||||||
|
log.Println("[storage][Get] Provider requested before it was initialized, automatically initializing")
|
||||||
|
err := Initialize(nil)
|
||||||
|
if err != nil {
|
||||||
|
panic("failed to automatically initialize store: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return provider
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize instantiates the storage provider based on the Config provider
|
||||||
|
func Initialize(cfg *Config) error {
|
||||||
|
initialized = true
|
||||||
|
var err error
|
||||||
|
if cfg == nil || len(cfg.File) == 0 {
|
||||||
|
log.Println("[storage][Initialize] Creating storage provider")
|
||||||
|
provider, err = memory.NewStore("")
|
||||||
|
} else {
|
||||||
|
log.Printf("[storage][Initialize] Creating storage provider with file=%s", cfg.File)
|
||||||
|
provider, err = memory.NewStore(cfg.File)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
go provider.(*memory.Store).AutoSave(7 * time.Minute)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package memory
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/gob"
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwinProduction/gatus/core"
|
||||||
|
"github.com/TwinProduction/gatus/util"
|
||||||
|
"github.com/TwinProduction/gocache"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
gob.Register(&core.ServiceStatus{})
|
||||||
|
gob.Register(&core.Uptime{})
|
||||||
|
gob.Register(&core.Result{})
|
||||||
|
gob.Register(&core.Event{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store that leverages gocache
|
||||||
|
type Store struct {
|
||||||
|
file string
|
||||||
|
cache *gocache.Cache
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewStore creates a new store
|
||||||
|
func NewStore(file string) (*Store, error) {
|
||||||
|
store := &Store{
|
||||||
|
file: file,
|
||||||
|
cache: gocache.NewCache().WithMaxSize(gocache.NoMaxSize),
|
||||||
|
}
|
||||||
|
if len(file) > 0 {
|
||||||
|
_, err := store.cache.ReadFromFile(file)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return store, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAllAsJSON returns the JSON encoding of all monitored core.ServiceStatus
|
||||||
|
func (s *Store) GetAllAsJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(s.cache.GetAll())
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetServiceStatus returns the service status for a given service name in the given group
|
||||||
|
func (s *Store) GetServiceStatus(groupName, serviceName string) *core.ServiceStatus {
|
||||||
|
return s.GetServiceStatusByKey(util.ConvertGroupAndServiceToKey(groupName, serviceName))
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetServiceStatusByKey returns the service status for a given key
|
||||||
|
func (s *Store) GetServiceStatusByKey(key string) *core.ServiceStatus {
|
||||||
|
serviceStatus := s.cache.GetValue(key)
|
||||||
|
if serviceStatus == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return serviceStatus.(*core.ServiceStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert adds the observed result for the specified service into the store
|
||||||
|
func (s *Store) Insert(service *core.Service, result *core.Result) {
|
||||||
|
key := util.ConvertGroupAndServiceToKey(service.Group, service.Name)
|
||||||
|
serviceStatus, exists := s.cache.Get(key)
|
||||||
|
if !exists {
|
||||||
|
serviceStatus = core.NewServiceStatus(service)
|
||||||
|
}
|
||||||
|
serviceStatus.(*core.ServiceStatus).AddResult(result)
|
||||||
|
s.cache.Set(key, serviceStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteAllServiceStatusesNotInKeys removes all ServiceStatus that are not within the keys provided
|
||||||
|
func (s *Store) DeleteAllServiceStatusesNotInKeys(keys []string) int {
|
||||||
|
var keysToDelete []string
|
||||||
|
for _, existingKey := range s.cache.GetKeysByPattern("*", 0) {
|
||||||
|
shouldDelete := true
|
||||||
|
for _, key := range keys {
|
||||||
|
if existingKey == key {
|
||||||
|
shouldDelete = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if shouldDelete {
|
||||||
|
keysToDelete = append(keysToDelete, existingKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s.cache.DeleteAll(keysToDelete)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear deletes everything from the store
|
||||||
|
func (s *Store) Clear() {
|
||||||
|
s.cache.Clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save persists the cache to the store file
|
||||||
|
func (s *Store) Save() error {
|
||||||
|
return s.cache.SaveToFile(s.file)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AutoSave automatically calls the Save function at every interval
|
||||||
|
func (s *Store) AutoSave(interval time.Duration) {
|
||||||
|
for {
|
||||||
|
time.Sleep(interval)
|
||||||
|
log.Printf("[memory][AutoSave] Persisting data to file")
|
||||||
|
err := s.Save()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[memory][AutoSave] failed to save to file=%s: %s", s.file, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package storage
|
package memory
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/TwinProduction/gatus/core"
|
"github.com/TwinProduction/gatus/core"
|
||||||
|
"github.com/TwinProduction/gatus/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -82,17 +83,17 @@ var (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestInMemoryStore_Insert(t *testing.T) {
|
func TestStore_Insert(t *testing.T) {
|
||||||
store := NewInMemoryStore()
|
store, _ := NewStore("")
|
||||||
store.Insert(&testService, &testSuccessfulResult)
|
store.Insert(&testService, &testSuccessfulResult)
|
||||||
store.Insert(&testService, &testUnsuccessfulResult)
|
store.Insert(&testService, &testUnsuccessfulResult)
|
||||||
|
|
||||||
if len(store.serviceStatuses) != 1 {
|
if store.cache.Count() != 1 {
|
||||||
t.Fatalf("expected 1 ServiceStatus, got %d", len(store.serviceStatuses))
|
t.Fatalf("expected 1 ServiceStatus, got %d", store.cache.Count())
|
||||||
}
|
}
|
||||||
key := fmt.Sprintf("%s_%s", testService.Group, testService.Name)
|
key := fmt.Sprintf("%s_%s", testService.Group, testService.Name)
|
||||||
serviceStatus, exists := store.serviceStatuses[key]
|
serviceStatus := store.GetServiceStatusByKey(key)
|
||||||
if !exists {
|
if serviceStatus == nil {
|
||||||
t.Fatalf("Store should've had key '%s', but didn't", key)
|
t.Fatalf("Store should've had key '%s', but didn't", key)
|
||||||
}
|
}
|
||||||
if len(serviceStatus.Results) != 2 {
|
if len(serviceStatus.Results) != 2 {
|
||||||
@@ -139,8 +140,8 @@ func TestInMemoryStore_Insert(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInMemoryStore_GetServiceStatus(t *testing.T) {
|
func TestStore_GetServiceStatus(t *testing.T) {
|
||||||
store := NewInMemoryStore()
|
store, _ := NewStore("")
|
||||||
store.Insert(&testService, &testSuccessfulResult)
|
store.Insert(&testService, &testSuccessfulResult)
|
||||||
store.Insert(&testService, &testUnsuccessfulResult)
|
store.Insert(&testService, &testUnsuccessfulResult)
|
||||||
|
|
||||||
@@ -160,11 +161,10 @@ func TestInMemoryStore_GetServiceStatus(t *testing.T) {
|
|||||||
if serviceStatus.Uptime.LastSevenDays != 0.5 {
|
if serviceStatus.Uptime.LastSevenDays != 0.5 {
|
||||||
t.Errorf("serviceStatus.Uptime.LastSevenDays should've been 0.5")
|
t.Errorf("serviceStatus.Uptime.LastSevenDays should've been 0.5")
|
||||||
}
|
}
|
||||||
fmt.Println(serviceStatus.Results[0].Timestamp.Format(time.RFC3339))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInMemoryStore_GetServiceStatusForMissingStatusReturnsNil(t *testing.T) {
|
func TestStore_GetServiceStatusForMissingStatusReturnsNil(t *testing.T) {
|
||||||
store := NewInMemoryStore()
|
store, _ := NewStore("")
|
||||||
store.Insert(&testService, &testSuccessfulResult)
|
store.Insert(&testService, &testSuccessfulResult)
|
||||||
|
|
||||||
serviceStatus := store.GetServiceStatus("nonexistantgroup", "nonexistantname")
|
serviceStatus := store.GetServiceStatus("nonexistantgroup", "nonexistantname")
|
||||||
@@ -181,8 +181,31 @@ func TestInMemoryStore_GetServiceStatusForMissingStatusReturnsNil(t *testing.T)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInMemoryStore_GetAllAsJSON(t *testing.T) {
|
func TestStore_GetServiceStatusByKey(t *testing.T) {
|
||||||
store := NewInMemoryStore()
|
store, _ := NewStore("")
|
||||||
|
store.Insert(&testService, &testSuccessfulResult)
|
||||||
|
store.Insert(&testService, &testUnsuccessfulResult)
|
||||||
|
|
||||||
|
serviceStatus := store.GetServiceStatusByKey(util.ConvertGroupAndServiceToKey(testService.Group, testService.Name))
|
||||||
|
if serviceStatus == nil {
|
||||||
|
t.Fatalf("serviceStatus shouldn't have been nil")
|
||||||
|
}
|
||||||
|
if serviceStatus.Uptime == nil {
|
||||||
|
t.Fatalf("serviceStatus.Uptime shouldn't have been nil")
|
||||||
|
}
|
||||||
|
if serviceStatus.Uptime.LastHour != 0.5 {
|
||||||
|
t.Errorf("serviceStatus.Uptime.LastHour should've been 0.5")
|
||||||
|
}
|
||||||
|
if serviceStatus.Uptime.LastTwentyFourHours != 0.5 {
|
||||||
|
t.Errorf("serviceStatus.Uptime.LastTwentyFourHours should've been 0.5")
|
||||||
|
}
|
||||||
|
if serviceStatus.Uptime.LastSevenDays != 0.5 {
|
||||||
|
t.Errorf("serviceStatus.Uptime.LastSevenDays should've been 0.5")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStore_GetAllAsJSON(t *testing.T) {
|
||||||
|
store, _ := NewStore("")
|
||||||
firstResult := &testSuccessfulResult
|
firstResult := &testSuccessfulResult
|
||||||
secondResult := &testUnsuccessfulResult
|
secondResult := &testUnsuccessfulResult
|
||||||
store.Insert(&testService, firstResult)
|
store.Insert(&testService, firstResult)
|
||||||
@@ -194,8 +217,36 @@ func TestInMemoryStore_GetAllAsJSON(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("shouldn't have returned an error, got", err.Error())
|
t.Fatal("shouldn't have returned an error, got", err.Error())
|
||||||
}
|
}
|
||||||
expectedOutput := `{"group_name":{"name":"name","group":"group","results":[{"status":200,"hostname":"example.org","duration":150000000,"errors":null,"condition-results":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"},{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"condition-results":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}],"uptime":{"7d":0.5,"24h":0.5,"1h":0.5}}}`
|
expectedOutput := `{"group_name":{"name":"name","group":"group","key":"group_name","results":[{"status":200,"hostname":"example.org","duration":150000000,"errors":null,"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":true},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":true}],"success":true,"timestamp":"0001-01-01T00:00:00Z"},{"status":200,"hostname":"example.org","duration":750000000,"errors":["error-1","error-2"],"conditionResults":[{"condition":"[STATUS] == 200","success":true},{"condition":"[RESPONSE_TIME] \u003c 500","success":false},{"condition":"[CERTIFICATE_EXPIRATION] \u003c 72h","success":false}],"success":false,"timestamp":"0001-01-01T00:00:00Z"}]}}`
|
||||||
if string(output) != expectedOutput {
|
if string(output) != expectedOutput {
|
||||||
t.Errorf("expected:\n %s\n\ngot:\n %s", expectedOutput, string(output))
|
t.Errorf("expected:\n %s\n\ngot:\n %s", expectedOutput, string(output))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStore_DeleteAllServiceStatusesNotInKeys(t *testing.T) {
|
||||||
|
store, _ := NewStore("")
|
||||||
|
firstService := core.Service{Name: "service-1", Group: "group"}
|
||||||
|
secondService := core.Service{Name: "service-2", Group: "group"}
|
||||||
|
result := &testSuccessfulResult
|
||||||
|
store.Insert(&firstService, result)
|
||||||
|
store.Insert(&secondService, result)
|
||||||
|
if store.cache.Count() != 2 {
|
||||||
|
t.Errorf("expected cache to have 2 keys, got %d", store.cache.Count())
|
||||||
|
}
|
||||||
|
if store.GetServiceStatusByKey(util.ConvertGroupAndServiceToKey(firstService.Group, firstService.Name)) == nil {
|
||||||
|
t.Fatal("firstService should exist")
|
||||||
|
}
|
||||||
|
if store.GetServiceStatusByKey(util.ConvertGroupAndServiceToKey(secondService.Group, secondService.Name)) == nil {
|
||||||
|
t.Fatal("secondService should exist")
|
||||||
|
}
|
||||||
|
store.DeleteAllServiceStatusesNotInKeys([]string{util.ConvertGroupAndServiceToKey(firstService.Group, firstService.Name)})
|
||||||
|
if store.cache.Count() != 1 {
|
||||||
|
t.Fatalf("expected cache to have 1 keys, got %d", store.cache.Count())
|
||||||
|
}
|
||||||
|
if store.GetServiceStatusByKey(util.ConvertGroupAndServiceToKey(firstService.Group, firstService.Name)) == nil {
|
||||||
|
t.Error("secondService should've been deleted")
|
||||||
|
}
|
||||||
|
if store.GetServiceStatusByKey(util.ConvertGroupAndServiceToKey(secondService.Group, secondService.Name)) != nil {
|
||||||
|
t.Error("firstService should still exist")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/TwinProduction/gatus/core"
|
||||||
|
"github.com/TwinProduction/gatus/storage/store/memory"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Store is the interface that each stores should implement
|
||||||
|
type Store interface {
|
||||||
|
// GetAllAsJSON returns the JSON encoding of all monitored core.ServiceStatus
|
||||||
|
GetAllAsJSON() ([]byte, error)
|
||||||
|
|
||||||
|
// GetServiceStatus returns the service status for a given service name in the given group
|
||||||
|
GetServiceStatus(groupName, serviceName string) *core.ServiceStatus
|
||||||
|
|
||||||
|
// GetServiceStatusByKey returns the service status for a given key
|
||||||
|
GetServiceStatusByKey(key string) *core.ServiceStatus
|
||||||
|
|
||||||
|
// Insert adds the observed result for the specified service into the store
|
||||||
|
Insert(service *core.Service, result *core.Result)
|
||||||
|
|
||||||
|
// DeleteAllServiceStatusesNotInKeys removes all ServiceStatus that are not within the keys provided
|
||||||
|
//
|
||||||
|
// Used to delete services that have been persisted but are no longer part of the configured services
|
||||||
|
DeleteAllServiceStatusesNotInKeys(keys []string) int
|
||||||
|
|
||||||
|
// Clear deletes everything from the store
|
||||||
|
Clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Validate interface implementation on compile
|
||||||
|
_ Store = (*memory.Store)(nil)
|
||||||
|
)
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/TwinProduction/gatus/core"
|
||||||
|
"github.com/TwinProduction/gatus/storage/store/memory"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
firstCondition = core.Condition("[STATUS] == 200")
|
||||||
|
secondCondition = core.Condition("[RESPONSE_TIME] < 500")
|
||||||
|
thirdCondition = core.Condition("[CERTIFICATE_EXPIRATION] < 72h")
|
||||||
|
|
||||||
|
timestamp = time.Now()
|
||||||
|
|
||||||
|
testService = core.Service{
|
||||||
|
Name: "name",
|
||||||
|
Group: "group",
|
||||||
|
URL: "https://example.org/what/ever",
|
||||||
|
Method: "GET",
|
||||||
|
Body: "body",
|
||||||
|
Interval: 30 * time.Second,
|
||||||
|
Conditions: []*core.Condition{&firstCondition, &secondCondition, &thirdCondition},
|
||||||
|
Alerts: nil,
|
||||||
|
Insecure: false,
|
||||||
|
NumberOfFailuresInARow: 0,
|
||||||
|
NumberOfSuccessesInARow: 0,
|
||||||
|
}
|
||||||
|
testSuccessfulResult = core.Result{
|
||||||
|
Hostname: "example.org",
|
||||||
|
IP: "127.0.0.1",
|
||||||
|
HTTPStatus: 200,
|
||||||
|
Body: []byte("body"),
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
testUnsuccessfulResult = core.Result{
|
||||||
|
Hostname: "example.org",
|
||||||
|
IP: "127.0.0.1",
|
||||||
|
HTTPStatus: 200,
|
||||||
|
Body: []byte("body"),
|
||||||
|
Errors: []string{"error-1", "error-2"},
|
||||||
|
Connected: true,
|
||||||
|
Success: false,
|
||||||
|
Timestamp: timestamp,
|
||||||
|
Duration: 750 * time.Millisecond,
|
||||||
|
CertificateExpiration: 10 * time.Hour,
|
||||||
|
ConditionResults: []*core.ConditionResult{
|
||||||
|
{
|
||||||
|
Condition: "[STATUS] == 200",
|
||||||
|
Success: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Condition: "[RESPONSE_TIME] < 500",
|
||||||
|
Success: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Condition: "[CERTIFICATE_EXPIRATION] < 72h",
|
||||||
|
Success: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func BenchmarkStore_GetAllAsJSON(b *testing.B) {
|
||||||
|
memoryStore, err := memory.NewStore("")
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal("failed to create store:", err.Error())
|
||||||
|
}
|
||||||
|
type Scenario struct {
|
||||||
|
Name string
|
||||||
|
Store Store
|
||||||
|
}
|
||||||
|
scenarios := []Scenario{
|
||||||
|
{
|
||||||
|
Name: "memory",
|
||||||
|
Store: memoryStore,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
scenario.Store.Insert(&testService, &testSuccessfulResult)
|
||||||
|
scenario.Store.Insert(&testService, &testUnsuccessfulResult)
|
||||||
|
b.Run(scenario.Name, func(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
scenario.Store.GetAllAsJSON()
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkStore_Insert(b *testing.B) {
|
||||||
|
memoryStore, err := memory.NewStore("")
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal("failed to create store:", err.Error())
|
||||||
|
}
|
||||||
|
type Scenario struct {
|
||||||
|
Name string
|
||||||
|
Store Store
|
||||||
|
}
|
||||||
|
scenarios := []Scenario{
|
||||||
|
{
|
||||||
|
Name: "memory",
|
||||||
|
Store: memoryStore,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
b.Run(scenario.Name, func(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
scenario.Store.Insert(&testService, &testSuccessfulResult)
|
||||||
|
scenario.Store.Insert(&testService, &testUnsuccessfulResult)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// ConvertGroupAndServiceToKey converts a group and a service to a key
|
||||||
|
func ConvertGroupAndServiceToKey(group, service string) string {
|
||||||
|
return sanitize(group) + "_" + sanitize(service)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sanitize(s string) string {
|
||||||
|
s = strings.TrimSpace(strings.ToLower(s))
|
||||||
|
s = strings.ReplaceAll(s, "/", "-")
|
||||||
|
s = strings.ReplaceAll(s, "_", "-")
|
||||||
|
s = strings.ReplaceAll(s, ".", "-")
|
||||||
|
s = strings.ReplaceAll(s, ",", "-")
|
||||||
|
s = strings.ReplaceAll(s, " ", "-")
|
||||||
|
return s
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestConvertGroupAndServiceToKey(t *testing.T) {
|
||||||
|
type Scenario struct {
|
||||||
|
GroupName string
|
||||||
|
ServiceName string
|
||||||
|
ExpectedOutput string
|
||||||
|
}
|
||||||
|
scenarios := []Scenario{
|
||||||
|
{
|
||||||
|
GroupName: "Core",
|
||||||
|
ServiceName: "Front End",
|
||||||
|
ExpectedOutput: "core_front-end",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
GroupName: "Load balancers",
|
||||||
|
ServiceName: "us-west-2",
|
||||||
|
ExpectedOutput: "load-balancers_us-west-2",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
GroupName: "a/b test",
|
||||||
|
ServiceName: "a",
|
||||||
|
ExpectedOutput: "a-b-test_a",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, scenario := range scenarios {
|
||||||
|
t.Run(scenario.ExpectedOutput, func(t *testing.T) {
|
||||||
|
output := ConvertGroupAndServiceToKey(scenario.GroupName, scenario.ServiceName)
|
||||||
|
if output != scenario.ExpectedOutput {
|
||||||
|
t.Errorf("Expected '%s', got '%s'", scenario.ExpectedOutput, output)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -306,9 +306,9 @@ If you do not start the janitor, there will be no passive deletion of expired ke
|
|||||||
For the sake of convenience, a ready-to-go cache server is available
|
For the sake of convenience, a ready-to-go cache server is available
|
||||||
through the `gocacheserver` package.
|
through the `gocacheserver` package.
|
||||||
|
|
||||||
The reason why the server is in a different package is because `gocache` does not use
|
The reason why the server is in a different package is because `gocache` limit its external dependencies to the strict
|
||||||
any external dependencies, but rather than re-inventing the wheel, the server
|
minimum (e.g. boltdb for persistence), however, rather than re-inventing the wheel, the server implementation uses
|
||||||
implementation uses redcon, which is a Redis server framework for Go.
|
redcon, which is a very good Redis server framework for Go.
|
||||||
|
|
||||||
That way, those who desire to use gocache without the server will not add any extra dependencies
|
That way, those who desire to use gocache without the server will not add any extra dependencies
|
||||||
as long as they don't import the `gocacheserver` package.
|
as long as they don't import the `gocacheserver` package.
|
||||||
@@ -323,7 +323,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
cache := gocache.NewCache().WithEvictionPolicy(gocache.LeastRecentlyUsed).WithMaxSize(100000)
|
cache := gocache.NewCache().WithEvictionPolicy(gocache.LeastRecentlyUsed).WithMaxSize(100000)
|
||||||
server := gocacheserver.NewServer(cache)
|
server := gocacheserver.NewServer(cache).WithPort(6379)
|
||||||
server.Start()
|
server.Start()
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -382,43 +382,67 @@ but if you're looking into using a library like gocache, odds are, you want more
|
|||||||
| mem | 32G DDR4 |
|
| mem | 32G DDR4 |
|
||||||
|
|
||||||
```
|
```
|
||||||
BenchmarkMap_Get-8 95936680 26.3 ns/op
|
// Normal map
|
||||||
BenchmarkMap_SetSmallValue-8 7738132 424 ns/op
|
BenchmarkMap_Get
|
||||||
BenchmarkMap_SetMediumValue-8 7766346 424 ns/op
|
BenchmarkMap_Get-8 46087372 26.7 ns/op
|
||||||
BenchmarkMap_SetLargeValue-8 7947063 435 ns/op
|
BenchmarkMap_Set
|
||||||
BenchmarkCache_Get-8 54549049 45.7 ns/op
|
BenchmarkMap_Set/small_value-8 3841911 389 ns/op
|
||||||
BenchmarkCache_SetSmallValue-8 35225013 69.2 ns/op
|
BenchmarkMap_Set/medium_value-8 3887074 391 ns/op
|
||||||
BenchmarkCache_SetMediumValue-8 5952064 412 ns/op
|
BenchmarkMap_Set/large_value-8 3921956 393 ns/op
|
||||||
BenchmarkCache_SetLargeValue-8 5969121 411 ns/op
|
// Gocache
|
||||||
BenchmarkCache_GetUsingLRU-8 54545949 45.6 ns/op
|
BenchmarkCache_Get
|
||||||
BenchmarkCache_SetSmallValueUsingLRU-8 5909504 419 ns/op
|
BenchmarkCache_Get/FirstInFirstOut-8 27273036 46.4 ns/op
|
||||||
BenchmarkCache_SetMediumValueUsingLRU-8 5910885 418 ns/op
|
BenchmarkCache_Get/LeastRecentlyUsed-8 26648248 46.3 ns/op
|
||||||
BenchmarkCache_SetLargeValueUsingLRU-8 5867544 419 ns/op
|
BenchmarkCache_Set
|
||||||
BenchmarkCache_SetSmallValueWhenUsingMaxMemoryUsage-8 5477178 462 ns/op
|
BenchmarkCache_Set/FirstInFirstOut_small_value-8 2919584 405 ns/op
|
||||||
BenchmarkCache_SetMediumValueWhenUsingMaxMemoryUsage-8 5417595 475 ns/op
|
BenchmarkCache_Set/FirstInFirstOut_medium_value-8 2990841 391 ns/op
|
||||||
BenchmarkCache_SetLargeValueWhenUsingMaxMemoryUsage-8 5215263 479 ns/op
|
BenchmarkCache_Set/FirstInFirstOut_large_value-8 2970513 391 ns/op
|
||||||
BenchmarkCache_SetSmallValueWithMaxSize10-8 10115574 236 ns/op
|
BenchmarkCache_Set/LeastRecentlyUsed_small_value-8 2962939 402 ns/op
|
||||||
BenchmarkCache_SetMediumValueWithMaxSize10-8 10242792 241 ns/op
|
BenchmarkCache_Set/LeastRecentlyUsed_medium_value-8 2962963 390 ns/op
|
||||||
BenchmarkCache_SetLargeValueWithMaxSize10-8 10201894 241 ns/op
|
BenchmarkCache_Set/LeastRecentlyUsed_large_value-8 2962928 394 ns/op
|
||||||
BenchmarkCache_SetSmallValueWithMaxSize1000-8 9637113 253 ns/op
|
BenchmarkCache_SetUsingMaxMemoryUsage
|
||||||
BenchmarkCache_SetMediumValueWithMaxSize1000-8 9635175 253 ns/op
|
BenchmarkCache_SetUsingMaxMemoryUsage/small_value-8 2683356 447 ns/op
|
||||||
BenchmarkCache_SetLargeValueWithMaxSize1000-8 9598982 260 ns/op
|
BenchmarkCache_SetUsingMaxMemoryUsage/medium_value-8 2637578 441 ns/op
|
||||||
BenchmarkCache_SetSmallValueWithMaxSize100000-8 7642584 337 ns/op
|
BenchmarkCache_SetUsingMaxMemoryUsage/large_value-8 2672434 443 ns/op
|
||||||
BenchmarkCache_SetMediumValueWithMaxSize100000-8 7407571 344 ns/op
|
BenchmarkCache_SetWithMaxSize
|
||||||
BenchmarkCache_SetLargeValueWithMaxSize100000-8 7071360 345 ns/op
|
BenchmarkCache_SetWithMaxSize/100_small_value-8 4782966 252 ns/op
|
||||||
BenchmarkCache_SetSmallValueWithMaxSize100000AndLRU-8 7544194 332 ns/op
|
BenchmarkCache_SetWithMaxSize/10000_small_value-8 4067967 296 ns/op
|
||||||
BenchmarkCache_SetMediumValueWithMaxSize100000AndLRU-8 7667004 344 ns/op
|
BenchmarkCache_SetWithMaxSize/100000_small_value-8 3762055 328 ns/op
|
||||||
BenchmarkCache_SetLargeValueWithMaxSize100000AndLRU-8 7357642 338 ns/op
|
BenchmarkCache_SetWithMaxSize/100_medium_value-8 4760479 252 ns/op
|
||||||
BenchmarkCache_GetAndSetMultipleConcurrently-8 1442306 1684 ns/op
|
BenchmarkCache_SetWithMaxSize/10000_medium_value-8 4081050 295 ns/op
|
||||||
BenchmarkCache_GetAndSetConcurrentlyWithRandomKeysAndLRU-8 5117271 477 ns/op
|
BenchmarkCache_SetWithMaxSize/100000_medium_value-8 3785050 330 ns/op
|
||||||
BenchmarkCache_GetAndSetConcurrentlyWithRandomKeysAndFIFO-8 5228412 475 ns/op
|
BenchmarkCache_SetWithMaxSize/100_large_value-8 4732909 254 ns/op
|
||||||
BenchmarkCache_GetAndSetConcurrentlyWithRandomKeysAndNoEvictionAndLRU-8 5139195 529 ns/op
|
BenchmarkCache_SetWithMaxSize/10000_large_value-8 4079533 297 ns/op
|
||||||
BenchmarkCache_GetAndSetConcurrentlyWithRandomKeysAndNoEvictionAndFIFO-8 5251639 511 ns/op
|
BenchmarkCache_SetWithMaxSize/100000_large_value-8 3712820 331 ns/op
|
||||||
BenchmarkCache_GetAndSetConcurrentlyWithFrequentEvictionsAndLRU-8 7384626 334 ns/op
|
BenchmarkCache_SetWithMaxSizeAndLRU
|
||||||
BenchmarkCache_GetAndSetConcurrentlyWithFrequentEvictionsAndFIFO-8 7361985 332 ns/op
|
BenchmarkCache_SetWithMaxSizeAndLRU/100_small_value-8 4761732 254 ns/op
|
||||||
BenchmarkCache_GetConcurrentlyWithLRU-8 3370784 726 ns/op
|
BenchmarkCache_SetWithMaxSizeAndLRU/10000_small_value-8 4084474 296 ns/op
|
||||||
BenchmarkCache_GetConcurrentlyWithFIFO-8 3749994 681 ns/op
|
BenchmarkCache_SetWithMaxSizeAndLRU/100000_small_value-8 3761402 329 ns/op
|
||||||
BenchmarkCache_GetKeysThatDoNotExistConcurrently-8 17647344 143 ns/op
|
BenchmarkCache_SetWithMaxSizeAndLRU/100_medium_value-8 4783075 254 ns/op
|
||||||
|
BenchmarkCache_SetWithMaxSizeAndLRU/10000_medium_value-8 4103980 296 ns/op
|
||||||
|
BenchmarkCache_SetWithMaxSizeAndLRU/100000_medium_value-8 3646023 331 ns/op
|
||||||
|
BenchmarkCache_SetWithMaxSizeAndLRU/100_large_value-8 4779025 254 ns/op
|
||||||
|
BenchmarkCache_SetWithMaxSizeAndLRU/10000_large_value-8 4096192 296 ns/op
|
||||||
|
BenchmarkCache_SetWithMaxSizeAndLRU/100000_large_value-8 3726823 331 ns/op
|
||||||
|
BenchmarkCache_GetSetMultipleConcurrent
|
||||||
|
BenchmarkCache_GetSetMultipleConcurrent-8 707142 1698 ns/op
|
||||||
|
BenchmarkCache_GetSetConcurrentWithFrequentEviction
|
||||||
|
BenchmarkCache_GetSetConcurrentWithFrequentEviction/FirstInFirstOut-8 3616256 334 ns/op
|
||||||
|
BenchmarkCache_GetSetConcurrentWithFrequentEviction/LeastRecentlyUsed-8 3636367 331 ns/op
|
||||||
|
BenchmarkCache_GetConcurrentWithLRU
|
||||||
|
BenchmarkCache_GetConcurrentWithLRU/FirstInFirstOut-8 4405557 268 ns/op
|
||||||
|
BenchmarkCache_GetConcurrentWithLRU/LeastRecentlyUsed-8 4445475 269 ns/op
|
||||||
|
BenchmarkCache_WithForceNilInterfaceOnNilPointer
|
||||||
|
BenchmarkCache_WithForceNilInterfaceOnNilPointer/true_with_nil_struct_pointer-8 6184591 191 ns/op
|
||||||
|
BenchmarkCache_WithForceNilInterfaceOnNilPointer/true-8 6090482 191 ns/op
|
||||||
|
BenchmarkCache_WithForceNilInterfaceOnNilPointer/false_with_nil_struct_pointer-8 6184629 187 ns/op
|
||||||
|
BenchmarkCache_WithForceNilInterfaceOnNilPointer/false-8 6281781 186 ns/op
|
||||||
|
(Trimmed "BenchmarkCache_" for readability)
|
||||||
|
WithForceNilInterfaceOnNilPointerWithConcurrency
|
||||||
|
WithForceNilInterfaceOnNilPointerWithConcurrency/true_with_nil_struct_pointer-8 4379564 268 ns/op
|
||||||
|
WithForceNilInterfaceOnNilPointerWithConcurrency/true-8 4379558 265 ns/op
|
||||||
|
WithForceNilInterfaceOnNilPointerWithConcurrency/false_with_nil_struct_pointer-8 4444456 261 ns/op
|
||||||
|
WithForceNilInterfaceOnNilPointerWithConcurrency/false-8 4493896 262 ns/op
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ func (cache *Cache) WithEvictionPolicy(policy EvictionPolicy) *Cache {
|
|||||||
// value, _ := cache.Get("key")
|
// value, _ := cache.Get("key")
|
||||||
// // the following returns true, because the interface{} was forcefully set to nil
|
// // the following returns true, because the interface{} was forcefully set to nil
|
||||||
// if value == nil {}
|
// if value == nil {}
|
||||||
// // the following will panic, because the value has been casted to its type
|
// // the following will panic, because the value has been casted to its type (which is nil)
|
||||||
// if value.(*Struct) == nil {}
|
// if value.(*Struct) == nil {}
|
||||||
//
|
//
|
||||||
// If set to false:
|
// If set to false:
|
||||||
@@ -218,7 +218,8 @@ func (cache *Cache) Set(key string, value interface{}) {
|
|||||||
// The TTL provided must be greater than 0, or NoExpiration (-1). If a negative value that isn't -1 (NoExpiration) is
|
// The TTL provided must be greater than 0, or NoExpiration (-1). If a negative value that isn't -1 (NoExpiration) is
|
||||||
// provided, the entry will not be created if the key doesn't exist
|
// provided, the entry will not be created if the key doesn't exist
|
||||||
func (cache *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration) {
|
func (cache *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration) {
|
||||||
// An interface is only nil if both its value and its type are nil, however, passing a pointer
|
// An interface is only nil if both its value and its type are nil, however, passing a nil pointer as an interface{}
|
||||||
|
// means that the interface itself is not nil, because the interface value is nil but not the type.
|
||||||
if cache.forceNilInterfaceOnNilPointer {
|
if cache.forceNilInterfaceOnNilPointer {
|
||||||
if value != nil && (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
if value != nil && (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
||||||
value = nil
|
value = nil
|
||||||
@@ -334,6 +335,13 @@ func (cache *Cache) Get(key string) (interface{}, bool) {
|
|||||||
return entry.Value, true
|
return entry.Value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetValue retrieves an entry using the key passed as parameter
|
||||||
|
// Unlike Get, this function only returns the value
|
||||||
|
func (cache *Cache) GetValue(key string) interface{} {
|
||||||
|
value, _ := cache.Get(key)
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
// GetByKeys retrieves multiple entries using the keys passed as parameter
|
// GetByKeys retrieves multiple entries using the keys passed as parameter
|
||||||
// All keys are returned in the map, regardless of whether they exist or not, however, entries that do not exist in the
|
// All keys are returned in the map, regardless of whether they exist or not, however, entries that do not exist in the
|
||||||
// cache will return nil, meaning that there is no way of determining whether a key genuinely has the value nil, or
|
// cache will return nil, meaning that there is no way of determining whether a key genuinely has the value nil, or
|
||||||
|
|||||||
@@ -3,6 +3,30 @@ package gocache
|
|||||||
type EvictionPolicy string
|
type EvictionPolicy string
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
// LeastRecentlyUsed is an eviction policy that causes the most recently accessed cache entry to be moved to the
|
||||||
|
// head of the cache. Effectively, this causes the cache entries that have not been accessed for some time to
|
||||||
|
// gradually move closer and closer to the tail, and since the tail is the entry that gets deleted when an eviction
|
||||||
|
// is required, it allows less used cache entries to be evicted while keeping recently accessed entries at or close
|
||||||
|
// to the head.
|
||||||
|
//
|
||||||
|
// For instance, creating a Cache with a Cache.MaxSize of 3 and creating the entries 1, 2 and 3 in that order would
|
||||||
|
// put 3 at the head and 1 at the tail:
|
||||||
|
// 3 (head) -> 2 -> 1 (tail)
|
||||||
|
// If the cache entry 1 was then accessed, 1 would become the head and 2 the tail:
|
||||||
|
// 1 (head) -> 3 -> 2 (tail)
|
||||||
|
// If a cache entry 4 was then created, because the Cache.MaxSize is 3, the tail (2) would then be evicted:
|
||||||
|
// 4 (head) -> 1 -> 3 (tail)
|
||||||
LeastRecentlyUsed EvictionPolicy = "LeastRecentlyUsed"
|
LeastRecentlyUsed EvictionPolicy = "LeastRecentlyUsed"
|
||||||
FirstInFirstOut EvictionPolicy = "FirstInFirstOut"
|
|
||||||
|
// FirstInFirstOut is an eviction policy that causes cache entries to be evicted in the same order that they are
|
||||||
|
// created.
|
||||||
|
//
|
||||||
|
// For instance, creating a Cache with a Cache.MaxSize of 3 and creating the entries 1, 2 and 3 in that order would
|
||||||
|
// put 3 at the head and 1 at the tail:
|
||||||
|
// 3 (head) -> 2 -> 1 (tail)
|
||||||
|
// If the cache entry 1 was then accessed, unlike with LeastRecentlyUsed, nothing would change:
|
||||||
|
// 3 (head) -> 2 -> 1 (tail)
|
||||||
|
// If a cache entry 4 was then created, because the Cache.MaxSize is 3, the tail (1) would then be evicted:
|
||||||
|
// 4 (head) -> 3 -> 2 (tail)
|
||||||
|
FirstInFirstOut EvictionPolicy = "FirstInFirstOut"
|
||||||
)
|
)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# cloud.google.com/go v0.74.0
|
# cloud.google.com/go v0.74.0
|
||||||
## explicit
|
## explicit
|
||||||
cloud.google.com/go/compute/metadata
|
cloud.google.com/go/compute/metadata
|
||||||
# github.com/TwinProduction/gocache v1.1.0
|
# github.com/TwinProduction/gocache v1.2.0
|
||||||
## explicit
|
## explicit
|
||||||
github.com/TwinProduction/gocache
|
github.com/TwinProduction/gocache
|
||||||
# github.com/beorn7/perks v1.0.1
|
# github.com/beorn7/perks v1.0.1
|
||||||
|
|||||||
@@ -26,18 +26,18 @@ func handleAlertsToTrigger(service *core.Service, result *core.Result, cfg *conf
|
|||||||
service.NumberOfFailuresInARow++
|
service.NumberOfFailuresInARow++
|
||||||
for _, alert := range service.Alerts {
|
for _, alert := range service.Alerts {
|
||||||
// If the alert hasn't been triggered, move to the next one
|
// If the alert hasn't been triggered, move to the next one
|
||||||
if !alert.Enabled || alert.FailureThreshold != service.NumberOfFailuresInARow {
|
if !alert.Enabled || alert.FailureThreshold > service.NumberOfFailuresInARow {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if alert.Triggered {
|
if alert.Triggered {
|
||||||
if cfg.Debug {
|
if cfg.Debug {
|
||||||
log.Printf("[watchdog][handleAlertsToTrigger] Alert with description='%s' has already been TRIGGERED, skipping", alert.Description)
|
log.Printf("[watchdog][handleAlertsToTrigger] Alert for service=%s with description='%s' has already been TRIGGERED, skipping", service.Name, alert.Description)
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
alertProvider := config.GetAlertingProviderByAlertType(cfg, alert.Type)
|
alertProvider := config.GetAlertingProviderByAlertType(cfg, alert.Type)
|
||||||
if alertProvider != nil && alertProvider.IsValid() {
|
if alertProvider != nil && alertProvider.IsValid() {
|
||||||
log.Printf("[watchdog][handleAlertsToTrigger] Sending %s alert because alert with description='%s' has been TRIGGERED", alert.Type, alert.Description)
|
log.Printf("[watchdog][handleAlertsToTrigger] Sending %s alert because alert for service=%s with description='%s' has been TRIGGERED", alert.Type, service.Name, alert.Description)
|
||||||
customAlertProvider := alertProvider.ToCustomAlertProvider(service, alert, result, false)
|
customAlertProvider := alertProvider.ToCustomAlertProvider(service, alert, result, false)
|
||||||
// TODO: retry on error
|
// TODO: retry on error
|
||||||
var err error
|
var err error
|
||||||
@@ -47,7 +47,7 @@ func handleAlertsToTrigger(service *core.Service, result *core.Result, cfg *conf
|
|||||||
if body, err = customAlertProvider.Send(service.Name, alert.Description, false); err == nil {
|
if body, err = customAlertProvider.Send(service.Name, alert.Description, false); err == nil {
|
||||||
var response pagerDutyResponse
|
var response pagerDutyResponse
|
||||||
if err = json.Unmarshal(body, &response); err != nil {
|
if err = json.Unmarshal(body, &response); err != nil {
|
||||||
log.Printf("[watchdog][handleAlertsToTrigger] Ran into error unmarshaling pager duty response: %s", err.Error())
|
log.Printf("[watchdog][handleAlertsToTrigger] Ran into error unmarshaling pagerduty response: %s", err.Error())
|
||||||
} else {
|
} else {
|
||||||
alert.ResolveKey = response.DedupKey
|
alert.ResolveKey = response.DedupKey
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ func handleAlertsToTrigger(service *core.Service, result *core.Result, cfg *conf
|
|||||||
_, err = customAlertProvider.Send(service.Name, alert.Description, false)
|
_, err = customAlertProvider.Send(service.Name, alert.Description, false)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[watchdog][handleAlertsToTrigger] Ran into error sending an alert: %s", err.Error())
|
log.Printf("[watchdog][handleAlertsToTrigger] Failed to send an alert for service=%s: %s", service.Name, err.Error())
|
||||||
} else {
|
} else {
|
||||||
alert.Triggered = true
|
alert.Triggered = true
|
||||||
}
|
}
|
||||||
@@ -73,18 +73,20 @@ func handleAlertsToResolve(service *core.Service, result *core.Result, cfg *conf
|
|||||||
if !alert.Enabled || !alert.Triggered || alert.SuccessThreshold > service.NumberOfSuccessesInARow {
|
if !alert.Enabled || !alert.Triggered || alert.SuccessThreshold > service.NumberOfSuccessesInARow {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// Even if the alert provider returns an error, we still set the alert's Triggered variable to false.
|
||||||
|
// Further explanation can be found on Alert's Triggered field.
|
||||||
alert.Triggered = false
|
alert.Triggered = false
|
||||||
if !alert.SendOnResolved {
|
if !alert.SendOnResolved {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
alertProvider := config.GetAlertingProviderByAlertType(cfg, alert.Type)
|
alertProvider := config.GetAlertingProviderByAlertType(cfg, alert.Type)
|
||||||
if alertProvider != nil && alertProvider.IsValid() {
|
if alertProvider != nil && alertProvider.IsValid() {
|
||||||
log.Printf("[watchdog][handleAlertsToResolve] Sending %s alert because alert with description='%s' has been RESOLVED", alert.Type, alert.Description)
|
log.Printf("[watchdog][handleAlertsToResolve] Sending %s alert because alert for service=%s with description='%s' has been RESOLVED", alert.Type, service.Name, alert.Description)
|
||||||
customAlertProvider := alertProvider.ToCustomAlertProvider(service, alert, result, true)
|
customAlertProvider := alertProvider.ToCustomAlertProvider(service, alert, result, true)
|
||||||
// TODO: retry on error
|
// TODO: retry on error
|
||||||
_, err := customAlertProvider.Send(service.Name, alert.Description, true)
|
_, err := customAlertProvider.Send(service.Name, alert.Description, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[watchdog][handleAlertsToResolve] Ran into error sending an alert: %s", err.Error())
|
log.Printf("[watchdog][handleAlertsToResolve] Failed to send an alert for service=%s: %s", service.Name, err.Error())
|
||||||
} else {
|
} else {
|
||||||
if alert.Type == core.PagerDutyAlert {
|
if alert.Type == core.PagerDutyAlert {
|
||||||
alert.ResolveKey = ""
|
alert.ResolveKey = ""
|
||||||
|
|||||||
@@ -39,103 +39,23 @@ func TestHandleAlerting(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 0, false, "The alert shouldn't start triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've started at 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've started at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't start triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 1 {
|
verify(t, service, 1, 0, false, "The alert shouldn't have triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 0 to 1, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't have triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 2 {
|
verify(t, service, 2, 0, true, "The alert should've triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 1 to 2, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if !service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should've triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 3 {
|
verify(t, service, 3, 0, true, "The alert should still be triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 2 to 3, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if !service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should still show as triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 4 {
|
verify(t, service, 4, 0, true, "The alert should still be triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 3 to 4, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if !service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should still show as triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: true})
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 1, true, "The alert should still be triggered (because service.Alerts[0].SuccessThreshold is 3)")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've reset to 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 1 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've increased from 0 to 1, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if !service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should still be triggered (because service.Alerts[0].SuccessThreshold is 3)")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: true})
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 2, true, "The alert should still be triggered (because service.Alerts[0].SuccessThreshold is 3)")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've stayed at 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 2 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've increased from 1 to 2, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if !service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should still be triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: true})
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 3, false, "The alert should've been resolved")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've stayed at 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 3 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've increased from 2 to 3, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should not be triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: true})
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 4, false, "The alert should no longer be triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've stayed at 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 4 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've increased from 3 to 4, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should no longer be triggered")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHandleAlertingWhenAlertingConfigIsNil(t *testing.T) {
|
func TestHandleAlertingWhenAlertingConfigIsNil(t *testing.T) {
|
||||||
@@ -172,92 +92,11 @@ func TestHandleAlertingWithBadAlertProvider(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 0, false, "The alert shouldn't start triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've started at 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've started at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't start triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 1 {
|
verify(t, service, 1, 0, false, "The alert shouldn't have triggered")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 0 to 1, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't have triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 2 {
|
verify(t, service, 2, 0, false, "The alert shouldn't have triggered, because the provider wasn't configured properly")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 1 to 2, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't have triggered, because the provider wasn't configured properly")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleAlertingWithoutSendingAlertOnResolve(t *testing.T) {
|
|
||||||
_ = os.Setenv("MOCK_ALERT_PROVIDER", "true")
|
|
||||||
defer os.Clearenv()
|
|
||||||
|
|
||||||
cfg := &config.Config{
|
|
||||||
Alerting: &alerting.Config{},
|
|
||||||
}
|
|
||||||
config.Set(cfg)
|
|
||||||
service := &core.Service{
|
|
||||||
URL: "http://example.com",
|
|
||||||
Alerts: []*core.Alert{
|
|
||||||
{
|
|
||||||
Type: core.CustomAlert,
|
|
||||||
Enabled: true,
|
|
||||||
FailureThreshold: 1,
|
|
||||||
SuccessThreshold: 1,
|
|
||||||
SendOnResolved: false,
|
|
||||||
Triggered: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've started at 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've started at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't start triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
|
||||||
if service.NumberOfFailuresInARow != 1 {
|
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 0 to 1, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't have triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
|
||||||
if service.NumberOfFailuresInARow != 2 {
|
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 1 to 2, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't have triggered, because the provider wasn't configured properly")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHandleAlertingWhenTriggeredAlertIsAlmostResolvedButServiceStartFailingAgain(t *testing.T) {
|
func TestHandleAlertingWhenTriggeredAlertIsAlmostResolvedButServiceStartFailingAgain(t *testing.T) {
|
||||||
@@ -291,15 +130,7 @@ func TestHandleAlertingWhenTriggeredAlertIsAlmostResolvedButServiceStartFailingA
|
|||||||
|
|
||||||
// This test simulate an alert that was already triggered
|
// This test simulate an alert that was already triggered
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 2 {
|
verify(t, service, 2, 0, true, "The alert was already triggered at the beginning of this test")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 1 to 2, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if !service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert was already triggered at the beginning of this test")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHandleAlertingWhenTriggeredAlertIsResolvedButSendOnResolvedIsFalse(t *testing.T) {
|
func TestHandleAlertingWhenTriggeredAlertIsResolvedButSendOnResolvedIsFalse(t *testing.T) {
|
||||||
@@ -332,15 +163,7 @@ func TestHandleAlertingWhenTriggeredAlertIsResolvedButSendOnResolvedIsFalse(t *t
|
|||||||
}
|
}
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: true})
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 1, false, "The alert should've been resolved")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've decreased from 1 to 0, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 1 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've increased from 0 to 1, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't be triggered anymore")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHandleAlertingWhenTriggeredAlertIsResolvedPagerDuty(t *testing.T) {
|
func TestHandleAlertingWhenTriggeredAlertIsResolvedPagerDuty(t *testing.T) {
|
||||||
@@ -372,24 +195,138 @@ func TestHandleAlertingWhenTriggeredAlertIsResolvedPagerDuty(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: false})
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
if service.NumberOfFailuresInARow != 1 {
|
verify(t, service, 1, 0, true, "")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've increased from 0 to 1, got", service.NumberOfFailuresInARow)
|
|
||||||
}
|
|
||||||
if service.NumberOfSuccessesInARow != 0 {
|
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've stayed at 0, got", service.NumberOfSuccessesInARow)
|
|
||||||
}
|
|
||||||
if !service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert should've been triggered")
|
|
||||||
}
|
|
||||||
|
|
||||||
HandleAlerting(service, &core.Result{Success: true})
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
if service.NumberOfFailuresInARow != 0 {
|
verify(t, service, 0, 1, false, "The alert should've been resolved")
|
||||||
t.Fatal("service.NumberOfFailuresInARow should've decreased from 1 to 0, got", service.NumberOfFailuresInARow)
|
}
|
||||||
|
|
||||||
|
func TestHandleAlertingWithProviderThatReturnsAnError(t *testing.T) {
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER", "true")
|
||||||
|
defer os.Clearenv()
|
||||||
|
|
||||||
|
cfg := &config.Config{
|
||||||
|
Debug: true,
|
||||||
|
Alerting: &alerting.Config{
|
||||||
|
Custom: &custom.AlertProvider{
|
||||||
|
URL: "https://twinnation.org/health",
|
||||||
|
Method: "GET",
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if service.NumberOfSuccessesInARow != 1 {
|
config.Set(cfg)
|
||||||
t.Fatal("service.NumberOfSuccessesInARow should've increased from 0 to 1, got", service.NumberOfSuccessesInARow)
|
service := &core.Service{
|
||||||
|
URL: "http://example.com",
|
||||||
|
Alerts: []*core.Alert{
|
||||||
|
{
|
||||||
|
Type: core.CustomAlert,
|
||||||
|
Enabled: true,
|
||||||
|
FailureThreshold: 2,
|
||||||
|
SuccessThreshold: 2,
|
||||||
|
SendOnResolved: true,
|
||||||
|
Triggered: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if service.Alerts[0].Triggered {
|
|
||||||
t.Fatal("The alert shouldn't be triggered anymore")
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "true")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 1, 0, false, "")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 2, 0, false, "The alert should have failed to trigger, because the alert provider is returning an error")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 3, 0, false, "The alert should still not be triggered, because the alert provider is still returning an error")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 4, 0, false, "The alert should still not be triggered, because the alert provider is still returning an error")
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "false")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 5, 0, true, "The alert should've been triggered because the alert provider is no longer returning an error")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 1, true, "The alert should've still been triggered")
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "true")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 2, false, "The alert should've been resolved DESPITE THE ALERT PROVIDER RETURNING AN ERROR. See Alert.Triggered for further explanation.")
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "false")
|
||||||
|
|
||||||
|
// Make sure that everything's working as expected after a rough patch
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 1, 0, false, "")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 2, 0, true, "The alert should have triggered")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 1, true, "The alert should still be triggered")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 2, false, "The alert should have been resolved")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleAlertingWithProviderThatOnlyReturnsErrorOnResolve(t *testing.T) {
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER", "true")
|
||||||
|
defer os.Clearenv()
|
||||||
|
|
||||||
|
cfg := &config.Config{
|
||||||
|
Debug: true,
|
||||||
|
Alerting: &alerting.Config{
|
||||||
|
Custom: &custom.AlertProvider{
|
||||||
|
URL: "https://twinnation.org/health",
|
||||||
|
Method: "GET",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
config.Set(cfg)
|
||||||
|
service := &core.Service{
|
||||||
|
URL: "http://example.com",
|
||||||
|
Alerts: []*core.Alert{
|
||||||
|
{
|
||||||
|
Type: core.CustomAlert,
|
||||||
|
Enabled: true,
|
||||||
|
FailureThreshold: 1,
|
||||||
|
SuccessThreshold: 1,
|
||||||
|
SendOnResolved: true,
|
||||||
|
Triggered: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 1, 0, true, "")
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "true")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 1, false, "")
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "false")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 1, 0, true, "")
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "true")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 1, false, "")
|
||||||
|
_ = os.Setenv("MOCK_ALERT_PROVIDER_ERROR", "false")
|
||||||
|
|
||||||
|
// Make sure that everything's working as expected after a rough patch
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 1, 0, true, "")
|
||||||
|
HandleAlerting(service, &core.Result{Success: false})
|
||||||
|
verify(t, service, 2, 0, true, "")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 1, false, "")
|
||||||
|
HandleAlerting(service, &core.Result{Success: true})
|
||||||
|
verify(t, service, 0, 2, false, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func verify(t *testing.T, service *core.Service, expectedNumberOfFailuresInARow, expectedNumberOfSuccessInARow int, expectedTriggered bool, expectedTriggeredReason string) {
|
||||||
|
if service.NumberOfFailuresInARow != expectedNumberOfFailuresInARow {
|
||||||
|
t.Fatalf("service.NumberOfFailuresInARow should've been %d, got %d", expectedNumberOfFailuresInARow, service.NumberOfFailuresInARow)
|
||||||
|
}
|
||||||
|
if service.NumberOfSuccessesInARow != expectedNumberOfSuccessInARow {
|
||||||
|
t.Fatalf("service.NumberOfSuccessesInARow should've been %d, got %d", expectedNumberOfSuccessInARow, service.NumberOfSuccessesInARow)
|
||||||
|
}
|
||||||
|
if service.Alerts[0].Triggered != expectedTriggered {
|
||||||
|
if len(expectedTriggeredReason) != 0 {
|
||||||
|
t.Fatal(expectedTriggeredReason)
|
||||||
|
} else {
|
||||||
|
if expectedTriggered {
|
||||||
|
t.Fatal("The alert should've been triggered")
|
||||||
|
} else {
|
||||||
|
t.Fatal("The alert shouldn't have been triggered")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,8 +13,6 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
store = storage.NewInMemoryStore()
|
|
||||||
|
|
||||||
// monitoringMutex is used to prevent multiple services from being evaluated at the same time.
|
// monitoringMutex is used to prevent multiple services from being evaluated at the same time.
|
||||||
// Without this, conditions using response time may become inaccurate.
|
// Without this, conditions using response time may become inaccurate.
|
||||||
monitoringMutex sync.Mutex
|
monitoringMutex sync.Mutex
|
||||||
@@ -22,18 +20,23 @@ var (
|
|||||||
|
|
||||||
// GetServiceStatusesAsJSON the JSON encoding of all core.ServiceStatus recorded
|
// GetServiceStatusesAsJSON the JSON encoding of all core.ServiceStatus recorded
|
||||||
func GetServiceStatusesAsJSON() ([]byte, error) {
|
func GetServiceStatusesAsJSON() ([]byte, error) {
|
||||||
return store.GetAllAsJSON()
|
return storage.Get().GetAllAsJSON()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUptimeByServiceGroupAndName returns the uptime of a service based on its group and name
|
// GetUptimeByKey returns the uptime of a service based on the ServiceStatus key
|
||||||
func GetUptimeByServiceGroupAndName(group, name string) *core.Uptime {
|
func GetUptimeByKey(key string) *core.Uptime {
|
||||||
serviceStatus := store.GetServiceStatus(group, name)
|
serviceStatus := storage.Get().GetServiceStatusByKey(key)
|
||||||
if serviceStatus == nil {
|
if serviceStatus == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return serviceStatus.Uptime
|
return serviceStatus.Uptime
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetServiceStatusByKey returns the uptime of a service based on its ServiceStatus key
|
||||||
|
func GetServiceStatusByKey(key string) *core.ServiceStatus {
|
||||||
|
return storage.Get().GetServiceStatusByKey(key)
|
||||||
|
}
|
||||||
|
|
||||||
// Monitor loops over each services and starts a goroutine to monitor each services separately
|
// Monitor loops over each services and starts a goroutine to monitor each services separately
|
||||||
func Monitor(cfg *config.Config) {
|
func Monitor(cfg *config.Config) {
|
||||||
for _, service := range cfg.Services {
|
for _, service := range cfg.Services {
|
||||||
@@ -83,5 +86,5 @@ func monitor(service *core.Service) {
|
|||||||
|
|
||||||
// UpdateServiceStatuses updates the slice of service statuses
|
// UpdateServiceStatuses updates the slice of service statuses
|
||||||
func UpdateServiceStatuses(service *core.Service, result *core.Result) {
|
func UpdateServiceStatuses(service *core.Service, result *core.Result) {
|
||||||
store.Insert(service, result)
|
storage.Get().Insert(service, result)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
.DS_Store
|
||||||
|
node_modules
|
||||||
|
/dist
|
||||||
|
|
||||||
|
|
||||||
|
# local env files
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# Log files
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# app
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
```
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compiles and hot-reloads for development
|
||||||
|
```
|
||||||
|
npm run serve
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compiles and minifies for production
|
||||||
|
```
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Lints and fixes files
|
||||||
|
```
|
||||||
|
npm run lint
|
||||||
|
```
|
||||||
|
|
||||||
|
### Customize configuration
|
||||||
|
See [Configuration Reference](https://cli.vuejs.org/config/).
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module.exports = {
|
||||||
|
presets: [
|
||||||
|
'@vue/cli-plugin-babel/preset'
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"name": "app",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"serve": "vue-cli-service serve --mode development",
|
||||||
|
"build": "vue-cli-service build --mode production",
|
||||||
|
"lint": "vue-cli-service lint"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tailwindcss/postcss7-compat": "^2.0.2",
|
||||||
|
"autoprefixer": "^9.8.6",
|
||||||
|
"core-js": "^3.6.5",
|
||||||
|
"postcss": "^7.0.35",
|
||||||
|
"tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.0.2",
|
||||||
|
"vue": "^3.0.0",
|
||||||
|
"vue-router": "^4.0.0-0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vue/cli-plugin-babel": "~4.5.0",
|
||||||
|
"@vue/cli-plugin-eslint": "~4.5.0",
|
||||||
|
"@vue/cli-plugin-router": "~4.5.0",
|
||||||
|
"@vue/cli-service": "~4.5.0",
|
||||||
|
"@vue/compiler-sfc": "^3.0.0",
|
||||||
|
"babel-eslint": "^10.1.0",
|
||||||
|
"eslint": "^6.7.2",
|
||||||
|
"eslint-plugin-vue": "^7.0.0-0"
|
||||||
|
},
|
||||||
|
"eslintConfig": {
|
||||||
|
"root": true,
|
||||||
|
"env": {
|
||||||
|
"node": true
|
||||||
|
},
|
||||||
|
"extends": [
|
||||||
|
"plugin:vue/vue3-essential",
|
||||||
|
"eslint:recommended"
|
||||||
|
],
|
||||||
|
"parserOptions": {
|
||||||
|
"parser": "babel-eslint"
|
||||||
|
},
|
||||||
|
"rules": {}
|
||||||
|
},
|
||||||
|
"browserslist": [
|
||||||
|
"> 1%",
|
||||||
|
"last 2 versions",
|
||||||
|
"not dead"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module.exports = {
|
||||||
|
plugins: [
|
||||||
|
require('tailwindcss')
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||||
|
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
||||||
|
<title>Health Dashboard | Gatus</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<noscript>
|
||||||
|
<strong>Enable JavaScript to view this page.</strong>
|
||||||
|
</noscript>
|
||||||
|
<div id="app"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<template>
|
||||||
|
<div class="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" id="global">
|
||||||
|
<div class="mb-2">
|
||||||
|
<div class="flex flex-wrap">
|
||||||
|
<div class="w-3/4 text-left my-auto">
|
||||||
|
<div class="text-3xl xl:text-5xl lg:text-4xl font-light">Health Status</div>
|
||||||
|
</div>
|
||||||
|
<div class="w-1/4 flex justify-end">
|
||||||
|
<img src="./assets/logo.png" alt="Gatus" class="object-scale-down" style="max-width: 100px; min-width: 50px; min-height:50px;"/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<router-view @showTooltip="showTooltip"/>
|
||||||
|
</div>
|
||||||
|
<Tooltip :result="tooltip.result" :event="tooltip.event"/>
|
||||||
|
<Social/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import Social from './components/Social.vue'
|
||||||
|
import Tooltip from './components/Tooltip.vue';
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'App',
|
||||||
|
components: {
|
||||||
|
Social,
|
||||||
|
Tooltip
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
showTooltip(result, event) {
|
||||||
|
this.tooltip = {result: result, event: event};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
tooltip: {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<style>
|
||||||
|
html {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
background-color: #f7f9fb;
|
||||||
|
}
|
||||||
|
|
||||||
|
#global, #results {
|
||||||
|
max-width: 1200px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
@@ -0,0 +1,147 @@
|
|||||||
|
<template>
|
||||||
|
<div class='service px-3 py-3 border-l border-r border-t rounded-none hover:bg-gray-100' v-if="data && data.results && data.results.length">
|
||||||
|
<div class='flex flex-wrap mb-2'>
|
||||||
|
<div class='w-3/4'>
|
||||||
|
<router-link :to="generatePath()" class="font-bold hover:text-blue-800 hover:underline" title="View detailed service health">
|
||||||
|
{{ data.name }}
|
||||||
|
</router-link>
|
||||||
|
<span class='text-gray-500 font-light'> | {{ data.results[data.results.length - 1].hostname }}</span>
|
||||||
|
</div>
|
||||||
|
<div class='w-1/4 text-right'>
|
||||||
|
<span class='font-light status-min-max-ms'>
|
||||||
|
{{ (minResponseTime === maxResponseTime ? minResponseTime : (minResponseTime + '-' + maxResponseTime)) }}ms
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class='status-over-time flex flex-row'>
|
||||||
|
<slot v-for="filler in maximumNumberOfResults - data.results.length" :key="filler">
|
||||||
|
<span class="status rounded border border-dashed"> </span>
|
||||||
|
</slot>
|
||||||
|
<slot v-for="result in data.results" :key="result">
|
||||||
|
<span v-if="result.success" class="status rounded bg-success" @mouseenter="showTooltip(result, $event)" @mouseleave="showTooltip(null, $event)">✓</span>
|
||||||
|
<span v-else class="status rounded bg-red-600" @mouseenter="showTooltip(result, $event)" @mouseleave="showTooltip(null, $event)">X</span>
|
||||||
|
</slot>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class='flex flex-wrap status-time-ago'>
|
||||||
|
<!-- Show "Last update at" instead? -->
|
||||||
|
<div class='w-1/2'>
|
||||||
|
{{ generatePrettyTimeAgo(data.results[0].timestamp) }}
|
||||||
|
</div>
|
||||||
|
<div class='w-1/2 text-right'>
|
||||||
|
{{ generatePrettyTimeAgo(data.results[data.results.length - 1].timestamp) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import {helper} from "@/mixins/helper";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'Service',
|
||||||
|
props: {
|
||||||
|
maximumNumberOfResults: Number,
|
||||||
|
data: Object,
|
||||||
|
},
|
||||||
|
emits: ['showTooltip'],
|
||||||
|
mixins: [helper],
|
||||||
|
methods: {
|
||||||
|
updateMinAndMaxResponseTimes() {
|
||||||
|
let minResponseTime = null;
|
||||||
|
let maxResponseTime = null;
|
||||||
|
for (let i in this.data.results) {
|
||||||
|
const responseTime = parseInt(this.data.results[i].duration/1000000);
|
||||||
|
if (minResponseTime == null || minResponseTime > responseTime) {
|
||||||
|
minResponseTime = responseTime;
|
||||||
|
}
|
||||||
|
if (maxResponseTime == null || maxResponseTime < responseTime) {
|
||||||
|
maxResponseTime = responseTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.minResponseTime !== minResponseTime) {
|
||||||
|
this.minResponseTime = minResponseTime;
|
||||||
|
}
|
||||||
|
if (this.maxResponseTime !== maxResponseTime) {
|
||||||
|
this.maxResponseTime = maxResponseTime;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
generatePath() {
|
||||||
|
if (!this.data) {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
return `/services/${this.data.key}`;
|
||||||
|
},
|
||||||
|
showTooltip(result, event) {
|
||||||
|
this.$emit('showTooltip', result, event);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
data: function () {
|
||||||
|
this.updateMinAndMaxResponseTimes();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
created() {
|
||||||
|
this.updateMinAndMaxResponseTimes()
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
minResponseTime: 0,
|
||||||
|
maxResponseTime: 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.service:first-child {
|
||||||
|
border-top-left-radius: 3px;
|
||||||
|
border-top-right-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.service:last-child {
|
||||||
|
border-bottom-left-radius: 3px;
|
||||||
|
border-bottom-right-radius: 3px;
|
||||||
|
border-bottom-width: 3px;
|
||||||
|
border-color: #dee2e6;
|
||||||
|
border-style: solid;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 500ms ease-in-out;
|
||||||
|
overflow-x: hidden;
|
||||||
|
color: white;
|
||||||
|
width: 5%;
|
||||||
|
font-size: 75%;
|
||||||
|
font-weight: 700;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status:hover {
|
||||||
|
opacity: 0.7;
|
||||||
|
transition: opacity 100ms ease-in-out;
|
||||||
|
color: black;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-over-time {
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-over-time > span:not(:first-child) {
|
||||||
|
margin-left: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-time-ago {
|
||||||
|
color: #6a737d;
|
||||||
|
opacity: 0.5;
|
||||||
|
margin-top: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-min-max-ms {
|
||||||
|
overflow-x: hidden;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
<template>
|
||||||
|
<div :class="services.length === 0 ? 'mt-3' : 'mt-4'">
|
||||||
|
<slot v-if="name !== 'undefined'">
|
||||||
|
<div class="service-group pt-2 border" @click="toggleGroup">
|
||||||
|
<h5 class='text-monospace text-gray-400 text-xl font-medium pb-2 px-3'>
|
||||||
|
<span v-if="healthy" class='text-green-600'>✓</span>
|
||||||
|
<span v-else class='text-yellow-400'>~</span>
|
||||||
|
{{ name }}
|
||||||
|
<span class='float-right service-group-arrow'>
|
||||||
|
{{ collapsed ? '▼' : '▲' }}
|
||||||
|
</span>
|
||||||
|
</h5>
|
||||||
|
</div>
|
||||||
|
</slot>
|
||||||
|
<div v-if="!collapsed" :class="name === 'undefined' ? '' : 'service-group-content'">
|
||||||
|
<slot v-for="service in services" :key="service">
|
||||||
|
<Service :data="service" @showTooltip="showTooltip" :maximumNumberOfResults="20"/>
|
||||||
|
</slot>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import Service from './Service.vue';
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'ServiceGroup',
|
||||||
|
components: {
|
||||||
|
Service
|
||||||
|
},
|
||||||
|
props: {
|
||||||
|
name: String,
|
||||||
|
services: Array
|
||||||
|
},
|
||||||
|
emits: ['showTooltip'],
|
||||||
|
methods: {
|
||||||
|
healthCheck() {
|
||||||
|
if (this.services) {
|
||||||
|
for (let i in this.services) {
|
||||||
|
for (let j in this.services[i].results) {
|
||||||
|
if (!this.services[i].results[j].success) {
|
||||||
|
// Set the service group to unhealthy (only if it's currently healthy)
|
||||||
|
if (this.healthy) {
|
||||||
|
this.healthy = false;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Set the service group to healthy (only if it's currently unhealthy)
|
||||||
|
if (!this.healthy) {
|
||||||
|
this.healthy = true;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
toggleGroup() {
|
||||||
|
this.collapsed = !this.collapsed;
|
||||||
|
sessionStorage.setItem(`service-group:${this.name}:collapsed`, this.collapsed);
|
||||||
|
},
|
||||||
|
showTooltip(result, event) {
|
||||||
|
this.$emit('showTooltip', result, event);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
services: function () {
|
||||||
|
this.healthCheck();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
created() {
|
||||||
|
this.healthCheck();
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
healthy: true,
|
||||||
|
collapsed: sessionStorage.getItem(`service-group:${this.name}:collapsed`) === "true"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.service-group {
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.service-group h5:hover {
|
||||||
|
color: #1b1e21 !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<template>
|
||||||
|
<div id="results">
|
||||||
|
<slot v-for="serviceGroup in serviceGroups" :key="serviceGroup">
|
||||||
|
<ServiceGroup :services="serviceGroup.services" :name="serviceGroup.name" @showTooltip="showTooltip"/>
|
||||||
|
</slot>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import ServiceGroup from './ServiceGroup.vue';
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'Services',
|
||||||
|
components: {
|
||||||
|
ServiceGroup
|
||||||
|
},
|
||||||
|
props: {
|
||||||
|
showStatusOnHover: Boolean,
|
||||||
|
serviceStatuses: Object
|
||||||
|
},
|
||||||
|
emits: ['showTooltip'],
|
||||||
|
methods: {
|
||||||
|
process() {
|
||||||
|
let outputByGroup = {};
|
||||||
|
for (let serviceStatusIndex in this.serviceStatuses) {
|
||||||
|
let serviceStatus = this.serviceStatuses[serviceStatusIndex];
|
||||||
|
// create an empty entry if this group is new
|
||||||
|
if (!outputByGroup[serviceStatus.group] || outputByGroup[serviceStatus.group].length === 0) {
|
||||||
|
outputByGroup[serviceStatus.group] = [];
|
||||||
|
}
|
||||||
|
outputByGroup[serviceStatus.group].push(serviceStatus);
|
||||||
|
}
|
||||||
|
let serviceGroups = [];
|
||||||
|
for (let name in outputByGroup) {
|
||||||
|
if (name !== 'undefined') {
|
||||||
|
serviceGroups.push({name: name, services: outputByGroup[name]})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Add all services that don't have a group at the end
|
||||||
|
if (outputByGroup['undefined']) {
|
||||||
|
serviceGroups.push({name: 'undefined', services: outputByGroup['undefined']})
|
||||||
|
}
|
||||||
|
this.serviceGroups = serviceGroups;
|
||||||
|
},
|
||||||
|
showTooltip(result, event) {
|
||||||
|
this.$emit('showTooltip', result, event);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
serviceStatuses: function () {
|
||||||
|
this.process();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
userClickedStatus: false,
|
||||||
|
serviceGroups: []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.service-group-content > div:nth-child(1) {
|
||||||
|
border-top-left-radius: 0;
|
||||||
|
border-top-right-radius: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<template>
|
||||||
|
<div id="settings">
|
||||||
|
<div class="flex bg-gray-200 rounded border border-gray-300 shadow">
|
||||||
|
<div class="text-sm text-gray-600 rounded-xl py-1 px-2">
|
||||||
|
↻
|
||||||
|
</div>
|
||||||
|
<select class="text-center text-gray-500 text-sm" id="refresh-rate" ref="refreshInterval" @change="handleChangeRefreshInterval">
|
||||||
|
<option value="10">10s</option>
|
||||||
|
<option value="30" selected>30s</option>
|
||||||
|
<option value="60">1m</option>
|
||||||
|
<option value="120">2m</option>
|
||||||
|
<option value="300">5m</option>
|
||||||
|
<option value="600">10m</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
name: 'Settings',
|
||||||
|
props: {},
|
||||||
|
methods: {
|
||||||
|
setRefreshInterval(seconds) {
|
||||||
|
let that = this;
|
||||||
|
this.refreshIntervalHandler = setInterval(function () {
|
||||||
|
that.refreshData();
|
||||||
|
}, seconds * 1000);
|
||||||
|
},
|
||||||
|
refreshData() {
|
||||||
|
this.$emit('refreshData');
|
||||||
|
},
|
||||||
|
handleChangeRefreshInterval() {
|
||||||
|
this.refreshData();
|
||||||
|
clearInterval(this.refreshIntervalHandler);
|
||||||
|
this.setRefreshInterval(this.$refs.refreshInterval.value);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
created() {
|
||||||
|
this.setRefreshInterval(this.refreshInterval);
|
||||||
|
},
|
||||||
|
unmounted() {
|
||||||
|
clearInterval(this.refreshIntervalHandler);
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
refreshInterval: 30,
|
||||||
|
refreshIntervalHandler: 0,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// props.refreshInterval = 30
|
||||||
|
//$("#refresh-rate").val(30);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
#settings {
|
||||||
|
position: fixed;
|
||||||
|
left: 5px;
|
||||||
|
bottom: 5px;
|
||||||
|
padding: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#settings select:focus {
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<template>
|
||||||
|
<div id="social">
|
||||||
|
<a href="https://github.com/TwinProduction/gatus" target="_blank" title="Gatus on GitHub">
|
||||||
|
<img src="../assets/github.png" alt="GitHub" width="32" height="auto"/>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
name: 'Social'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
#social {
|
||||||
|
position: fixed;
|
||||||
|
right: 5px;
|
||||||
|
bottom: 5px;
|
||||||
|
padding: 5px;
|
||||||
|
margin: 0;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
#social img {
|
||||||
|
opacity: 0.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
#social img:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
<template>
|
||||||
|
<div id="tooltip" ref="tooltip" :class="hidden ? 'invisible' : ''" :style="'top:' + top + 'px; left:' + left + 'px'">
|
||||||
|
<slot v-if="result">
|
||||||
|
<div class="tooltip-title">Timestamp:</div>
|
||||||
|
<code id="tooltip-timestamp">{{ prettifyTimestamp(result.timestamp) }}</code>
|
||||||
|
<div class="tooltip-title">Response time:</div>
|
||||||
|
<code id="tooltip-response-time">{{ (result.duration / 1000000).toFixed(0) }}ms</code>
|
||||||
|
<div class="tooltip-title">Conditions:</div>
|
||||||
|
<code id="tooltip-conditions">
|
||||||
|
<slot v-for="conditionResult in result.conditionResults" :key="conditionResult">
|
||||||
|
{{ conditionResult.success ? "✓" : "X" }} ~ {{ conditionResult.condition }}<br/>
|
||||||
|
</slot>
|
||||||
|
</code>
|
||||||
|
<div id="tooltip-errors-container" v-if="result.errors && result.errors.length">
|
||||||
|
<div class="tooltip-title">Errors:</div>
|
||||||
|
<code id="tooltip-errors">
|
||||||
|
<slot v-for="error in result.errors" :key="error">
|
||||||
|
- {{ error }}<br/>
|
||||||
|
</slot>
|
||||||
|
</code>
|
||||||
|
</div>
|
||||||
|
</slot>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
name: 'Services',
|
||||||
|
props: {
|
||||||
|
event: Event,
|
||||||
|
result: Object
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
prettifyTimestamp(timestamp) {
|
||||||
|
let date = new Date(timestamp);
|
||||||
|
let YYYY = date.getFullYear();
|
||||||
|
let MM = ((date.getMonth() + 1) < 10 ? "0" : "") + "" + (date.getMonth() + 1);
|
||||||
|
let DD = ((date.getDate()) < 10 ? "0" : "") + "" + (date.getDate());
|
||||||
|
let hh = ((date.getHours()) < 10 ? "0" : "") + "" + (date.getHours());
|
||||||
|
let mm = ((date.getMinutes()) < 10 ? "0" : "") + "" + (date.getMinutes());
|
||||||
|
let ss = ((date.getSeconds()) < 10 ? "0" : "") + "" + (date.getSeconds());
|
||||||
|
return YYYY + "-" + MM + "-" + DD + " " + hh + ":" + mm + ":" + ss;
|
||||||
|
},
|
||||||
|
htmlEntities(s) {
|
||||||
|
return String(s)
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
},
|
||||||
|
reposition() {
|
||||||
|
if (this.event && this.event.type) {
|
||||||
|
if (this.event.type === 'mouseenter') {
|
||||||
|
let targetTopPosition = this.event.target.getBoundingClientRect().y + 30;
|
||||||
|
let targetLeftPosition = this.event.target.getBoundingClientRect().x;
|
||||||
|
let tooltipBoundingClientRect = this.$refs.tooltip.getBoundingClientRect();
|
||||||
|
if (targetLeftPosition + window.scrollX + tooltipBoundingClientRect.width + 50 > document.body.getBoundingClientRect().width) {
|
||||||
|
targetLeftPosition = this.event.target.getBoundingClientRect().x - tooltipBoundingClientRect.width + this.event.target.getBoundingClientRect().width;
|
||||||
|
if (targetLeftPosition < 0) {
|
||||||
|
targetLeftPosition += -targetLeftPosition;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (targetTopPosition + window.scrollY + tooltipBoundingClientRect.height + 50 > document.body.getBoundingClientRect().height && targetTopPosition >= 0) {
|
||||||
|
targetTopPosition = this.event.target.getBoundingClientRect().y - (tooltipBoundingClientRect.height + 10);
|
||||||
|
if (targetTopPosition < 0) {
|
||||||
|
targetTopPosition = this.event.target.getBoundingClientRect().y + 30;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.top = targetTopPosition;
|
||||||
|
this.left = targetLeftPosition;
|
||||||
|
} else if (this.event.type === 'mouseleave') {
|
||||||
|
this.hidden = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
event: function (value) {
|
||||||
|
if (value && value.type) {
|
||||||
|
if (value.type === 'mouseenter') {
|
||||||
|
this.hidden = false;
|
||||||
|
} else if (value.type === 'mouseleave') {
|
||||||
|
this.hidden = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
updated() {
|
||||||
|
this.reposition();
|
||||||
|
},
|
||||||
|
created() {
|
||||||
|
this.reposition();
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
hidden: true,
|
||||||
|
top: 0,
|
||||||
|
left: 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<style>
|
||||||
|
#tooltip {
|
||||||
|
position: fixed;
|
||||||
|
background-color: white;
|
||||||
|
border: 1px solid lightgray;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tooltip code {
|
||||||
|
color: #212529;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tooltip .tooltip-title {
|
||||||
|
font-weight: bold;
|
||||||
|
margin-bottom: 0;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tooltip .tooltip-title {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tooltip > .tooltip-title:first-child {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
.bg-success {
|
||||||
|
background-color: #28a745;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-monospace {
|
||||||
|
font-family: Consolas, monospace;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import App from './App.vue'
|
||||||
|
import './index.css'
|
||||||
|
import router from './router'
|
||||||
|
|
||||||
|
export const SERVER_URL = process.env.NODE_ENV === 'production' ? '.' : 'http://localhost:8080'
|
||||||
|
|
||||||
|
createApp(App).use(router).mount('#app')
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
export const helper = {
|
||||||
|
methods: {
|
||||||
|
generatePrettyTimeAgo(t) {
|
||||||
|
let differenceInMs = new Date().getTime() - new Date(t).getTime();
|
||||||
|
if (differenceInMs > 3600000) {
|
||||||
|
let hours = (differenceInMs / 3600000).toFixed(0);
|
||||||
|
return hours + " hour" + (hours !== "1" ? "s" : "") + " ago";
|
||||||
|
}
|
||||||
|
if (differenceInMs > 60000) {
|
||||||
|
let minutes = (differenceInMs / 60000).toFixed(0);
|
||||||
|
return minutes + " minute" + (minutes !== "1" ? "s" : "") + " ago";
|
||||||
|
}
|
||||||
|
return (differenceInMs / 1000).toFixed(0) + " seconds ago";
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import {createRouter, createWebHistory} from 'vue-router'
|
||||||
|
import Home from '@/views/Home'
|
||||||
|
import Details from "@/views/Details";
|
||||||
|
|
||||||
|
const routes = [
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
name: 'Home',
|
||||||
|
component: Home
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/services/:key',
|
||||||
|
name: 'Details',
|
||||||
|
component: Details,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(process.env.BASE_URL),
|
||||||
|
routes
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
<template>
|
||||||
|
<router-link to="../" class="absolute top-2 left-2 inline-block px-2 py-0 text-lg text-black transition bg-gray-100 rounded shadow ripple hover:shadow-lg hover:bg-gray-200 focus:outline-none">
|
||||||
|
←
|
||||||
|
</router-link>
|
||||||
|
<div>
|
||||||
|
<slot v-if="serviceStatus">
|
||||||
|
<h1 class="text-xl xl:text-3xl text-monospace text-gray-400">RECENT CHECKS</h1>
|
||||||
|
<hr class="mb-4" />
|
||||||
|
<Service :data="serviceStatus" :maximumNumberOfResults="20" @showTooltip="showTooltip" />
|
||||||
|
</slot>
|
||||||
|
<div v-if="uptime" class="mt-12">
|
||||||
|
<h1 class="text-xl xl:text-3xl text-monospace text-gray-400">UPTIME</h1>
|
||||||
|
<hr />
|
||||||
|
<div class="flex space-x-4 text-center text-xl xl:text-2xl mt-3">
|
||||||
|
<div class="flex-1">
|
||||||
|
{{ prettifyUptime(uptime['7d']) }}
|
||||||
|
<h2 class="text-sm text-gray-400">Last 7 days</h2>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1">
|
||||||
|
{{ prettifyUptime(uptime['24h']) }}
|
||||||
|
<h2 class="text-sm text-gray-400">Last 24 hours</h2>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1">
|
||||||
|
{{ prettifyUptime(uptime['1h']) }}
|
||||||
|
<h2 class="text-sm text-gray-400">Last hour</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<hr class="mt-1"/>
|
||||||
|
<h3 class="text-xl text-monospace text-gray-400 mt-1 text-right">BADGES</h3>
|
||||||
|
<div v-if="serviceStatus && serviceStatus.key" class="flex space-x-4 text-center text-2xl mt-6 relative bottom-12">
|
||||||
|
<div class="flex-1">
|
||||||
|
<img :src="generateBadgeImageURL('7d')" alt="7d uptime badge" class="mx-auto" />
|
||||||
|
</div>
|
||||||
|
<div class="flex-1">
|
||||||
|
<img :src="generateBadgeImageURL('24h')" alt="24h uptime badge" class="mx-auto" />
|
||||||
|
</div>
|
||||||
|
<div class="flex-1">
|
||||||
|
<img :src="generateBadgeImageURL('1h')" alt="1h uptime badge" class="mx-auto" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h1 class="text-xl xl:text-3xl text-monospace text-gray-400 mt-4">EVENTS</h1>
|
||||||
|
<hr class="mb-4" />
|
||||||
|
<div>
|
||||||
|
<slot v-for="event in events" :key="event">
|
||||||
|
<div class="p-3 my-4">
|
||||||
|
<h2 class="text-lg">
|
||||||
|
<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" />
|
||||||
|
<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" />
|
||||||
|
<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" />
|
||||||
|
{{ event.fancyText }}
|
||||||
|
</h2>
|
||||||
|
<div class="flex mt-1 text-sm text-gray-400">
|
||||||
|
<div class="flex-1 text-left pl-10">
|
||||||
|
{{ new Date(event.timestamp).toISOString() }}
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 text-right">
|
||||||
|
{{ event.fancyTimeAgo }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</slot>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Settings @refreshData="fetchData"/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import Settings from '@/components/Settings.vue'
|
||||||
|
import Service from '@/components/Service.vue';
|
||||||
|
import {SERVER_URL} from "@/main.js";
|
||||||
|
import {helper} from "@/mixins/helper.js";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'Details',
|
||||||
|
components: {
|
||||||
|
Service,
|
||||||
|
Settings,
|
||||||
|
},
|
||||||
|
emits: ['showTooltip'],
|
||||||
|
mixins: [helper],
|
||||||
|
methods: {
|
||||||
|
fetchData() {
|
||||||
|
//console.log("[Details][fetchData] Fetching data");
|
||||||
|
fetch(`${this.serverUrl}/api/v1/statuses/${this.$route.params.key}`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (JSON.stringify(this.serviceStatus) !== JSON.stringify(data)) {
|
||||||
|
this.serviceStatus = data.serviceStatus;
|
||||||
|
this.uptime = data.uptime;
|
||||||
|
let events = [];
|
||||||
|
for (let i = data.events.length-1; i >= 0; i--) {
|
||||||
|
let event = data.events[i];
|
||||||
|
if (i === data.events.length-1) {
|
||||||
|
if (event.type === 'UNHEALTHY') {
|
||||||
|
event.fancyText = 'Service is unhealthy';
|
||||||
|
} else if (event.type === 'HEALTHY') {
|
||||||
|
event.fancyText = 'Service is healthy';
|
||||||
|
} else if (event.type === 'START') {
|
||||||
|
event.fancyText = 'Monitoring started';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let nextEvent = data.events[i+1];
|
||||||
|
if (event.type === 'HEALTHY') {
|
||||||
|
event.fancyText = 'Service became healthy';
|
||||||
|
} else if (event.type === 'UNHEALTHY') {
|
||||||
|
if (nextEvent) {
|
||||||
|
event.fancyText = 'Service was unhealthy for ' + this.prettifyTimeDifference(nextEvent.timestamp, event.timestamp);
|
||||||
|
} else {
|
||||||
|
event.fancyText = 'Service became unhealthy';
|
||||||
|
}
|
||||||
|
} else if (event.type === 'START') {
|
||||||
|
event.fancyText = 'Monitoring started';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
event.fancyTimeAgo = this.generatePrettyTimeAgo(event.timestamp);
|
||||||
|
events.push(event);
|
||||||
|
}
|
||||||
|
this.events = events;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
generateBadgeImageURL(duration) {
|
||||||
|
return `${this.serverUrl}/api/v1/badges/uptime/${duration}/${this.serviceStatus.key}`;
|
||||||
|
},
|
||||||
|
prettifyUptime(uptime) {
|
||||||
|
if (!uptime) {
|
||||||
|
return '0%';
|
||||||
|
}
|
||||||
|
return (uptime * 100).toFixed(2) + '%'
|
||||||
|
},
|
||||||
|
prettifyTimeDifference(start, end) {
|
||||||
|
let minutes = Math.ceil((new Date(start) - new Date(end))/1000/60);
|
||||||
|
return minutes + (minutes === 1 ? ' minute' : ' minutes');
|
||||||
|
},
|
||||||
|
showTooltip(result, event) {
|
||||||
|
this.$emit('showTooltip', result, event);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
serviceStatus: {},
|
||||||
|
events: [],
|
||||||
|
uptime: {"7d": 0, "24h": 0, "1h": 0},
|
||||||
|
// Since this page isn't at the root, we need to modify the server URL a bit
|
||||||
|
serverUrl: SERVER_URL === '.' ? '..' : SERVER_URL,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
created() {
|
||||||
|
this.fetchData();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.service {
|
||||||
|
border-radius: 3px;
|
||||||
|
border-bottom-width: 3px;
|
||||||
|
border-color: #dee2e6;
|
||||||
|
border-style: solid;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<template>
|
||||||
|
<Services :serviceStatuses="serviceStatuses" :showStatusOnHover="true" @showTooltip="showTooltip"/>
|
||||||
|
<Settings @refreshData="fetchData"/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import Settings from '@/components/Settings.vue'
|
||||||
|
import Services from '@/components/Services.vue';
|
||||||
|
import {SERVER_URL} from "@/main.js";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'Home',
|
||||||
|
components: {
|
||||||
|
Services,
|
||||||
|
Settings,
|
||||||
|
},
|
||||||
|
emits: ['showTooltip'],
|
||||||
|
methods: {
|
||||||
|
fetchData() {
|
||||||
|
//console.log("[Home][fetchData] Fetching data");
|
||||||
|
fetch(`${SERVER_URL}/api/v1/statuses`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (JSON.stringify(this.serviceStatuses) !== JSON.stringify(data)) {
|
||||||
|
this.serviceStatuses = data;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
showTooltip(result, event) {
|
||||||
|
this.$emit('showTooltip', result, event);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
serviceStatuses: {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
created() {
|
||||||
|
this.fetchData();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
module.exports = {
|
||||||
|
purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
|
||||||
|
darkMode: false, // or 'media' or 'class'
|
||||||
|
theme: {
|
||||||
|
extend: {},
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
extend: {},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
filenameHashing: false,
|
||||||
|
productionSourceMap: false,
|
||||||
|
outputDir: '../static',
|
||||||
|
publicPath: '/'
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
#social[data-v-1cbbc992]{position:fixed;right:5px;bottom:5px;padding:5px;margin:0;z-index:100}#social img[data-v-1cbbc992]{opacity:.3}#social img[data-v-1cbbc992]: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}html{height:100%}body,html{background-color:#f7f9fb}#global,#results{max-width:1200px}
|
||||||
|
|
||||||
|
/*! modern-normalize v1.0.0 | MIT License | https://github.com/sindresorhus/modern-normalize */:root{-moz-tab-size:4;tab-size:4}html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0;font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji}hr{height:0;color:inherit}abbr[title]{text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Consolas,Liberation Mono,Menlo,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}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,select{text-transform:none}[type=button],button{-webkit-appearance:button}legend{padding:0}progress{vertical-align:baseline}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}button{background-color:transparent;background-image:none}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}fieldset,ol,ul{margin:0;padding:0}ol,ul{list-style:none}html{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;line-height:1.5}body{font-family:inherit;line-height:inherit}*,:after,:before{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}hr{border-top-width:1px}img{border-style:solid}textarea{resize:vertical}input::placeholder,textarea::placeholder{color:#9ca3af}button{cursor:pointer}table{border-collapse:collapse}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}button,input,optgroup,select,textarea{padding:0;line-height:inherit;color:inherit}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1536px){.container{max-width:1536px}}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(1rem*var(--tw-space-x-reverse));margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgba(243,244,246,var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgba(229,231,235,var(--tw-bg-opacity))}.bg-red-100{--tw-bg-opacity:1;background-color:rgba(254,226,226,var(--tw-bg-opacity))}.bg-red-600{--tw-bg-opacity:1;background-color:rgba(220,38,38,var(--tw-bg-opacity))}.bg-green-100{--tw-bg-opacity:1;background-color:rgba(209,250,229,var(--tw-bg-opacity))}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgba(243,244,246,var(--tw-bg-opacity))}.hover\:bg-gray-200:hover{--tw-bg-opacity:1;background-color:rgba(229,231,235,var(--tw-bg-opacity))}.border-gray-300{--tw-border-opacity:1;border-color:rgba(209,213,219,var(--tw-border-opacity))}.border-gray-500{--tw-border-opacity:1;border-color:rgba(107,114,128,var(--tw-border-opacity))}.border-red-500{--tw-border-opacity:1;border-color:rgba(239,68,68,var(--tw-border-opacity))}.border-green-600{--tw-border-opacity:1;border-color:rgba(5,150,105,var(--tw-border-opacity))}.rounded-none{border-radius:0}.rounded{border-radius:.25rem}.rounded-xl{border-radius:.75rem}.rounded-full{border-radius:9999px}.border-dashed{border-style:dashed}.border{border-width:1px}.border-t{border-top-width:1px}.border-r{border-right-width:1px}.border-l{border-left-width:1px}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.table{display:table}.hidden{display:none}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.justify-end{justify-content:flex-end}.flex-1{flex:1 1 0%}.float-right{float:right}.font-light{font-weight:300}.font-medium{font-weight:500}.font-bold{font-weight:700}.text-sm{font-size:.875rem;line-height:1.25rem}.text-lg{font-size:1.125rem}.text-lg,.text-xl{line-height:1.75rem}.text-xl{font-size:1.25rem}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.my-4{margin-top:1rem;margin-bottom:1rem}.my-auto{margin-top:auto;margin-bottom:auto}.mx-auto{margin-left:auto;margin-right:auto}.mt-1{margin-top:.25rem}.mr-2{margin-right:.5rem}.mb-2{margin-bottom:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mb-4{margin-bottom:1rem}.mt-6{margin-top:1.5rem}.mt-12{margin-top:3rem}.object-scale-down{object-fit:scale-down}.opacity-75{opacity:.75}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.p-3{padding:.75rem}.p-5{padding:1.25rem}.py-0{padding-top:0;paddiLine truncated
|
||||||
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 51 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="/favicon.ico"><title>Health Dashboard | Gatus</title><link href="/css/app.css" rel="preload" as="style"><link href="/js/app.js" rel="preload" as="script"><link href="/js/chunk-vendors.js" rel="preload" as="script"><link href="/css/app.css" rel="stylesheet"></head><body><noscript><strong>Enable JavaScript to view this page.</strong></noscript><div id="app"></div><script src="/js/chunk-vendors.js"></script><script src="/js/app.js"></script></body></html>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
(function(e){function t(t){for(var s,c,o=t[0],a=t[1],l=t[2],h=0,d=[];h<o.length;h++)c=o[h],Object.prototype.hasOwnProperty.call(r,c)&&r[c]&&d.push(r[c][0]),r[c]=0;for(s in a)Object.prototype.hasOwnProperty.call(a,s)&&(e[s]=a[s]);u&&u(t);while(d.length)d.shift()();return i.push.apply(i,l||[]),n()}function n(){for(var e,t=0;t<i.length;t++){for(var n=i[t],s=!0,o=1;o<n.length;o++){var a=n[o];0!==r[a]&&(s=!1)}s&&(i.splice(t--,1),e=c(c.s=n[0]))}return e}var s={},r={app:0},i=[];function c(t){if(s[t])return s[t].exports;var n=s[t]={i:t,l:!1,exports:{}};return e[t].call(n.exports,n,n.exports,c),n.l=!0,n.exports}c.m=e,c.c=s,c.d=function(e,t,n){c.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},c.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.t=function(e,t){if(1&t&&(e=c(e)),8&t)return e;if(4&t&&"object"===typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(c.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)c.d(n,s,function(t){return e[t]}.bind(null,s));return n},c.n=function(e){var t=e&&e.__esModule?function(){return e["default"]}:function(){return e};return c.d(t,"a",t),t},c.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},c.p="/";var o=window["webpackJsonp"]=window["webpackJsonp"]||[],a=o.push.bind(o);o.push=t,o=o.slice();for(var l=0;l<o.length;l++)t(o[l]);var u=a;i.push([0,"chunk-vendors"]),n()})({0:function(e,t,n){e.exports=n("56d7")},"1cb3":function(e,t,n){"use strict";n("e007")},"1dd9":function(e,t,n){"use strict";n("ae5b")},"22c8":function(e,t,n){},"359c":function(e,t,n){e.exports=n.p+"img/github.png"},"3d28":function(e,t,n){"use strict";n("afea")},"3f93":function(e,t,n){},"49d2":function(e,t,n){"use strict";n("bca1")},"508b":function(e,t,n){"use strict";n("22c8")},"56d7":function(e,t,n){"use strict";n.r(t),n.d(t,"SERVER_URL",(function(){return it}));n("e260"),n("e6cf"),n("cca6"),n("a79d");var s=n("7a23"),r=n("cf05"),i=n.n(r),c={class:"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",id:"global"},o=Object(s["h"])("div",{class:"mb-2"},[Object(s["h"])("div",{class:"flex flex-wrap"},[Object(s["h"])("div",{class:"w-3/4 text-left my-auto"},[Object(s["h"])("div",{class:"text-3xl xl:text-5xl lg:text-4xl font-light"},"Health Status")]),Object(s["h"])("div",{class:"w-1/4 flex justify-end"},[Object(s["h"])("img",{src:i.a,alt:"Gatus",class:"object-scale-down",style:{"max-width":"100px","min-width":"50px","min-height":"50px"}})])])],-1);function a(e,t,n,r,i,a){var l=Object(s["y"])("router-view"),u=Object(s["y"])("Tooltip"),h=Object(s["y"])("Social");return Object(s["q"])(),Object(s["d"])(s["a"],null,[Object(s["h"])("div",c,[o,Object(s["h"])(l,{onShowTooltip:a.showTooltip},null,8,["onShowTooltip"])]),Object(s["h"])(u,{result:i.tooltip.result,event:i.tooltip.event},null,8,["result","event"]),Object(s["h"])(h)],64)}var l=n("359c"),u=n.n(l),h=Object(s["E"])("data-v-1cbbc992");Object(s["t"])("data-v-1cbbc992");var d={id:"social"},f=Object(s["h"])("a",{href:"https://github.com/TwinProduction/gatus",target:"_blank",title:"Gatus on GitHub"},[Object(s["h"])("img",{src:u.a,alt:"GitHub",width:"32",height:"auto"})],-1);Object(s["r"])();var A=h((function(e,t,n,r,i,c){return Object(s["q"])(),Object(s["d"])("div",d,[f])})),b={name:"Social"};n("508b");b.render=A,b.__scopeId="data-v-1cbbc992";var p=b,v=(n("b680"),Object(s["h"])("div",{class:"tooltip-title"},"Timestamp:",-1)),g={id:"tooltip-timestamp"},O=Object(s["h"])("div",{class:"tooltip-title"},"Response time:",-1),m={id:"tooltip-response-time"},j=Object(s["h"])("div",{class:"tooltip-title"},"Conditions:",-1),x={id:"tooltip-conditions"},y=Object(s["h"])("br",null,null,-1),w={key:0,id:"tooltip-errors-container"},I=Object(s["h"])("div",{class:"tooltip-title"},"Errors:",-1),T={id:"tooltip-errors"},B=Object(s["h"])("br",null,null,-1);function S(e,t,n,r,i,c){return Object(s["q"])(),Object(s["d"])("div",{id:"tooltip",ref:"tooltip",class:i.hidden?"invisible":"",style:"top:"+i.top+"px; left:"+i.left+"px"},[n.result?Object(s["x"])(e.$slots,"default",{key:0},(function(){return[v,Object(s["h"])("code",g,Object(s["A"])(c.prettifyTimestamp(n.result.timestamp)),1),O,Object(s["h"])("code",m,Object(s["A"])((n.result.duration/1e6).toFixed(0))+"ms",1),j,Object(s["h"])("code",x,[(Object(s["q"])(!0),Object(s["d"])(s["a"],null,Object(s["w"])(n.result.conditionResults,(function(t){return Object(s["x"])(e.$slots,"default",{key:t},(function(){return[Object(s["g"])(Object(s["A"])(t.success?"✓":"X")+" ~ "+Object(s["A"])(t.condition),1),y]}))})),128))]),n.result.errors&&n.result.errors.length?(Object(s["q"])(),Object(s["d"])("div",w,[I,Object(s["h"])("code",T,[(Object(s["q"])(!0),Object(s["d"])(s["a"],null,Object(s["w"])(n.result.errors,(function(t){return Object(s["x"])(e.$slots,"default",{key:t},(function(){return[Object(s["g"])(Line truncated
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-vendors"],{"00ee":function(e,t,n){var r=n("b622"),o=r("toStringTag"),c={};c[o]="z",e.exports="[object z]"===String(c)},"0366":function(e,t,n){var r=n("1c0b");e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 0:return function(){return e.call(t)};case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},"06cf":function(e,t,n){var r=n("83ab"),o=n("d1e7"),c=n("5c6c"),i=n("fc6a"),s=n("c04e"),a=n("5135"),u=n("0cfb"),l=Object.getOwnPropertyDescriptor;t.f=r?l:function(e,t){if(e=i(e),t=s(t,!0),u)try{return l(e,t)}catch(n){}if(a(e,t))return c(!o.f.call(e,t),e[t])}},"0cb2":function(e,t,n){var r=n("7b0b"),o=Math.floor,c="".replace,i=/\$([$&'`]|\d\d?|<[^>]*>)/g,s=/\$([$&'`]|\d\d?)/g;e.exports=function(e,t,n,a,u,l){var f=n+e.length,p=a.length,d=s;return void 0!==u&&(u=r(u),d=i),c.call(l,d,(function(r,c){var i;switch(c.charAt(0)){case"$":return"$";case"&":return e;case"`":return t.slice(0,n);case"'":return t.slice(f);case"<":i=u[c.slice(1,-1)];break;default:var s=+c;if(0===s)return r;if(s>p){var l=o(s/10);return 0===l?r:l<=p?void 0===a[l-1]?c.charAt(1):a[l-1]+c.charAt(1):r}i=a[s-1]}return void 0===i?"":i}))}},"0cfb":function(e,t,n){var r=n("83ab"),o=n("d039"),c=n("cc12");e.exports=!r&&!o((function(){return 7!=Object.defineProperty(c("div"),"a",{get:function(){return 7}}).a}))},1148:function(e,t,n){"use strict";var r=n("a691"),o=n("1d80");e.exports="".repeat||function(e){var t=String(o(this)),n="",c=r(e);if(c<0||c==1/0)throw RangeError("Wrong number of repetitions");for(;c>0;(c>>>=1)&&(t+=t))1&c&&(n+=t);return n}},"14c3":function(e,t,n){var r=n("c6b6"),o=n("9263");e.exports=function(e,t){var n=e.exec;if("function"===typeof n){var c=n.call(e,t);if("object"!==typeof c)throw TypeError("RegExp exec method returned something other than an Object or null");return c}if("RegExp"!==r(e))throw TypeError("RegExp#exec called on incompatible receiver");return o.call(e,t)}},"19aa":function(e,t){e.exports=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e}},"1be4":function(e,t,n){var r=n("d066");e.exports=r("document","documentElement")},"1c0b":function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},"1c7e":function(e,t,n){var r=n("b622"),o=r("iterator"),c=!1;try{var i=0,s={next:function(){return{done:!!i++}},return:function(){c=!0}};s[o]=function(){return this},Array.from(s,(function(){throw 2}))}catch(a){}e.exports=function(e,t){if(!t&&!c)return!1;var n=!1;try{var r={};r[o]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(a){}return n}},"1cdc":function(e,t,n){var r=n("342f");e.exports=/(iphone|ipod|ipad).*applewebkit/i.test(r)},"1d80":function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},"1dde":function(e,t,n){var r=n("d039"),o=n("b622"),c=n("2d00"),i=o("species");e.exports=function(e){return c>=51||!r((function(){var t=[],n=t.constructor={};return n[i]=function(){return{foo:1}},1!==t[e](Boolean).foo}))}},2266:function(e,t,n){var r=n("825a"),o=n("e95a"),c=n("50c4"),i=n("0366"),s=n("35a1"),a=n("2a62"),u=function(e,t){this.stopped=e,this.result=t};e.exports=function(e,t,n){var l,f,p,d,h,v,b,g=n&&n.that,m=!(!n||!n.AS_ENTRIES),y=!(!n||!n.IS_ITERATOR),O=!(!n||!n.INTERRUPTED),j=i(t,g,1+m+O),x=function(e){return l&&a(l),new u(!0,e)},w=function(e){return m?(r(e),O?j(e[0],e[1],x):j(e[0],e[1])):O?j(e,x):j(e)};if(y)l=e;else{if(f=s(e),"function"!=typeof f)throw TypeError("Target is not iterable");if(o(f)){for(p=0,d=c(e.length);d>p;p++)if(h=w(e[p]),h&&h instanceof u)return h;return new u(!1)}l=f.call(e)}v=l.next;while(!(b=v.call(l)).done){try{h=w(b.value)}catch(_){throw a(l),_}if("object"==typeof h&&h&&h instanceof u)return h}return new u(!1)}},"23cb":function(e,t,n){var r=n("a691"),o=Math.max,c=Math.min;e.exports=function(e,t){var n=r(e);return n<0?o(n+t,0):c(n,t)}},"23e7":function(e,t,n){var r=n("da84"),o=n("06cf").f,c=n("9112"),i=n("6eeb"),s=n("ce4e"),a=n("e893"),u=n("94ca");e.exports=function(e,t){var n,l,f,p,d,h,v=e.target,b=e.global,g=e.stat;if(l=b?r:g?r[v]||s(v,{}):(r[v]||{}).prototype,l)for(f in t){if(d=t[f],e.noTargetGet?(h=o(l,f),p=h&&h.value):p=l[f],n=u(b?f:v+(g?".":"#")+f,e.forced),!n&&void 0!==p){if(typeof d===typeof p)continue;a(d,p)}(e.sham||p&&p.sham)&&c(d,"sham",!0),i(l,f,d,e)}}},"241c":function(e,t,n){var r=n("ca84"),o=n("7839"),c=o.concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,c)}},2626:function(e,t,n){"use strict";var r=n("d066"),o=n("9bf2"),c=n("b622"),i=n("83ab"),s=c("species");e.exports=function(e){var t=r(e),n=o.f;i&&t&&!t[s]&&n(t,s,{configurable:!0,get:function(){return this}})}},"2a62":function(e,t,n){var r=n("825a");e.exports=function(e){var t=e["return"];if(void 0!==t)return r(t.call(Line truncated
|
||||||
|
/*!
|
||||||
|
* vue-router v4.0.3
|
||||||
|
* (c) 2021 Eduardo San Martin Morote
|
||||||
|
* @license MIT
|
||||||
|
*/const o="function"===typeof Symbol&&"symbol"===typeof Symbol.toStringTag,c=e=>o?Symbol(e):"_vr_"+e,i=c("rvlm"),s=c("rvd"),a=c("r"),u=c("rl"),l=c("rvl"),f="undefined"!==typeof window;function p(e){return e.__esModule||o&&"Module"===e[Symbol.toStringTag]}const d=Object.assign;function h(e,t){const n={};for(const r in t){const o=t[r];n[r]=Array.isArray(o)?o.map(e):e(o)}return n}let v=()=>{};const b=/\/$/,g=e=>e.replace(b,"");function m(e,t,n="/"){let r,o={},c="",i="";const s=t.indexOf("?"),a=t.indexOf("#",s>-1?s:0);return s>-1&&(r=t.slice(0,s),c=t.slice(s+1,a>-1?a:t.length),o=e(c)),a>-1&&(r=r||t.slice(0,a),i=t.slice(a,t.length)),r=S(null!=r?r:t,n),{fullPath:r+(c&&"?")+c+i,path:r,query:o,hash:i}}function y(e,t){let n=t.query?e(t.query):"";return t.path+(n&&"?")+n+(t.hash||"")}function O(e,t){return!t||e.toLowerCase().indexOf(t.toLowerCase())?e:e.slice(t.length)||"/"}function j(e,t,n){let r=t.matched.length-1,o=n.matched.length-1;return r>-1&&r===o&&x(t.matched[r],n.matched[o])&&w(t.params,n.params)&&e(t.query)===e(n.query)&&t.hash===n.hash}function x(e,t){return(e.aliasOf||e)===(t.aliasOf||t)}function w(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(!_(e[n],t[n]))return!1;return!0}function _(e,t){return Array.isArray(e)?E(e,t):Array.isArray(t)?E(t,e):e===t}function E(e,t){return Array.isArray(t)?e.length===t.length&&e.every((e,n)=>e===t[n]):1===e.length&&e[0]===t}function S(e,t){if(e.startsWith("/"))return e;if(!e)return t;const n=t.split("/"),r=e.split("/");let o,c,i=n.length-1;for(o=0;o<r.length;o++)if(c=r[o],1!==i&&"."!==c){if(".."!==c)break;i--}return n.slice(0,i).join("/")+"/"+r.slice(o-(o===r.length?1:0)).join("/")}var k,C;(function(e){e["pop"]="pop",e["push"]="push"})(k||(k={})),function(e){e["back"]="back",e["forward"]="forward",e["unknown"]=""}(C||(C={}));function A(e){if(!e)if(f){const t=document.querySelector("base");e=t&&t.getAttribute("href")||"/",e=e.replace(/^\w+:\/\/[^\/]+/,"")}else e="/";return"/"!==e[0]&&"#"!==e[0]&&(e="/"+e),g(e)}const R=/^[^#]+#/;function P(e,t){return e.replace(R,"#")+t}function T(e,t){const n=document.documentElement.getBoundingClientRect(),r=e.getBoundingClientRect();return{behavior:t.behavior,left:r.left-n.left-(t.left||0),top:r.top-n.top-(t.top||0)}}const F=()=>({left:window.pageXOffset,top:window.pageYOffset});function I(e){let t;if("el"in e){let n=e.el;const 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;t=T(o,e)}else t=e;"scrollBehavior"in document.documentElement.style?window.scrollTo(t):window.scrollTo(null!=t.left?t.left:window.pageXOffset,null!=t.top?t.top:window.pageYOffset)}function M(e,t){const n=history.state?history.state.position-t:-1;return n+e}const N=new Map;function L(e,t){N.set(e,t)}function B(e){const t=N.get(e);return N.delete(e),t}let $=()=>location.protocol+"//"+location.host;function U(e,t){const{pathname:n,search:r,hash:o}=t,c=e.indexOf("#");if(c>-1){let e=o.slice(1);return"/"!==e[0]&&(e="/"+e),O(e,"")}const i=O(n,e);return i+r+o}function D(e,t,n,r){let o=[],c=[],i=null;const s=({state:c})=>{const s=U(e,location),a=n.value,u=t.value;let l=0;if(c){if(n.value=s,t.value=c,i&&i===a)return void(i=null);l=u?c.position-u.position:0}else r(s);o.forEach(e=>{e(n.value,a,{delta:l,type:k.pop,direction:l?l>0?C.forward:C.back:C.unknown})})};function a(){i=n.value}function u(e){o.push(e);const t=()=>{const t=o.indexOf(e);t>-1&&o.splice(t,1)};return c.push(t),t}function l(){const{history:e}=window;e.state&&e.replaceState(d({},e.state,{scroll:F()}),"")}function f(){for(const e of c)e();c=[],window.removeEventListener("popstate",s),window.removeEventListener("beforeunload",l)}return window.addEventListener("popstate",s),window.addEventListener("beforeunload",l),{pauseListeners:a,listen:u,destroy:f}}function V(e,t,n,r=!1,o=!1){return{back:e,current:t,forward:n,replaced:r,position:window.history.length,scroll:o?F():null}}function q(e){const{history:t,location:n}=window;let r={value:U(e,n)},o={value:t.state};function c(r,c,i){const s=e.indexOf("#"),a=s>-1?(n.host&&document.querySelector("base")?e:e.slice(s))+r:$()+e+r;try{t[i?"replaceState":"pushState"](c,"",a),o.value=c}catch(u){console.error(u),n[i?"replace":"assign"](a)}}function i(e,n){const i=d({},t.state,V(o.value.back,e,o.value.forward,!0),n,{position:o.value.position});c(e,i,!0),r.value=e}function s(e,n){const i=d({},o.value,t.state,{forward:e,scroll:F()});c(i.current,i,!0);const s=d({},V(r.value,e,null),{position:i.position+1},n);c(e,s,!1),r.value=e}return o.value||c(r.value,{back:null,current:r.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0),{location:r,state:o,push:s,replace:i}}function G(e){e=A(e);const t=q(e),n=D(e,t.state,t.location,t.replace);function r(e,t=!0){t||n.pauseListeners(),history.go(e)}const o=d({location:"",base:e,go:r,createHref:P.bind(null,e)},t,n);return Object.defineProperty(o,"location",{get:()=>t.location.value}),Object.definLine truncated
|
||||||