feat: add status probe
This commit is contained in:
3
vendor/github.com/hellofresh/health-go/v4/.gitignore
generated
vendored
Normal file
3
vendor/github.com/hellofresh/health-go/v4/.gitignore
generated
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
vendor/
|
||||
coverage.txt
|
||||
.idea/
|
15
vendor/github.com/hellofresh/health-go/v4/.golangci.yml
generated
vendored
Normal file
15
vendor/github.com/hellofresh/health-go/v4/.golangci.yml
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
# See https://golangci-lint.run/usage/configuration/#config-file for more information
|
||||
run:
|
||||
timeout: 5m
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- gofmt
|
||||
- golint
|
||||
- goimports
|
||||
fast: false
|
||||
linters-settings:
|
||||
gofmt:
|
||||
simplify: false
|
||||
issues:
|
||||
exclude-use-default: false
|
13
vendor/github.com/hellofresh/health-go/v4/.whitesource
generated
vendored
Normal file
13
vendor/github.com/hellofresh/health-go/v4/.whitesource
generated
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"scanSettings": {
|
||||
"configMode": "AUTO",
|
||||
"configExternalURL": "",
|
||||
"projectToken" : ""
|
||||
},
|
||||
"checkRunSettings": {
|
||||
"vulnerableCheckRunConclusionLevel": "success"
|
||||
},
|
||||
"issueSettings": {
|
||||
"minSeverityLevel": "NONE"
|
||||
}
|
||||
}
|
201
vendor/github.com/hellofresh/health-go/v4/LICENSE.txt
generated
vendored
Normal file
201
vendor/github.com/hellofresh/health-go/v4/LICENSE.txt
generated
vendored
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2020 HelloFresh SE
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
23
vendor/github.com/hellofresh/health-go/v4/Makefile
generated
vendored
Normal file
23
vendor/github.com/hellofresh/health-go/v4/Makefile
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
OK_COLOR=\033[32;01m
|
||||
NO_COLOR=\033[0m
|
||||
|
||||
test:
|
||||
@echo "$(OK_COLOR)==> Running tests against container deps$(NO_COLOR)"
|
||||
@docker-compose up -d
|
||||
@sleep 3 && \
|
||||
HEALTH_GO_PG_PQ_DSN="postgres://test:test@`docker-compose port pg-pq 5432`/test?sslmode=disable" \
|
||||
HEALTH_GO_PG_PGX4_DSN="postgres://test:test@`docker-compose port pg-pgx4 5432`/test?sslmode=disable" \
|
||||
HEALTH_GO_MQ_DSN="amqp://guest:guest@`docker-compose port rabbit 5672`/" \
|
||||
HEALTH_GO_MQ_URL="http://guest:guest@`docker-compose port rabbit 15672`/" \
|
||||
HEALTH_GO_RD_DSN="redis://`docker-compose port redis 6379`/" \
|
||||
HEALTH_GO_MG_DSN="mongodb://`docker-compose port mongo 27017`/" \
|
||||
HEALTH_GO_MS_DSN="test:test@tcp(`docker-compose port mysql 3306`)/test?charset=utf8" \
|
||||
HEALTH_GO_HTTP_URL="http://`docker-compose port http 8080`/status" \
|
||||
HEALTH_GO_MD_DSN="memcached://localhost:${{ job.services.memcached.ports[11211] }}/" \
|
||||
go test -cover ./... -coverprofile=coverage.txt -covermode=atomic
|
||||
|
||||
lint:
|
||||
@echo "$(OK_COLOR)==> Linting with golangci-lint$(NO_COLOR)"
|
||||
@docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:v1.33.0 golangci-lint run -v
|
||||
|
||||
.PHONY: test lint
|
192
vendor/github.com/hellofresh/health-go/v4/README.md
generated
vendored
Normal file
192
vendor/github.com/hellofresh/health-go/v4/README.md
generated
vendored
Normal file
@ -0,0 +1,192 @@
|
||||
# health-go
|
||||
[](https://goreportcard.com/report/github.com/hellofresh/health-go)
|
||||
[](https://godoc.org/github.com/hellofresh/health-go)
|
||||
|
||||
* Exposes an HTTP handler that retrieves health status of the application
|
||||
* Implements some generic checkers for the following services:
|
||||
* RabbitMQ
|
||||
* PostgreSQL
|
||||
* Redis
|
||||
* HTTP
|
||||
* MongoDB
|
||||
* MySQL
|
||||
* gRPC
|
||||
* Memcached
|
||||
|
||||
## Usage
|
||||
|
||||
The library exports `Handler` and `HandlerFunc` functions which are fully compatible with `net/http`.
|
||||
|
||||
Additionally, library exports `Measure` function that returns summary status for all the registered health checks,
|
||||
so it can be used in non-HTTP environments.
|
||||
|
||||
### Handler
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/hellofresh/health-go/v4"
|
||||
healthMysql "github.com/hellofresh/health-go/v4/checks/mysql"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// add some checks on instance creation
|
||||
h, _ := health.New(health.WithChecks(health.Config{
|
||||
Name: "rabbitmq",
|
||||
Timeout: time.Second * 5,
|
||||
SkipOnErr: true,
|
||||
Check: func(ctx context.Context) error {
|
||||
// rabbitmq health check implementation goes here
|
||||
return nil
|
||||
}}, health.Config{
|
||||
Name: "mongodb",
|
||||
Check: func(ctx context.Context) error {
|
||||
// mongo_db health check implementation goes here
|
||||
return nil
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
// and then add some more if needed
|
||||
h.Register(health.Config{
|
||||
Name: "mysql",
|
||||
Timeout: time.Second * 2,
|
||||
SkipOnErr: false,
|
||||
Check: healthMysql.New(healthMysql.Config{
|
||||
DSN: "test:test@tcp(0.0.0.0:31726)/test?charset=utf8",
|
||||
}),
|
||||
})
|
||||
|
||||
http.Handle("/status", h.Handler())
|
||||
http.ListenAndServe(":3000", nil)
|
||||
}
|
||||
```
|
||||
|
||||
### HandlerFunc
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/hellofresh/health-go/v4"
|
||||
healthMysql "github.com/hellofresh/health-go/v4/checks/mysql"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// add some checks on instance creation
|
||||
h, _ := health.New(health.WithChecks(health.Config{
|
||||
Name: "rabbitmq",
|
||||
Timeout: time.Second * 5,
|
||||
SkipOnErr: true,
|
||||
Check: func(ctx context.Context) error {
|
||||
// rabbitmq health check implementation goes here
|
||||
return nil
|
||||
}}, health.Config{
|
||||
Name: "mongodb",
|
||||
Check: func(ctx context.Context) error {
|
||||
// mongo_db health check implementation goes here
|
||||
return nil
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
// and then add some more if needed
|
||||
h.Register(health.Config{
|
||||
Name: "mysql",
|
||||
Timeout: time.Second * 2,
|
||||
SkipOnErr: false,
|
||||
Check: healthMysql.New(healthMysql.Config{
|
||||
DSN: "test:test@tcp(0.0.0.0:31726)/test?charset=utf8",
|
||||
}),
|
||||
})
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Get("/status", h.HandlerFunc)
|
||||
http.ListenAndServe(":3000", nil)
|
||||
}
|
||||
```
|
||||
|
||||
For more examples please check [here](https://github.com/hellofresh/health-go/blob/master/_examples/server.go)
|
||||
## API Documentation
|
||||
|
||||
### `GET /status`
|
||||
|
||||
Get the health of the application.
|
||||
- Method: `GET`
|
||||
- Endpoint: `/status`
|
||||
- Request:
|
||||
```
|
||||
curl localhost:3000/status
|
||||
```
|
||||
- Response:
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
```json
|
||||
{
|
||||
"status": "OK",
|
||||
"timestamp": "2017-01-01T00:00:00.413567856+033:00",
|
||||
"system": {
|
||||
"version": "go1.8",
|
||||
"goroutines_count": 4,
|
||||
"total_alloc_bytes": 21321,
|
||||
"heap_objects_count": 21323,
|
||||
"alloc_bytes": 234523
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
```json
|
||||
{
|
||||
"status": "Partially Available",
|
||||
"timestamp": "2017-01-01T00:00:00.413567856+033:00",
|
||||
"failures": {
|
||||
"rabbitmq": "Failed during rabbitmq health check"
|
||||
},
|
||||
"system": {
|
||||
"version": "go1.8",
|
||||
"goroutines_count": 4,
|
||||
"total_alloc_bytes": 21321,
|
||||
"heap_objects_count": 21323,
|
||||
"alloc_bytes": 234523
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
HTTP/1.1 503 Service Unavailable
|
||||
```json
|
||||
{
|
||||
"status": "Unavailable",
|
||||
"timestamp": "2017-01-01T00:00:00.413567856+033:00",
|
||||
"failures": {
|
||||
"mongodb": "Failed during mongodb health check"
|
||||
},
|
||||
"system": {
|
||||
"version": "go1.8",
|
||||
"goroutines_count": 4,
|
||||
"total_alloc_bytes": 21321,
|
||||
"heap_objects_count": 21323,
|
||||
"alloc_bytes": 234523
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Contributing
|
||||
- Fork it
|
||||
- Create your feature branch (`git checkout -b my-new-feature`)
|
||||
- Commit your changes (`git commit -am 'Add some feature'`)
|
||||
- Push to the branch (`git push origin my-new-feature`)
|
||||
- Create new Pull Request
|
||||
|
||||
---
|
||||
> GitHub [@hellofresh](https://github.com/hellofresh) ·
|
||||
> Medium [@engineering.hellofresh](https://engineering.hellofresh.com)
|
88
vendor/github.com/hellofresh/health-go/v4/docker-compose.yml
generated
vendored
Normal file
88
vendor/github.com/hellofresh/health-go/v4/docker-compose.yml
generated
vendored
Normal file
@ -0,0 +1,88 @@
|
||||
version: '3'
|
||||
services:
|
||||
|
||||
pg-pq:
|
||||
image: postgres:9.6-alpine
|
||||
ports:
|
||||
- "5432"
|
||||
environment:
|
||||
POSTGRES_USER: test
|
||||
POSTGRES_PASSWORD: test
|
||||
POSTGRES_DB: test
|
||||
healthcheck:
|
||||
test: [ "CMD", "pg_isready" ]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
pg-pgx4:
|
||||
image: postgres:9.6-alpine
|
||||
ports:
|
||||
- "5432"
|
||||
environment:
|
||||
POSTGRES_USER: test
|
||||
POSTGRES_PASSWORD: test
|
||||
POSTGRES_DB: test
|
||||
healthcheck:
|
||||
test: [ "CMD", "pg_isready" ]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
rabbit:
|
||||
image: rabbitmq:3.6-management-alpine
|
||||
ports:
|
||||
- "5672"
|
||||
- "15672"
|
||||
healthcheck:
|
||||
test: [ "CMD", "rabbitmqctl", "status" ]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
redis:
|
||||
image: redis:3.2-alpine
|
||||
ports:
|
||||
- "6379"
|
||||
healthcheck:
|
||||
test: [ "CMD", "redis-cli", "ping" ]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
mongo:
|
||||
image: mongo:3
|
||||
ports:
|
||||
- "27017"
|
||||
healthcheck:
|
||||
test: "mongo localhost:27017/test --quiet --eval 'quit(db.runCommand({ ping: 1 }).ok ? 0 : 2)'"
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
mysql:
|
||||
image: mysql:5.7
|
||||
ports:
|
||||
- "3306"
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: test
|
||||
MYSQL_DATABASE: test
|
||||
MYSQL_USER: test
|
||||
MYSQL_PASSWORD: test
|
||||
healthcheck:
|
||||
test: [ "CMD", "mysqladmin", "ping", "-h", "localhost" ]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
memcached:
|
||||
image: memcached:1.6.9-alpine
|
||||
ports:
|
||||
- "11211"
|
||||
|
||||
http:
|
||||
image: pierreprinetti/apimock:latest
|
||||
ports:
|
||||
- "8080"
|
||||
environment:
|
||||
HOST: ":8080"
|
262
vendor/github.com/hellofresh/health-go/v4/health.go
generated
vendored
Normal file
262
vendor/github.com/hellofresh/health-go/v4/health.go
generated
vendored
Normal file
@ -0,0 +1,262 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Status type represents health status
|
||||
type Status string
|
||||
|
||||
// Possible health statuses
|
||||
const (
|
||||
StatusOK Status = "OK"
|
||||
StatusPartiallyAvailable Status = "Partially Available"
|
||||
StatusUnavailable Status = "Unavailable"
|
||||
StatusTimeout Status = "Timeout during health check"
|
||||
)
|
||||
|
||||
type (
|
||||
// CheckFunc is the func which executes the check.
|
||||
CheckFunc func(context.Context) error
|
||||
|
||||
// Config carries the parameters to run the check.
|
||||
Config struct {
|
||||
// Name is the name of the resource to be checked.
|
||||
Name string
|
||||
// Timeout is the timeout defined for every check.
|
||||
Timeout time.Duration
|
||||
// SkipOnErr if set to true, it will retrieve StatusOK providing the error message from the failed resource.
|
||||
SkipOnErr bool
|
||||
// Check is the func which executes the check.
|
||||
Check CheckFunc
|
||||
}
|
||||
|
||||
// Check represents the health check response.
|
||||
Check struct {
|
||||
// Status is the check status.
|
||||
Status Status `json:"status"`
|
||||
// Timestamp is the time in which the check occurred.
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
// Failures holds the failed checks along with their messages.
|
||||
Failures map[string]string `json:"failures,omitempty"`
|
||||
// System holds information of the go process.
|
||||
System `json:"system"`
|
||||
}
|
||||
|
||||
// System runtime variables about the go process.
|
||||
System struct {
|
||||
// Version is the go version.
|
||||
Version string `json:"version"`
|
||||
// GoroutinesCount is the number of the current goroutines.
|
||||
GoroutinesCount int `json:"goroutines_count"`
|
||||
// TotalAllocBytes is the total bytes allocated.
|
||||
TotalAllocBytes int `json:"total_alloc_bytes"`
|
||||
// HeapObjectsCount is the number of objects in the go heap.
|
||||
HeapObjectsCount int `json:"heap_objects_count"`
|
||||
// TotalAllocBytes is the bytes allocated and not yet freed.
|
||||
AllocBytes int `json:"alloc_bytes"`
|
||||
}
|
||||
|
||||
// Health is the health-checks container
|
||||
Health struct {
|
||||
mu sync.Mutex
|
||||
checks map[string]Config
|
||||
|
||||
tp trace.TracerProvider
|
||||
instrumentationName string
|
||||
}
|
||||
|
||||
checkResponse struct {
|
||||
name string
|
||||
skipOnErr bool
|
||||
err error
|
||||
}
|
||||
)
|
||||
|
||||
// New instantiates and build new health check container
|
||||
func New(opts ...Option) (*Health, error) {
|
||||
h := &Health{
|
||||
checks: make(map[string]Config),
|
||||
tp: trace.NewNoopTracerProvider(),
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
if err := o(h); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// Register registers a check config to be performed.
|
||||
func (h *Health) Register(c Config) error {
|
||||
if c.Timeout == 0 {
|
||||
c.Timeout = time.Second * 2
|
||||
}
|
||||
|
||||
if c.Name == "" {
|
||||
return errors.New("health check must have a name to be registered")
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
if _, ok := h.checks[c.Name]; ok {
|
||||
return fmt.Errorf("health check %q is already registered", c.Name)
|
||||
}
|
||||
|
||||
h.checks[c.Name] = c
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Handler returns an HTTP handler (http.HandlerFunc).
|
||||
func (h *Health) Handler() http.Handler {
|
||||
return http.HandlerFunc(h.HandlerFunc)
|
||||
}
|
||||
|
||||
// HandlerFunc is the HTTP handler function.
|
||||
func (h *Health) HandlerFunc(w http.ResponseWriter, r *http.Request) {
|
||||
c := h.Measure(r.Context())
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
data, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
code := http.StatusOK
|
||||
if c.Status == StatusUnavailable {
|
||||
code = http.StatusServiceUnavailable
|
||||
}
|
||||
w.WriteHeader(code)
|
||||
w.Write(data)
|
||||
}
|
||||
|
||||
type checkSpan struct {
|
||||
ctx context.Context
|
||||
span trace.Span
|
||||
}
|
||||
|
||||
func newCheckSpan(ctx context.Context, tracer trace.Tracer, name string) checkSpan {
|
||||
var cs checkSpan
|
||||
cs.ctx, cs.span = tracer.Start(ctx, name)
|
||||
return cs
|
||||
}
|
||||
|
||||
// Measure runs all the registered health checks and returns summary status
|
||||
func (h *Health) Measure(ctx context.Context) Check {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
tracer := h.tp.Tracer(h.instrumentationName)
|
||||
|
||||
ctx, span := tracer.Start(ctx, "health.Measure")
|
||||
defer span.End()
|
||||
|
||||
status := StatusOK
|
||||
total := len(h.checks)
|
||||
failures := make(map[string]string)
|
||||
resChan := make(chan checkResponse, total)
|
||||
checkSpans := make(map[string]checkSpan)
|
||||
|
||||
span.SetAttributes(attribute.Int("checks", total))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(total)
|
||||
|
||||
go func() {
|
||||
defer close(resChan)
|
||||
|
||||
wg.Wait()
|
||||
}()
|
||||
|
||||
for _, c := range h.checks {
|
||||
checkSpans[c.Name] = newCheckSpan(ctx, tracer, c.Name)
|
||||
|
||||
go func(c Config) {
|
||||
defer wg.Done()
|
||||
|
||||
select {
|
||||
case resChan <- checkResponse{c.Name, c.SkipOnErr, c.Check(ctx)}:
|
||||
default:
|
||||
}
|
||||
}(c)
|
||||
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case <-time.After(c.Timeout):
|
||||
failures[c.Name] = string(StatusTimeout)
|
||||
status = getAvailability(status, c.SkipOnErr)
|
||||
|
||||
cs := checkSpans[c.Name]
|
||||
cs.span.SetStatus(codes.Error, string(StatusTimeout))
|
||||
cs.span.End()
|
||||
|
||||
break loop
|
||||
case res := <-resChan:
|
||||
cs := checkSpans[res.name]
|
||||
|
||||
if res.err != nil {
|
||||
failures[res.name] = res.err.Error()
|
||||
status = getAvailability(status, res.skipOnErr)
|
||||
|
||||
cs.span.RecordError(res.err)
|
||||
}
|
||||
|
||||
cs.span.End()
|
||||
|
||||
break loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
span.SetAttributes(attribute.String("status", string(status)))
|
||||
|
||||
return newCheck(status, failures)
|
||||
}
|
||||
|
||||
func newCheck(s Status, failures map[string]string) Check {
|
||||
return Check{
|
||||
Status: s,
|
||||
Timestamp: time.Now(),
|
||||
Failures: failures,
|
||||
System: newSystemMetrics(),
|
||||
}
|
||||
}
|
||||
|
||||
func newSystemMetrics() System {
|
||||
s := runtime.MemStats{}
|
||||
runtime.ReadMemStats(&s)
|
||||
|
||||
return System{
|
||||
Version: runtime.Version(),
|
||||
GoroutinesCount: runtime.NumGoroutine(),
|
||||
TotalAllocBytes: int(s.TotalAlloc),
|
||||
HeapObjectsCount: int(s.HeapObjects),
|
||||
AllocBytes: int(s.Alloc),
|
||||
}
|
||||
}
|
||||
|
||||
func getAvailability(s Status, skipOnErr bool) Status {
|
||||
if skipOnErr && s != StatusUnavailable {
|
||||
return StatusPartiallyAvailable
|
||||
}
|
||||
|
||||
return StatusUnavailable
|
||||
}
|
34
vendor/github.com/hellofresh/health-go/v4/options.go
generated
vendored
Normal file
34
vendor/github.com/hellofresh/health-go/v4/options.go
generated
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Option is the health-container options type
|
||||
type Option func(*Health) error
|
||||
|
||||
// WithChecks adds checks to newly instantiated health-container
|
||||
func WithChecks(checks ...Config) Option {
|
||||
return func(h *Health) error {
|
||||
for _, c := range checks {
|
||||
if err := h.Register(c); err != nil {
|
||||
return fmt.Errorf("could not register check %q: %w", c.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithTracerProvider sets trace provider for the checks and instrumentation name that will be used
|
||||
// for tracer from trace provider.
|
||||
func WithTracerProvider(tp trace.TracerProvider, instrumentationName string) Option {
|
||||
return func(h *Health) error {
|
||||
h.tp = tp
|
||||
h.instrumentationName = instrumentationName
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user