Compare commits

..

11 Commits

Author SHA1 Message Date
Ian Fijolek
67c2375bba Remove docker linting for now
Drone check doesn't pass. Need to install docker there
2020-07-14 17:29:54 -07:00
Ian Fijolek
aad9eaa32f Update exported status metric to properly reflect alerting status of a monitor
It was using the result of the individual check and not the monitor as a whole
2020-07-14 17:09:56 -07:00
Ian Fijolek
5dc5ba5257 Add docker linting 2020-07-14 17:08:48 -07:00
Ian Fijolek
4aff294739 Set overrided version in drone config 2020-07-07 12:15:53 -07:00
Ian Fijolek
0684b15a44 Update logic for setting version
I noticed that versions were not being properly dervied from the git
tags. This fixes that in a simpler way by allowing git to describe the
current commit with tags, commits, shas, and a dirty maker.
2020-07-07 10:51:13 -07:00
Ian Fijolek
d3826dacde Update drone to use new linux only target 2020-07-06 20:33:02 -07:00
Ian Fijolek
f8e40c643c Move static binaries to dist/ for easier publishing
This will make it easier to publish them to Github or Gitea releases later.

To avoid making the Makefile super complex, this patch also makes use of
variables to simplify the Makefile as well.
2020-07-06 20:15:21 -07:00
Ian Fijolek
cffbbd734a Make default log alert conditional
Allow using the default `log` alert for both up and down alerts using
Go's templating conditionals. Following this example can do away with
the need for an up and down version of every alert.
2020-06-19 09:51:42 -07:00
Ian Fijolek
ad6f3be6ec Update README with more detailed running instructions from prior project 2020-02-19 22:13:30 -08:00
Ian Fijolek
ae30f477f7 Add ability to customize metrics port 2020-02-19 22:13:07 -08:00
Ian Fijolek
9dcd8ebf12 Update README to correct differences between py and go versions 2020-02-19 21:56:01 -08:00
11 changed files with 202 additions and 102 deletions
+5 -1
View File
@@ -6,6 +6,8 @@ steps:
- name: test - name: test
image: golang:1.12 image: golang:1.12
environment:
VERSION: ${DRONE_TAG:-${DRONE_COMMIT}}
commands: commands:
- make build - make build
- make test - make test
@@ -47,8 +49,10 @@ trigger:
steps: steps:
- name: build all binaries - name: build all binaries
image: golang:1.12 image: golang:1.12
environment:
VERSION: ${DRONE_TAG:-${DRONE_COMMIT}}
commands: commands:
- make all - make all-linux
- name: push image - arm - name: push image - arm
image: plugins/docker image: plugins/docker
Vendored
+1 -2
View File
@@ -17,5 +17,4 @@ config.yml
# Output binary # Output binary
minitor minitor
minitor-linux-* dist/
minitor-darwin-amd64
+5
View File
@@ -17,3 +17,8 @@ repos:
- id: go-imports - id: go-imports
# - id: gometalinter # - id: gometalinter
# - id: golangci-lint # - id: golangci-lint
# - repo: https://github.com/IamTheFij/docker-pre-commit
# rev: v2.0.0
# hooks:
# - id: docker-compose-check
# - id: hadolint
+1 -1
View File
@@ -20,7 +20,7 @@ RUN chmod -R 755 /app/scripts
# Copy minitor in # Copy minitor in
ARG ARCH=amd64 ARG ARCH=amd64
COPY ./minitor-linux-${ARCH} ./minitor COPY ./dist/minitor-linux-${ARCH} ./minitor
# Drop to non-root user # Drop to non-root user
USER minitor USER minitor
+33 -39
View File
@@ -1,36 +1,43 @@
DOCKER_TAG ?= minitor-go-${USER} DOCKER_TAG ?= minitor-go-${USER}
GIT_TAG_NAME := $(shell git tag -l --contains HEAD) VERSION ?= $(shell git describe --tags --dirty)
GIT_SHA := $(shell git rev-parse HEAD) GOFILES = *.go
VERSION := $(if $(GIT_TAG_NAME),$(GIT_TAG_NAME),$(GIT_SHA)) # Multi-arch targets are generated from this
TARGET_ALIAS = minitor-linux-amd64 minitor-linux-arm minitor-linux-arm64 minitor-darwin-amd64
TARGETS = $(addprefix dist/,$(TARGET_ALIAS))
#
# Default make target will run tests
.DEFAULT_GOAL = test
# Build all static Minitor binaries
.PHONY: all .PHONY: all
all: minitor-linux-amd64 minitor-linux-arm minitor-linux-arm64 all: $(TARGETS)
.PHONY: default # Build all static Linux Minitor binaries. Used in Docker images
default: test .PHONY: all-linux
all-linux: $(filter dist/minitor-linux-%,$(TARGETS))
# Build minitor for the current machine
minitor: $(GOFILES)
@echo Version: $(VERSION)
go build -ldflags '-X "main.version=${VERSION}"' -o minitor
.PHONY: build .PHONY: build
build: minitor build: minitor
minitor: # Run minitor for the current machine
@echo Version: $(VERSION)
go build -ldflags '-X "main.version=${VERSION}"' -o minitor
.PHONY: run .PHONY: run
run: minitor build run: minitor
./minitor -debug ./minitor -debug
.PHONY: run-metrics .PHONY: run-metrics
run-metrics: minitor build run-metrics: minitor
./minitor -debug -metrics ./minitor -debug -metrics
# Run all tests
.PHONY: test .PHONY: test
test: test:
go test -coverprofile=coverage.out go test -coverprofile=coverage.out
@echo
go tool cover -func=coverage.out go tool cover -func=coverage.out
@echo
@# Check min coverage percentage
@go tool cover -func=coverage.out | awk -v target=80.0% \ @go tool cover -func=coverage.out | awk -v target=80.0% \
'/^total:/ { print "Total coverage: " $$3 " Minimum coverage: " target; if ($$3+0.0 >= target+0.0) print "ok"; else { print "fail"; exit 1; } }' '/^total:/ { print "Total coverage: " $$3 " Minimum coverage: " target; if ($$3+0.0 >= target+0.0) print "ok"; else { print "fail"; exit 1; } }'
@@ -47,9 +54,8 @@ check:
.PHONY: clean .PHONY: clean
clean: clean:
rm -f ./minitor rm -f ./minitor
rm -f ./minitor-linux-*
rm -f ./minitor-darwin-amd64
rm -f ./coverage.out rm -f ./coverage.out
rm -fr ./dist
.PHONY: docker-build .PHONY: docker-build
docker-build: docker-build:
@@ -60,35 +66,23 @@ docker-run: docker-build
docker run --rm -v $(shell pwd)/config.yml:/root/config.yml $(DOCKER_TAG) docker run --rm -v $(shell pwd)/config.yml:/root/config.yml $(DOCKER_TAG)
## Multi-arch targets ## Multi-arch targets
$(TARGETS): $(GOFILES)
# Arch specific go build targets mkdir -p ./dist
minitor-darwin-amd64: GOOS=$(word 2, $(subst -, ,$(@))) GOARCH=$(word 3, $(subst -, ,$(@))) CGO_ENABLED=0 \
GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 \
go build -ldflags '-X "main.version=${VERSION}"' -a -installsuffix nocgo \ go build -ldflags '-X "main.version=${VERSION}"' -a -installsuffix nocgo \
-o minitor-darwin-amd64 -o $@
minitor-linux-amd64: .PHONY: $(TARGET_ALIAS)
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 \ $(TARGET_ALIAS):
go build -ldflags '-X "main.version=${VERSION}"' -a -installsuffix nocgo \ $(MAKE) $(addprefix dist/,$@)
-o minitor-linux-amd64
minitor-linux-arm:
GOOS=linux GOARCH=arm CGO_ENABLED=0 \
go build -ldflags '-X "main.version=${VERSION}"' -a -installsuffix nocgo \
-o minitor-linux-arm
minitor-linux-arm64:
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 \
go build -ldflags '-X "main.version=${VERSION}"' -a -installsuffix nocgo \
-o minitor-linux-arm64
# Arch specific docker build targets # Arch specific docker build targets
.PHONY: docker-build-arm .PHONY: docker-build-arm
docker-build-arm: minitor-linux-arm docker-build-arm: dist/minitor-linux-arm
docker build --build-arg REPO=arm32v7 --build-arg ARCH=arm . -t ${DOCKER_TAG}-linux-arm docker build --build-arg REPO=arm32v7 --build-arg ARCH=arm . -t ${DOCKER_TAG}-linux-arm
.PHONY: docker-build-arm .PHONY: docker-build-arm64
docker-build-arm64: minitor-linux-arm64 docker-build-arm64: dist/minitor-linux-arm64
docker build --build-arg REPO=arm64v8 --build-arg ARCH=arm64 . -t ${DOCKER_TAG}-linux-arm64 docker build --build-arg REPO=arm64v8 --build-arg ARCH=arm64 . -t ${DOCKER_TAG}-linux-arm64
# Cross run on host architechture # Cross run on host architechture
+129 -51
View File
@@ -1,79 +1,157 @@
# minitor-go # [minitor-go](https://git.iamthefij.com/iamthefij/minitor-go)
A reimplementation of [Minitor](https://git.iamthefij.com/iamthefij/minitor) in Go A minimal monitoring system
## What does it do?
Minitor accepts a YAML configuration file with a set of commands to run and a set of alerts to execute when those commands fail. It is designed to be as simple as possible and relies on other command line tools to do checks and issue alerts.
## But why?
I'm running a few small services and found Sensu, Consul, Nagios, etc. to all be far too complicated for my usecase.
## So how do I use it?
### Running
Install and execute with:
```bash
go get github.com/iamthefij/minitor-go
minitor
```
If locally developing you can use:
```bash
make run
```
It will read the contents of `config.yml` and begin its loop. You could also run it directly and provide a new config file via the `-config` argument.
#### Docker
You can pull this repository directly from Docker:
```bash
docker pull iamthefij/minitor-go:latest
```
The Docker image uses a default `config.yml` that is copied from `sample-config.yml`. This won't really do anything for you, so when you run the Docker image, you should supply your own `config.yml` file:
```bash
docker run -v $PWD/config.yml:/app/config.yml iamthefij/minitor-go:latest
```
Images are provided for `amd64`, `arm`, and `arm64` architechtures.
## Configuring
In this repo, you can explore the `sample-config.yml` file for an example, but the general structure is as follows. It should be noted that environment variable interpolation happens on load of the YAML file.
The global configurations are:
|key|value|
|---|---|
|`check_interval`|Maximum frequency to run checks for each monitor|
|`monitors`|List of all monitors. Detailed description below|
|`alerts`|List of all alerts. Detailed description below|
### Monitors
All monitors should be listed under `monitors`.
Each monitor allows the following configuration:
|key|value|
|---|---|
|`name`|Name of the monitor running. This will show up in messages and logs.|
|`command`|Specifies the command that should be executed, either in exec or shell form. This command's exit value will determine whether the check is successful|
|`alert_down`|A list of Alerts to be triggered when the monitor is in a "down" state|
|`alert_up`|A list of Alerts to be triggered when the monitor moves to an "up" state|
|`check_interval`|The interval at which this monitor should be checked. This must be greater than the global `check_interval` value|
|`alert_after`|Allows specifying the number of failed checks before an alert should be triggered|
|`alert_every`|Allows specifying how often an alert should be retriggered. There are a few magic numbers here. Defaults to `-1` for an exponential backoff. Setting to `0` disables re-alerting. Positive values will allow retriggering after the specified number of checks|
### Alerts
Alerts exist as objects keyed under `alerts`. Their key should be the name of the Alert. This is used in your monitor setup in `alert_down` and `alert_up`.
Eachy alert allows the following configuration:
|key|value|
|---|---|
|`command`|Specifies the command that should be executed, either in exec or shell form. This is the command that will be run when the alert is executed. This can be templated with environment variables or the variables shown in the table below|
Also, when alerts are executed, they will be passed through Go's format function with arguments for some attributes of the Monitor. The following monitor specific variables can be referenced using Go formatting syntax:
|token|value|
|---|---|
|`{{.AlertCount}}`|Number of times this monitor has alerted|
|`{{.FailureCount}}`|The total number of sequential failed checks for this monitor|
|`{{.LastCheckOutput}}`|The last returned value from the check command to either stderr or stdout|
|`{{.LastSuccess}}`|The ISO datetime of the last successful check|
|`{{.MonitorName}}`|The name of the monitor that failed and triggered the alert|
|`{{.IsUp}}`|Indicates if the monitor that is alerting is up or not. Can be used in a conditional message template|
### Metrics
Minitor supports exporting metrics for [Prometheus](https://prometheus.io/). Prometheus is an open source tool for reading and querying metrics from different sources. Combined with another tool, [Grafana](https://grafana.com/), it allows building of charts and dashboards. You could also opt to just use Minitor to log check results, and instead do your alerting with Grafana.
It is also possible to use the metrics endpoint for monitoring Minitor itself! This allows setting up multiple instances of Minitor on different servers and have them monitor each-other so that you can detect a minitor outage.
To run minitor with metrics, use the `-metrics` flag. The metrics will be served on port `8080` by default, though it can be overriden using `-metrics-port`. They will be accessible on the path `/metrics`. Eg. `localhost:8080/metrics`.
```bash
minitor -metrics
# or
minitor -metrics -metrics-port 3000
```
## Contributing
Whether you're looking to submit a patch or just tell me I broke something, you can contribute through the Github mirror and I can merge PRs back to the source repository.
Primary Repo: https://git.iamthefij.com/iamthefij/minitor.git
Github Mirror: https://github.com/IamTheFij/minitor.git
## Original Minitor
This is a reimplementation of [Minitor](https://git.iamthefij.com/iamthefij/minitor) in Go
Minitor is already a minimal monitoring tool. Python 3 was a quick way to get something live, but Python itself comes with a large footprint. Thus Go feels like a better fit for the project, longer term. Minitor is already a minimal monitoring tool. Python 3 was a quick way to get something live, but Python itself comes with a large footprint. Thus Go feels like a better fit for the project, longer term.
Initial target is meant to be roughly compatible requiring only minor changes to configuration. Future iterations may diverge to take advantage of Go specific features. Initial target is meant to be roughly compatible requiring only minor changes to configuration. Future iterations may diverge to take advantage of Go specific features.
## Differences from Python version ### Differences from Python version
Templating for Alert messages has been updated. In the Python version, `str.format(...)` was used with certain keys passed in that could be used to format messages. In the Go version, we use a struct, `AlertNotice` defined in `alert.go` and the built in Go templating format. Eg. Templating for Alert messages has been updated. In the Python version, `str.format(...)` was used with certain keys passed in that could be used to format messages. In the Go version, we use a struct, `AlertNotice` defined in `alert.go` and the built in Go templating format. Eg.
minitor-py: minitor-py:
```yaml ```yaml
alerts: alerts:
log_command: log:
command: ['echo', '{monitor_name}']
log_shell:
command: 'echo {monitor_name}' command: 'echo {monitor_name}'
``` ```
minitor-go: minitor-go:
```yaml ```yaml
alerts: alerts:
log_command: log:
command: ['echo', '{{.MonitorName}}']
log_shell:
command: 'echo {{.MonitorName}}' command: 'echo {{.MonitorName}}'
``` ```
Finally, newlines in a shell command don't terminate a particular command. Semicolons must be used and continuations should not. For the time being, legacy configs for the Python version of Minitor should be compatible if you apply the `-py-compat` flag when running Minitor. Eventually, this flag will go away when later breaking changes are introduced.
minitor-py: ## Future
```yaml
alerts:
log_shell:
command: >
echo "line 1"
echo "line 2"
echo "continued" \
"line"
```
minitor-go: Future, potentially breaking changes
```yaml
alerts:
log_shell:
command: >
echo "line 1";
echo "line 2";
echo "continued"
"line"
```
## To do
There are two sets of task lists. The first is to get rough parity on key features with the Python version. The second is to make some improvements to the framework.
Pairity:
- [x] Run monitor commands
- [x] Run monitor commands in a shell
- [x] Run alert commands
- [x] Run alert commands in a shell
- [x] Allow templating of alert commands
- [x] Implement Prometheus client to export metrics
- [x] Test coverage
- [x] Integration testing (manual or otherwise)
- [x] Allow commands and shell commands in the same config key
Improvement (potentially breaking):
- [ ] Implement leveled logging (maybe glog or logrus) - [ ] Implement leveled logging (maybe glog or logrus)
- [ ] Consider switching from YAML to TOML
- [ ] Consider value of templating vs injecting values into Env variables - [ ] Consider value of templating vs injecting values into Env variables
- [ ] Consider dropping `alert_up` and `alert_down` in favor of using Go templates that offer more control of messaging
- [ ] Async checking - [ ] Async checking
- [ ] Use durations rather than seconds checked in event loop
- [ ] Revisit metrics and see if they all make sense - [ ] Revisit metrics and see if they all make sense
- [ ] Consider dropping `alert_up` and `alert_down` in favor of using Go templates that offer more control of messaging (Breaking)
- [ ] Use durations rather than seconds checked in event loop (Potentially breaking)
+1 -1
View File
@@ -124,7 +124,7 @@ func NewLogAlert() *Alert {
Command: CommandOrShell{ Command: CommandOrShell{
Command: []string{ Command: []string{
"echo", "echo",
"{{.MonitorName}} check has failed {{.FailureCount}} times", "{{.MonitorName}} {{if .IsUp}}has recovered{{else}}check has failed {{.FailureCount}} times{{end}}",
}, },
}, },
} }
+18
View File
@@ -76,6 +76,24 @@ func TestAlertSend(t *testing.T) {
"Command shell with legacy template", "Command shell with legacy template",
true, true,
}, },
// Test default log alert down
{
*NewLogAlert(),
AlertNotice{MonitorName: "Test", FailureCount: 1, IsUp: false},
"Test check has failed 1 times\n",
false,
"Default log alert down",
false,
},
// Test default log alert up
{
*NewLogAlert(),
AlertNotice{MonitorName: "Test", IsUp: true},
"Test has recovered\n",
false,
"Default log alert up",
false,
},
} }
for _, c := range cases { for _, c := range cases {
+2 -1
View File
@@ -33,7 +33,7 @@ func checkMonitors(config *Config) error {
hasAlert := alertNotice != nil hasAlert := alertNotice != nil
// Track status metrics // Track status metrics
Metrics.SetMonitorStatus(monitor.Name, success) Metrics.SetMonitorStatus(monitor.Name, monitor.IsUp())
Metrics.CountCheck(monitor.Name, success, hasAlert) Metrics.CountCheck(monitor.Name, success, hasAlert)
// Should probably consider refactoring everything below here // Should probably consider refactoring everything below here
@@ -87,6 +87,7 @@ func main() {
flag.BoolVar(&LogDebug, "debug", false, "Enables debug logs (default: false)") flag.BoolVar(&LogDebug, "debug", false, "Enables debug logs (default: false)")
flag.BoolVar(&ExportMetrics, "metrics", false, "Enables prometheus metrics exporting (default: false)") flag.BoolVar(&ExportMetrics, "metrics", false, "Enables prometheus metrics exporting (default: false)")
flag.BoolVar(&PyCompat, "py-compat", false, "Enables support for legacy Python Minitor config. Will eventually be removed. (default: false)") flag.BoolVar(&PyCompat, "py-compat", false, "Enables support for legacy Python Minitor config. Will eventually be removed. (default: false)")
flag.IntVar(&MetricsPort, "metrics-port", 8080, "The port that Prometheus metrics should be exported on, if enabled. (default: 8080)")
var showVersion = flag.Bool("version", false, "Display the version of minitor and exit") var showVersion = flag.Bool("version", false, "Display the version of minitor and exit")
var configPath = flag.String("config", "config.yml", "Alternate configuration path (default: config.yml)") var configPath = flag.String("config", "config.yml", "Alternate configuration path (default: config.yml)")
flag.Parse() flag.Parse()
+3 -2
View File
@@ -85,12 +85,13 @@ func (monitor *Monitor) Check() (bool, *AlertNotice) {
return isSuccess, alertNotice return isSuccess, alertNotice
} }
func (monitor Monitor) isUp() bool { // IsUp returns the status of the current monitor
func (monitor Monitor) IsUp() bool {
return monitor.alertCount == 0 return monitor.alertCount == 0
} }
func (monitor *Monitor) success() (notice *AlertNotice) { func (monitor *Monitor) success() (notice *AlertNotice) {
if !monitor.isUp() { if !monitor.IsUp() {
// Alert that we have recovered // Alert that we have recovered
notice = monitor.createAlertNotice(true) notice = monitor.createAlertNotice(true)
} }
+3 -3
View File
@@ -56,7 +56,7 @@ func TestMonitorShouldCheck(t *testing.T) {
} }
} }
// TestMonitorIsUp tests the Monitor.isUp() // TestMonitorIsUp tests the Monitor.IsUp()
func TestMonitorIsUp(t *testing.T) { func TestMonitorIsUp(t *testing.T) {
cases := []struct { cases := []struct {
monitor Monitor monitor Monitor
@@ -71,9 +71,9 @@ func TestMonitorIsUp(t *testing.T) {
for _, c := range cases { for _, c := range cases {
log.Printf("Testing case %s", c.name) log.Printf("Testing case %s", c.name)
actual := c.monitor.isUp() actual := c.monitor.IsUp()
if actual != c.expected { if actual != c.expected {
t.Errorf("isUp(%v), expected=%t actual=%t", c.name, c.expected, actual) t.Errorf("IsUp(%v), expected=%t actual=%t", c.name, c.expected, actual)
log.Printf("Case failed: %s", c.name) log.Printf("Case failed: %s", c.name)
} }
log.Println("-----") log.Println("-----")