33 Commits

Author SHA1 Message Date
Matej Kramny
c04128ce36 compile message for Fixed status
- better logging
2017-02-06 23:05:39 -08:00
Matej Kramny
1b93730121 compile template message 2017-02-06 21:56:08 -08:00
Matej Kramny
85d92bcb07 rename monitor -> mon 2017-02-06 10:57:02 -08:00
Matej Kramny
0dc54e4e6e - customisable time format
- custom messages
- configure threshold count instead of uptime %
2017-02-05 23:43:38 -08:00
Matej Kramny
b3bc1d4405 - compile message templates
- send metrics to cachet
- fix http default configuration
2017-02-05 19:27:01 -08:00
Matej Kramny
b4fa33b8ad - immediate tick flag
- reword Start -> ClockStart etc
2017-02-04 22:40:31 -08:00
Matej Kramny
edfd4a51e6 Print monitor features 2017-02-04 22:15:24 -08:00
Matej Kramny
a2d8128109 huuman friendly config! 2017-02-04 21:49:13 -08:00
Matej Kramny
d43eca4b7d - yaml & json supported 2017-02-04 21:48:27 -08:00
Matej Kramny
36bf228599 a compiling proof of concept
- abstract type
- http, tcp, icmp & dns monitor types
- unmarshal from json into any monitor type
2017-02-04 18:23:53 -08:00
Matej Kramny
0cd6fa13a7 Merge branch 'master' into v3
# Conflicts:
#	cli/main.go
2017-02-04 16:12:42 -08:00
Matej Kramny
e910807973 basic refactor + new prototype 2017-02-04 16:02:22 -08:00
Matej Kramny
9b29a0450c Merge pull request #40 from to-kn/add_http_header_support
Add http header support
2017-02-04 14:45:21 -08:00
Matej Kramny
aaecc1669a Merge pull request #41 from yacloud-io/master
Support making request with proxy
2016-07-27 16:30:15 +01:00
Yi Tao Jiang
48586eb0aa Support making request with proxy 2016-07-27 23:24:54 +08:00
Tobias Knipping
2c364f3d2f add support for specifying http-headers and really use Method spezified 2016-07-24 16:34:30 +02:00
Matej Kramny
0de0baf5f9 Merge pull request #31 from faizshukri/fix/timeout-exceed
Timeout exceeded while awaiting headers
2016-06-22 15:59:54 +01:00
Faiz Shukri
3f4b9ced77 Add timeout customization 2016-06-16 13:38:51 +08:00
Matej Kramny
20e4dd1414 Add to readme 2016-05-19 19:43:01 +01:00
Matej Kramny
29b02fd164 Update example JSON 2016-05-19 19:41:19 +01:00
Matej Kramny
5c4f0c2e69 Print descriptions from cli 2016-05-19 19:34:36 +01:00
Matej Kramny
9d0e176695 Add to readme, remove comment 2016-05-19 19:26:29 +01:00
Matej Kramny
6e9f5440ba Update documentation 2016-05-19 19:18:02 +01:00
Matej Kramny
0ceccccd45 More config options, markdown in incidents
- Specify method to ping with
- Body regex match
- Markdown in incident messages
- Update existing incidents
2016-05-19 18:40:01 +01:00
Matej Kramny
c729fbdf41 Update readme 2016-05-19 12:55:53 +01:00
Matej Kramny
30eea191d3 Merge branch 'Soulou-monitor_interval'
* Soulou-monitor_interval:
  update readme
  Implement 'inteval' config parameter -> number of seconds between checks
2016-05-19 12:53:54 +01:00
Matej Kramny
e0556b56b4 Merge branch 'monitor_interval' of https://github.com/Soulou/cachet-monitor into Soulou-monitor_interval
* 'monitor_interval' of https://github.com/Soulou/cachet-monitor:
  update readme
  Implement 'inteval' config parameter -> number of seconds between checks

# Conflicts:
#	cachet/config.go
#	main.go
#	monitor.go
#	readme.md
2016-05-19 12:53:21 +01:00
Matej Kramny
2d62fc7443 refactoring 2016-05-19 12:20:56 +01:00
Matej Kramny
dfad6f0906 Vision readme 2016-05-19 00:05:00 +01:00
Matej Kramny
267a6cb6b3 better packaging
- update readme
2016-05-18 23:54:55 +01:00
Alan Campbell
025d0c5822 Merge pull request #27 from CastawayLabs/fix-readme
Update go install guide
2016-03-07 16:34:36 -05:00
Soulou
e4a586b92a update readme 2015-08-23 20:01:41 +02:00
Soulou
76b897eb05 Implement 'inteval' config parameter -> number of seconds between checks 2015-08-23 17:33:23 +02:00
24 changed files with 1082 additions and 624 deletions

5
.gitignore vendored
View File

@@ -1,2 +1,3 @@
gin-bin /config.yml
example.config.local.json /config.json
examples/

View File

@@ -1,6 +0,0 @@
FROM golang
ADD . /go/src/github.com/castawaylabs/cachet-monitor
RUN go install github.com/castawaylabs/cachet-monitor
ENTRYPOINT /go/bin/cachet-monitor

79
api.go Normal file
View File

@@ -0,0 +1,79 @@
package cachet
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"net/http"
"strconv"
"time"
"github.com/Sirupsen/logrus"
)
type CachetAPI struct {
URL string `json:"url"`
Token string `json:"token"`
Insecure bool `json:"insecure"`
}
type CachetResponse struct {
Data json.RawMessage `json:"data"`
}
// TODO: test
func (api CachetAPI) Ping() error {
resp, _, err := api.NewRequest("GET", "/ping", nil)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New("API Responded with non-200 status code")
}
return nil
}
// SendMetric adds a data point to a cachet monitor
func (api CachetAPI) SendMetric(id int, lag int64) {
logrus.Debugf("Sending lag metric ID:%d RTT %vms", id, lag)
jsonBytes, _ := json.Marshal(map[string]interface{}{
"value": lag,
"timestamp": time.Now().Unix(),
})
resp, _, err := api.NewRequest("POST", "/metrics/"+strconv.Itoa(id)+"/points", jsonBytes)
if err != nil || resp.StatusCode != 200 {
logrus.Warnf("Could not log metric! ID: %d, err: %v", id, err)
}
}
// TODO: test
// NewRequest wraps http.NewRequest
func (api CachetAPI) NewRequest(requestType, url string, reqBody []byte) (*http.Response, CachetResponse, error) {
req, err := http.NewRequest(requestType, api.URL+url, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", api.Token)
transport := http.DefaultTransport.(*http.Transport)
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: api.Insecure}
client := &http.Client{
Transport: transport,
}
res, err := client.Do(req)
if err != nil {
return nil, CachetResponse{}, err
}
var body struct {
Data json.RawMessage `json:"data"`
}
err = json.NewDecoder(res.Body).Decode(&body)
return res, body, err
}

View File

@@ -1,20 +0,0 @@
package cachet
import "encoding/json"
// Component Cachet model
type Component struct {
ID json.Number `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Status json.Number `json:"status_id"`
HumanStatus string `json:"-"`
IncidentCount int `json:"-"`
CreatedAt *string `json:"created_at"`
UpdatedAt *string `json:"updated_at"`
}
// ComponentData json response model
type ComponentData struct {
Component Component `json:"data"`
}

View File

@@ -1,119 +0,0 @@
package cachet
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"github.com/castawaylabs/cachet-monitor/system"
)
// Static config
var Config CachetConfig
// Central logger
var Logger *log.Logger
// CachetConfig is the monitoring tool configuration
type CachetConfig struct {
APIUrl string `json:"api_url"`
APIToken string `json:"api_token"`
Interval int64 `json:"interval"`
Monitors []*Monitor `json:"monitors"`
SystemName string `json:"system_name"`
LogPath string `json:"log_path"`
InsecureAPI bool `json:"insecure_api"`
}
func init() {
var configPath string
var systemName string
var logPath string
flag.StringVar(&configPath, "c", "/etc/cachet-monitor.config.json", "Config path")
flag.StringVar(&systemName, "name", "", "System Name")
flag.StringVar(&logPath, "log", "", "Log path")
flag.Parse()
var data []byte
// test if its a url
url, err := url.ParseRequestURI(configPath)
if err == nil && len(url.Scheme) > 0 {
// download config
response, err := http.Get(configPath)
if err != nil {
fmt.Printf("Cannot download network config: %v\n", err)
os.Exit(1)
}
defer response.Body.Close()
data, _ = ioutil.ReadAll(response.Body)
fmt.Println("Downloaded network configuration.")
} else {
data, err = ioutil.ReadFile(configPath)
if err != nil {
fmt.Println("Config file '" + configPath + "' missing!")
os.Exit(1)
}
}
err = json.Unmarshal(data, &Config)
if err != nil {
fmt.Println("Cannot parse config!")
os.Exit(1)
}
if len(systemName) > 0 {
Config.SystemName = systemName
}
if len(Config.SystemName) == 0 {
// get hostname
Config.SystemName = system.GetHostname()
}
if len(os.Getenv("CACHET_API")) > 0 {
Config.APIUrl = os.Getenv("CACHET_API")
}
if len(os.Getenv("CACHET_TOKEN")) > 0 {
Config.APIToken = os.Getenv("CACHET_TOKEN")
}
if len(Config.APIToken) == 0 || len(Config.APIUrl) == 0 {
fmt.Printf("API URL or API Token not set. cachet-monitor won't be able to report incidents.\n\nPlease set:\n CACHET_API and CACHET_TOKEN environment variable to override settings.\n\nGet help at https://github.com/CastawayLabs/cachet-monitor\n")
os.Exit(1)
}
if len(Config.Monitors) == 0 {
fmt.Printf("No monitors defined!\nSee sample configuration: https://github.com/CastawayLabs/cachet-monitor/blob/master/example.config.json\n")
os.Exit(1)
}
if len(logPath) > 0 {
Config.LogPath = logPath
}
var logWriter io.Writer
logWriter = os.Stdout
if len(Config.LogPath) > 0 {
logWriter, err = os.Create(Config.LogPath)
if err != nil {
fmt.Printf("Unable to open file '%v' for logging\n", Config.LogPath)
os.Exit(1)
}
}
flags := log.Llongfile | log.Ldate | log.Ltime
if len(os.Getenv("DEVELOPMENT")) > 0 {
flags = 0
}
Logger = log.New(logWriter, "", flags)
}

View File

@@ -1,165 +0,0 @@
package cachet
import (
"encoding/json"
"strconv"
)
// Incident Cachet data model
type Incident struct {
ID json.Number `json:"id"`
Name string `json:"name"`
Message string `json:"message"`
Status json.Number `json:"status"` // 4?
HumanStatus string `json:"human_status"`
Component *Component `json:"-"`
ComponentID *json.Number `json:"component_id"`
CreatedAt *string `json:"created_at"`
UpdatedAt *string `json:"updated_at"`
}
// IncidentData is a response when creating/updating an incident
type IncidentData struct {
Incident Incident `json:"data"`
}
// IncidentList - from API /incidents
type IncidentList struct {
Incidents []Incident `json:"data"`
}
// GetIncidents - Get list of incidents
func GetIncidents() []Incident {
_, body, err := makeRequest("GET", "/incidents", nil)
if err != nil {
Logger.Printf("Cannot get incidents: %v\n", err)
return []Incident{}
}
var data IncidentList
err = json.Unmarshal(body, &data)
if err != nil {
Logger.Printf("Cannot parse incidents: %v\n", err)
panic(err)
}
return data.Incidents
}
// Send - Create or Update incident
func (incident *Incident) Send() {
jsonBytes, _ := json.Marshal(map[string]interface{}{
"name": incident.Name,
"message": incident.Message,
"status": incident.Status,
"component_id": incident.ComponentID,
"notify": true,
})
requestType := "POST"
requestURL := "/incidents"
if len(incident.ID) > 0 {
requestType = "PUT"
requestURL += "/" + string(incident.ID)
}
resp, body, err := makeRequest(requestType, requestURL, jsonBytes)
if err != nil {
Logger.Printf("Cannot create/update incident: %v\n", err)
return
}
Logger.Println(strconv.Itoa(resp.StatusCode) + " " + string(body))
var data IncidentData
err = json.Unmarshal(body, &data)
if err != nil {
Logger.Println("Cannot parse incident body.", string(body))
panic(err)
} else {
incident.ID = data.Incident.ID
incident.Component = data.Incident.Component
}
if resp.StatusCode != 200 {
Logger.Println("Could not create/update incident!")
}
}
func (incident *Incident) fetchComponent() error {
_, body, err := makeRequest("GET", "/components/"+string(*incident.ComponentID), nil)
if err != nil {
return err
}
var data ComponentData
err = json.Unmarshal(body, &data)
if err != nil {
Logger.Println("Cannot parse component body. %v", string(body))
panic(err)
}
incident.Component = &data.Component
return nil
}
func (incident *Incident) UpdateComponent() {
if incident.ComponentID == nil || len(*incident.ComponentID) == 0 {
return
}
if incident.Component == nil {
// fetch component
if err := incident.fetchComponent(); err != nil {
Logger.Printf("Cannot fetch component for incident. %v\n", err)
return
}
}
status, _ := strconv.Atoi(string(incident.Status))
switch status {
case 1, 2, 3:
if incident.Component.Status == "3" {
incident.Component.Status = "4"
} else {
incident.Component.Status = "3"
}
case 4:
incident.Component.Status = "1"
}
jsonBytes, _ := json.Marshal(map[string]interface{}{
"status": incident.Component.Status,
})
resp, _, err := makeRequest("PUT", "/components/"+string(incident.Component.ID), jsonBytes)
if err != nil || resp.StatusCode != 200 {
Logger.Printf("Could not update component: (resp code %d) %v", resp.StatusCode, err)
return
}
}
// SetInvestigating sets status to Investigating
func (incident *Incident) SetInvestigating() {
incident.Status = "1"
incident.HumanStatus = "Investigating"
}
// SetIdentified sets status to Identified
func (incident *Incident) SetIdentified() {
incident.Status = "2"
incident.HumanStatus = "Identified"
}
// SetWatching sets status to Watching
func (incident *Incident) SetWatching() {
incident.Status = "3"
incident.HumanStatus = "Watching"
}
// SetFixed sets status to Fixed
func (incident *Incident) SetFixed() {
incident.Status = "4"
incident.HumanStatus = "Fixed"
}

View File

@@ -1,23 +0,0 @@
package cachet
import (
"encoding/json"
"strconv"
)
// SendMetric sends lag metric point
func SendMetric(metricID int, delay int64) {
if metricID <= 0 {
return
}
jsonBytes, _ := json.Marshal(&map[string]interface{}{
"value": delay,
})
resp, _, err := makeRequest("POST", "/metrics/"+strconv.Itoa(metricID)+"/points", jsonBytes)
if err != nil || resp.StatusCode != 200 {
Logger.Printf("Could not log data point!\n%v\n", err)
return
}
}

View File

@@ -1,133 +0,0 @@
package cachet
import (
"crypto/tls"
"encoding/json"
"net/http"
"strconv"
"time"
)
const timeout = time.Duration(time.Second)
// Monitor data model
type Monitor struct {
Name string `json:"name"`
URL string `json:"url"`
MetricID int `json:"metric_id"`
Threshold float32 `json:"threshold"`
ComponentID *int `json:"component_id"`
ExpectedStatusCode int `json:"expected_status_code"`
StrictTLS *bool `json:"strict_tls"`
History []bool `json:"-"`
LastFailReason *string `json:"-"`
Incident *Incident `json:"-"`
}
// Run loop
func (monitor *Monitor) Run() {
reqStart := getMs()
isUp := monitor.doRequest()
lag := getMs() - reqStart
if len(monitor.History) >= 10 {
monitor.History = monitor.History[len(monitor.History)-9:]
}
monitor.History = append(monitor.History, isUp)
monitor.AnalyseData()
if isUp == true && monitor.MetricID > 0 {
SendMetric(monitor.MetricID, lag)
}
}
func (monitor *Monitor) doRequest() bool {
client := &http.Client{
Timeout: timeout,
}
if monitor.StrictTLS != nil && *monitor.StrictTLS == false {
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
resp, err := client.Get(monitor.URL)
if err != nil {
errString := err.Error()
monitor.LastFailReason = &errString
return false
}
defer resp.Body.Close()
if resp.StatusCode != monitor.ExpectedStatusCode {
failReason := "Unexpected response code: " + strconv.Itoa(resp.StatusCode) + ". Expected " + strconv.Itoa(monitor.ExpectedStatusCode)
monitor.LastFailReason = &failReason
return false
}
return true
}
// AnalyseData decides if the monitor is statistically up or down and creates / resolves an incident
func (monitor *Monitor) AnalyseData() {
// look at the past few incidents
numDown := 0
for _, wasUp := range monitor.History {
if wasUp == false {
numDown++
}
}
t := (float32(numDown) / float32(len(monitor.History))) * 100
Logger.Printf("%s %.2f%% Down at %v. Threshold: %.2f%%\n", monitor.URL, t, time.Now().UnixNano()/int64(time.Second), monitor.Threshold)
if len(monitor.History) != 10 {
// not enough data
return
}
if t > monitor.Threshold && monitor.Incident == nil {
// is down, create an incident
Logger.Println("Creating incident...")
component_id := json.Number(strconv.Itoa(*monitor.ComponentID))
monitor.Incident = &Incident{
Name: monitor.Name + " - " + Config.SystemName,
Message: monitor.Name + " check failed",
ComponentID: &component_id,
}
if monitor.LastFailReason != nil {
monitor.Incident.Message += "\n\n - " + *monitor.LastFailReason
}
// set investigating status
monitor.Incident.SetInvestigating()
// create/update incident
monitor.Incident.Send()
monitor.Incident.UpdateComponent()
} else if t < monitor.Threshold && monitor.Incident != nil {
// was down, created an incident, its now ok, make it resolved.
Logger.Println("Updating incident to resolved...")
component_id := json.Number(strconv.Itoa(*monitor.ComponentID))
monitor.Incident = &Incident{
Name: monitor.Incident.Name,
Message: monitor.Name + " check succeeded",
ComponentID: &component_id,
}
monitor.Incident.SetFixed()
monitor.Incident.Send()
monitor.Incident.UpdateComponent()
monitor.Incident = nil
}
}
func getMs() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}

View File

@@ -1,32 +0,0 @@
package cachet
import (
"bytes"
"crypto/tls"
"io/ioutil"
"net/http"
)
func makeRequest(requestType string, url string, reqBody []byte) (*http.Response, []byte, error) {
req, err := http.NewRequest(requestType, Config.APIUrl+url, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Cachet-Token", Config.APIToken)
client := &http.Client{}
if Config.InsecureAPI == true {
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
res, err := client.Do(req)
if err != nil {
return nil, []byte{}, err
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return res, body, nil
}

206
cli/main.go Normal file
View File

@@ -0,0 +1,206 @@
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"sync"
"github.com/Sirupsen/logrus"
cachet "github.com/castawaylabs/cachet-monitor"
docopt "github.com/docopt/docopt-go"
"github.com/mitchellh/mapstructure"
"gopkg.in/yaml.v2"
)
const usage = `cachet-monitor
Usage:
cachet-monitor (-c PATH | --config PATH) [--log=LOGPATH] [--name=NAME] [--immediate]
cachet-monitor -h | --help | --version
cachet-monitor print-config
Arguments:
PATH path to config.json
LOGPATH path to log output (defaults to STDOUT)
NAME name of this logger
Examples:
cachet-monitor -c /root/cachet-monitor.json
cachet-monitor -c /root/cachet-monitor.json --log=/var/log/cachet-monitor.log --name="development machine"
Options:
-c PATH.json --config PATH Path to configuration file
-h --help Show this screen.
--version Show version
--immediate Tick immediately (by default waits for first defined interval)
print-config Print example configuration
Environment varaibles:
CACHET_API override API url from configuration
CACHET_TOKEN override API token from configuration
CACHET_DEV set to enable dev logging`
func main() {
arguments, _ := docopt.Parse(usage, nil, true, "cachet-monitor", false)
cfg, err := getConfiguration(arguments["--config"].(string))
if err != nil {
logrus.Panicf("Unable to start (reading config): %v", err)
}
if immediate, ok := arguments["--immediate"]; ok {
cfg.Immediate = immediate.(bool)
}
if name := arguments["--name"]; name != nil {
cfg.SystemName = name.(string)
}
logrus.SetOutput(getLogger(arguments["--log"]))
if len(os.Getenv("CACHET_API")) > 0 {
cfg.API.URL = os.Getenv("CACHET_API")
}
if len(os.Getenv("CACHET_TOKEN")) > 0 {
cfg.API.Token = os.Getenv("CACHET_TOKEN")
}
if len(os.Getenv("CACHET_DEV")) > 0 {
logrus.SetLevel(logrus.DebugLevel)
}
if valid := cfg.Validate(); !valid {
logrus.Errorf("Invalid configuration")
os.Exit(1)
}
logrus.Debug("Configuration valid")
logrus.Infof("System: %s", cfg.SystemName)
logrus.Infof("API: %s", cfg.API.URL)
logrus.Infof("Monitors: %d\n", len(cfg.Monitors))
logrus.Infof("Pinging cachet")
if err := cfg.API.Ping(); err != nil {
logrus.Errorf("Cannot ping cachet!\n%v", err)
os.Exit(1)
}
logrus.Infof("Ping OK")
wg := &sync.WaitGroup{}
for index, monitor := range cfg.Monitors {
logrus.Infof("Starting Monitor #%d: ", index)
logrus.Infof("Features: \n - %v", strings.Join(monitor.Describe(), "\n - "))
go monitor.ClockStart(cfg, monitor, wg)
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, os.Kill)
<-signals
logrus.Warnf("Abort: Waiting monitors to finish")
for _, mon := range cfg.Monitors {
mon.GetMonitor().ClockStop()
}
wg.Wait()
}
func getLogger(logPath interface{}) *os.File {
if logPath == nil || len(logPath.(string)) == 0 {
return os.Stdout
}
file, err := os.Create(logPath.(string))
if err != nil {
logrus.Errorf("Unable to open file '%v' for logging: \n%v", logPath, err)
os.Exit(1)
}
return file
}
func getConfiguration(path string) (*cachet.CachetMonitor, error) {
var cfg cachet.CachetMonitor
var data []byte
// test if its a url
url, err := url.ParseRequestURI(path)
if err == nil && len(url.Scheme) > 0 {
// download config
response, err := http.Get(path)
if err != nil {
logrus.Warn("Unable to download network configuration")
return nil, err
}
defer response.Body.Close()
data, _ = ioutil.ReadAll(response.Body)
logrus.Info("Downloaded network configuration.")
} else {
data, err = ioutil.ReadFile(path)
if err != nil {
return nil, errors.New("Unable to open file: '" + path + "'")
}
}
if strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml") {
err = yaml.Unmarshal(data, &cfg)
} else {
err = json.Unmarshal(data, &cfg)
}
if err != nil {
logrus.Warnf("Unable to parse configuration file")
}
cfg.Monitors = make([]cachet.MonitorInterface, len(cfg.RawMonitors))
for index, rawMonitor := range cfg.RawMonitors {
var t cachet.MonitorInterface
var err error
// get default type
monType := cachet.GetMonitorType("")
if t, ok := rawMonitor["type"].(string); ok {
monType = cachet.GetMonitorType(t)
}
switch monType {
case "http":
var s cachet.HTTPMonitor
err = mapstructure.Decode(rawMonitor, &s)
t = &s
case "dns":
var s cachet.DNSMonitor
err = mapstructure.Decode(rawMonitor, &s)
t = &s
case "icmp":
var s cachet.ICMPMonitor
err = mapstructure.Decode(rawMonitor, &s)
t = &s
case "tcp":
var s cachet.TCPMonitor
err = mapstructure.Decode(rawMonitor, &s)
t = &s
default:
logrus.Errorf("Invalid monitor type (index: %d) %v", index, monType)
continue
}
t.GetMonitor().Type = monType
if err != nil {
logrus.Errorf("Unable to unmarshal monitor to type (index: %d): %v", index, err)
continue
}
cfg.Monitors[index] = t
}
return &cfg, err
}

89
config.go Normal file
View File

@@ -0,0 +1,89 @@
package cachet
import (
"net"
"os"
"strings"
"time"
"github.com/Sirupsen/logrus"
)
type CachetMonitor struct {
SystemName string `json:"system_name" yaml:"system_name"`
DateFormat string `json:"date_format" yaml:"date_format"`
API CachetAPI `json:"api"`
RawMonitors []map[string]interface{} `json:"monitors" yaml:"monitors"`
Monitors []MonitorInterface `json:"-" yaml:"-"`
Immediate bool `json:"-" yaml:"-"`
}
// Validate configuration
func (cfg *CachetMonitor) Validate() bool {
valid := true
if len(cfg.SystemName) == 0 {
// get hostname
cfg.SystemName = getHostname()
}
if len(cfg.DateFormat) == 0 {
cfg.DateFormat = DefaultTimeFormat
}
if len(cfg.API.Token) == 0 || len(cfg.API.URL) == 0 {
logrus.Warnf("API URL or API Token missing.\nGet help at https://github.com/castawaylabs/cachet-monitor")
valid = false
}
if len(cfg.Monitors) == 0 {
logrus.Warnf("No monitors defined!\nSee help for example configuration")
valid = false
}
for index, monitor := range cfg.Monitors {
if errs := monitor.Validate(); len(errs) > 0 {
logrus.Warnf("Monitor validation errors (index %d): %v", index, "\n - "+strings.Join(errs, "\n - "))
valid = false
}
}
return valid
}
// getHostname returns id of the current system
func getHostname() string {
hostname, err := os.Hostname()
if err == nil && len(hostname) > 0 {
return hostname
}
addrs, err := net.InterfaceAddrs()
if err != nil || len(addrs) == 0 {
return "unknown"
}
return addrs[0].String()
}
func getMs() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}
func GetMonitorType(t string) string {
if len(t) == 0 {
return "http"
}
return strings.ToLower(t)
}
func getTemplateData(monitor *AbstractMonitor) map[string]interface{} {
return map[string]interface{}{
"SystemName": monitor.config.SystemName,
"API": monitor.config.API,
"Monitor": monitor,
"now": time.Now().Format(monitor.config.DateFormat),
}
}

15
config_test.go Normal file
View File

@@ -0,0 +1,15 @@
package cachet
import (
"testing"
)
func TestGetMonitorType(t *testing.T) {
if monType := GetMonitorType(""); monType != "http" {
t.Error("monitor type `` should default to http")
}
if mt := GetMonitorType("HTTP"); mt != "http" {
t.Error("does not return correct monitor type")
}
}

5
dns.go Normal file
View File

@@ -0,0 +1,5 @@
package cachet
type DNSMonitor struct {
AbstractMonitor `mapstructure:",squash"`
}

View File

@@ -1,17 +1,22 @@
{ {
"api_url": "https://demo.cachethq.io/api/v1", "api": {
"api_token": "9yMHsdioQosnyVK4iCVR", "url": "https://demo.cachethq.io/api/v1",
"interval": 5, "token": "9yMHsdioQosnyVK4iCVR",
"insecure": true
},
"monitors": [ "monitors": [
{ {
"name": "nodegear frontend", "name": "google",
"url": "https://nodegear.io/ping", "url": "https://google.com",
"metric_id": 1,
"threshold": 80, "threshold": 80,
"component_id": null, "component_id": 1,
"interval": 10,
"timeout": 5,
"headers": {
"Authorization": "Basic <hash>"
},
"expected_status_code": 200, "expected_status_code": 200,
"strict_tls": true "strict_tls": true
} }
], ]
"insecure_api": false }
}

14
example.config.yml Normal file
View File

@@ -0,0 +1,14 @@
api:
url: https://demo.cachethq.io/api/v1
token: 9yMHsdioQosnyVK4iCVR
monitors:
- name: google
target: https://google.com
threshold: 80
component_id: 1
interval: 10
timeout: 5
headers:
Authorization: Basic <hash>
expected_status_code: 200
strict: true

125
http.go Normal file
View File

@@ -0,0 +1,125 @@
package cachet
import (
"crypto/tls"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
// Investigating template
var defaultHTTPInvestigatingTpl = MessageTemplate{
Subject: `{{ .Monitor.Name }} - {{ .SystemName }}`,
Message: `{{ .Monitor.Name }} check **failed** (server time: {{ .now }})
{{ .FailReason }}`,
}
// Fixed template
var defaultHTTPFixedTpl = MessageTemplate{
Subject: `{{ .Monitor.Name }} - {{ .SystemName }}`,
Message: `**Resolved** - {{ .now }}
- - -
{{ .incident.Message }}`,
}
type HTTPMonitor struct {
AbstractMonitor `mapstructure:",squash"`
Method string
ExpectedStatusCode int `mapstructure:"expected_status_code"`
Headers map[string]string
// compiled to Regexp
ExpectedBody string `mapstructure:"expected_body"`
bodyRegexp *regexp.Regexp
}
// TODO: test
func (monitor *HTTPMonitor) test() bool {
req, err := http.NewRequest(monitor.Method, monitor.Target, nil)
for k, v := range monitor.Headers {
req.Header.Add(k, v)
}
transport := http.DefaultTransport.(*http.Transport)
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: monitor.Strict == false}
client := &http.Client{
Timeout: time.Duration(monitor.Timeout * time.Second),
Transport: transport,
}
resp, err := client.Do(req)
if err != nil {
monitor.lastFailReason = err.Error()
return false
}
defer resp.Body.Close()
if monitor.ExpectedStatusCode > 0 && resp.StatusCode != monitor.ExpectedStatusCode {
monitor.lastFailReason = "Expected HTTP response status: " + strconv.Itoa(monitor.ExpectedStatusCode) + ", got: " + strconv.Itoa(resp.StatusCode)
return false
}
if monitor.bodyRegexp != nil {
// check response body
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
monitor.lastFailReason = err.Error()
return false
}
if !monitor.bodyRegexp.Match(responseBody) {
monitor.lastFailReason = "Unexpected body: " + string(responseBody) + ".\nExpected to match: " + monitor.ExpectedBody
return false
}
}
return true
}
// TODO: test
func (mon *HTTPMonitor) Validate() []string {
mon.Template.Investigating.SetDefault(defaultHTTPInvestigatingTpl)
mon.Template.Fixed.SetDefault(defaultHTTPFixedTpl)
errs := mon.AbstractMonitor.Validate()
if len(mon.ExpectedBody) > 0 {
exp, err := regexp.Compile(mon.ExpectedBody)
if err != nil {
errs = append(errs, "Regexp compilation failure: "+err.Error())
} else {
mon.bodyRegexp = exp
}
}
if len(mon.ExpectedBody) == 0 && mon.ExpectedStatusCode == 0 {
errs = append(errs, "Both 'expected_body' and 'expected_status_code' fields empty")
}
mon.Method = strings.ToUpper(mon.Method)
switch mon.Method {
case "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD":
break
case "":
mon.Method = "GET"
default:
errs = append(errs, "Unsupported HTTP method: "+mon.Method)
}
return errs
}
func (mon *HTTPMonitor) Describe() []string {
features := mon.AbstractMonitor.Describe()
features = append(features, "Method: "+mon.Method)
return features
}

5
icmp.go Normal file
View File

@@ -0,0 +1,5 @@
package cachet
type ICMPMonitor struct {
AbstractMonitor `mapstructure:",squash"`
}

112
incident.go Normal file
View File

@@ -0,0 +1,112 @@
package cachet
import (
"encoding/json"
"fmt"
"strconv"
"github.com/Sirupsen/logrus"
)
// Incident Cachet data model
type Incident struct {
ID int `json:"id"`
Name string `json:"name"`
Message string `json:"message"`
Status int `json:"status"`
Visible int `json"visible"`
Notify bool `json:"notify"`
ComponentID int `json:"component_id"`
ComponentStatus int `json:"component_status"`
}
// Send - Create or Update incident
func (incident *Incident) Send(cfg *CachetMonitor) error {
switch incident.Status {
case 1, 2, 3:
// partial outage
incident.ComponentStatus = 3
componentStatus, err := incident.GetComponentStatus(cfg)
if componentStatus == 3 {
// major outage
incident.ComponentStatus = 4
}
if err != nil {
logrus.Warnf("cannot fetch component: %v", err)
}
case 4:
// fixed
incident.ComponentStatus = 1
}
requestType := "POST"
requestURL := "/incidents"
if incident.ID > 0 {
requestType = "PUT"
requestURL += "/" + strconv.Itoa(incident.ID)
}
jsonBytes, _ := json.Marshal(incident)
resp, body, err := cfg.API.NewRequest(requestType, requestURL, jsonBytes)
if err != nil {
return err
}
var data struct {
ID int `json:"id"`
}
if err := json.Unmarshal(body.Data, &data); err != nil {
return fmt.Errorf("Cannot parse incident body: %v, %v", err, string(body.Data))
}
incident.ID = data.ID
if resp.StatusCode != 200 {
return fmt.Errorf("Could not create/update incident!")
}
return nil
}
func (incident *Incident) GetComponentStatus(cfg *CachetMonitor) (int, error) {
resp, body, err := cfg.API.NewRequest("GET", "/components/"+strconv.Itoa(incident.ComponentID), nil)
if err != nil {
return 0, err
}
if resp.StatusCode != 200 {
return 0, fmt.Errorf("Invalid status code. Received %d", resp.StatusCode)
}
var data struct {
Status int `json:"status"`
}
if err := json.Unmarshal(body.Data, &data); err != nil {
return 0, fmt.Errorf("Cannot parse component body: %v. Err = %v", string(body.Data), err)
}
return data.Status, nil
}
// SetInvestigating sets status to Investigating
func (incident *Incident) SetInvestigating() {
incident.Status = 1
}
// SetIdentified sets status to Identified
func (incident *Incident) SetIdentified() {
incident.Status = 2
}
// SetWatching sets status to Watching
func (incident *Incident) SetWatching() {
incident.Status = 3
}
// SetFixed sets status to Fixed
func (incident *Incident) SetFixed() {
incident.Status = 4
}

29
main.go
View File

@@ -1,29 +0,0 @@
package main
import (
"github.com/castawaylabs/cachet-monitor/cachet"
"time"
)
func main() {
config := cachet.Config
log := cachet.Logger
log.Printf("System: %s, Interval: %d second(s), API: %s\n", config.SystemName, config.Interval, config.APIUrl)
log.Printf("Starting %d monitors:\n", len(config.Monitors))
for _, mon := range config.Monitors {
log.Printf(" %s: GET %s & Expect HTTP %d\n", mon.Name, mon.URL, mon.ExpectedStatusCode)
if mon.MetricID > 0 {
log.Printf(" - Logs lag to metric id: %d\n", mon.MetricID)
}
}
log.Println()
ticker := time.NewTicker(time.Duration(config.Interval)*time.Second)
for range ticker.C {
for _, mon := range config.Monitors {
go mon.Run()
}
}
}

253
monitor.go Normal file
View File

@@ -0,0 +1,253 @@
package cachet
import (
"sync"
"time"
"github.com/Sirupsen/logrus"
)
const DefaultInterval = time.Second * 60
const DefaultTimeout = time.Second
const DefaultTimeFormat = "15:04:05 Jan 2 MST"
const HistorySize = 10
type MonitorInterface interface {
ClockStart(*CachetMonitor, MonitorInterface, *sync.WaitGroup)
ClockStop()
tick(MonitorInterface)
test() bool
Validate() []string
GetMonitor() *AbstractMonitor
Describe() []string
}
// AbstractMonitor data model
type AbstractMonitor struct {
Name string
Target string
// (default)http, tcp, dns, icmp
Type string
Strict bool
Interval time.Duration
Timeout time.Duration
MetricID int `mapstructure:"metric_id"`
ComponentID int `mapstructure:"component_id"`
// Templating stuff
Template struct {
Investigating MessageTemplate
Fixed MessageTemplate
}
// Threshold = percentage / number of down incidents
Threshold float32
ThresholdCount bool `mapstructure:"threshold_count"`
// lag / average(lagHistory) * 100 = percentage above average lag
// PerformanceThreshold sets the % limit above which this monitor will trigger degraded-performance
PerformanceThreshold float32
history []bool
lagHistory []float32
lastFailReason string
incident *Incident
config *CachetMonitor
// Closed when mon.Stop() is called
stopC chan bool
}
func (mon *AbstractMonitor) Validate() []string {
errs := []string{}
if len(mon.Name) == 0 {
errs = append(errs, "Name is required")
}
if mon.Interval < 1 {
mon.Interval = DefaultInterval
}
if mon.Timeout < 1 {
mon.Timeout = DefaultTimeout
}
if mon.Timeout > mon.Interval {
errs = append(errs, "Timeout greater than interval")
}
if mon.ComponentID == 0 && mon.MetricID == 0 {
errs = append(errs, "component_id & metric_id are unset")
}
if mon.Threshold <= 0 {
mon.Threshold = 100
}
if err := mon.Template.Fixed.Compile(); err != nil {
errs = append(errs, "Could not compile \"fixed\" template: "+err.Error())
}
if err := mon.Template.Investigating.Compile(); err != nil {
errs = append(errs, "Could not compile \"investigating\" template: "+err.Error())
}
return errs
}
func (mon *AbstractMonitor) GetMonitor() *AbstractMonitor {
return mon
}
func (mon *AbstractMonitor) Describe() []string {
features := []string{"Type: " + mon.Type}
if len(mon.Name) > 0 {
features = append(features, "Name: "+mon.Name)
}
return features
}
func (mon *AbstractMonitor) ClockStart(cfg *CachetMonitor, iface MonitorInterface, wg *sync.WaitGroup) {
wg.Add(1)
mon.config = cfg
mon.stopC = make(chan bool)
if cfg.Immediate {
mon.tick(iface)
}
ticker := time.NewTicker(mon.Interval * time.Second)
for {
select {
case <-ticker.C:
mon.tick(iface)
case <-mon.stopC:
wg.Done()
return
}
}
}
func (mon *AbstractMonitor) ClockStop() {
select {
case <-mon.stopC:
return
default:
close(mon.stopC)
}
}
func (mon *AbstractMonitor) test() bool { return false }
// TODO: test
func (mon *AbstractMonitor) tick(iface MonitorInterface) {
reqStart := getMs()
up := iface.test()
lag := getMs() - reqStart
histSize := HistorySize
if mon.ThresholdCount {
histSize = int(mon.Threshold)
}
if len(mon.history) == histSize-1 {
logrus.Warnf("%v is now saturated\n", mon.Name)
}
if len(mon.history) >= histSize {
mon.history = mon.history[len(mon.history)-(histSize-1):]
}
mon.history = append(mon.history, up)
mon.AnalyseData()
// report lag
if mon.MetricID > 0 {
go mon.config.API.SendMetric(mon.MetricID, lag)
}
}
// TODO: test
// AnalyseData decides if the monitor is statistically up or down and creates / resolves an incident
func (mon *AbstractMonitor) AnalyseData() {
// look at the past few incidents
numDown := 0
for _, wasUp := range mon.history {
if wasUp == false {
numDown++
}
}
t := (float32(numDown) / float32(len(mon.history))) * 100
l := logrus.WithFields(logrus.Fields{
"monitor": mon.Name,
"time": time.Now().Format(mon.config.DateFormat),
})
if numDown == 0 {
l.Printf("monitor is up")
} else if mon.ThresholdCount {
l.Printf("monitor down %d/%d", numDown, int(mon.Threshold))
} else {
l.Printf("monitor down %.2f%%/%.2f%%", t, mon.Threshold)
}
histSize := HistorySize
if mon.ThresholdCount {
histSize = int(mon.Threshold)
}
if len(mon.history) != histSize {
// not saturated
return
}
triggered := (mon.ThresholdCount && numDown == int(mon.Threshold)) || (!mon.ThresholdCount && t > mon.Threshold)
if triggered && mon.incident == nil {
// create incident
tplData := getTemplateData(mon)
tplData["FailReason"] = mon.lastFailReason
subject, message := mon.Template.Investigating.Exec(tplData)
mon.incident = &Incident{
Name: subject,
ComponentID: mon.ComponentID,
Message: message,
Notify: true,
}
// is down, create an incident
l.Warnf("creating incident. Monitor is down: %v", mon.lastFailReason)
// set investigating status
mon.incident.SetInvestigating()
// create/update incident
if err := mon.incident.Send(mon.config); err != nil {
l.Printf("Error sending incident: %v", err)
}
return
}
// still triggered or no incident
if triggered || mon.incident == nil {
return
}
// was down, created an incident, its now ok, make it resolved.
l.Warn("Resolving incident")
// resolve incident
tplData := getTemplateData(mon)
tplData["incident"] = mon.incident
subject, message := mon.Template.Fixed.Exec(tplData)
mon.incident.Name = subject
mon.incident.Message = message
mon.incident.SetFixed()
if err := mon.incident.Send(mon.config); err != nil {
l.Printf("Error sending incident: %v", err)
}
mon.lastFailReason = ""
mon.incident = nil
}

154
readme.md
View File

@@ -1,79 +1,71 @@
Cachet Monitor plugin
=====================
This is a monitoring plugin for CachetHQ.
![screenshot](https://castawaylabs.github.io/cachet-monitor/screenshot.png) ![screenshot](https://castawaylabs.github.io/cachet-monitor/screenshot.png)
Features Features
-------- --------
- [x] Creates & Resolves Incidents - [x] Creates & Resolves Incidents
- [x] Posts monitor lag every second * config.Interval - [x] Check URLs by response code and/or body contents
- [x] Posts monitor lag to cachet graphs
- [x] Updates Component to Partial Outage - [x] Updates Component to Partial Outage
- [x] Updates Component to Major Outage if in Partial Outage - [x] Updates Component to Major Outage if already in Partial Outage (works well with distributed monitoring)
- [x] Can be run on multiple servers and geo regions - [x] Can be run on multiple servers and geo regions
Docker Quickstart
-----------------
1. Create a configuration json
2.
```
docker run -d \
--name cachet-monitor \
-h cachet-monitor \
-v `pwd`/config.json:/etc/cachet-monitor.config.json \
castawaylabs/cachet-monitor
```
Configuration Configuration
------------- -------------
``` ```
{ {
"api_url": "https://demo.cachethq.io/api/v1", // URL for the API. Note: Must end with /api/v1
"api_token": "9yMHsdioQosnyVK4iCVR", "api_url": "https://<cachet domain>/api/v1",
"interval": 60, // Your API token for Cachet
"monitors": [ "api_token": "<cachet api token>",
{ // optional, false default, set if your certificate is self-signed/untrusted
"name": "nodegear frontend", "insecure_api": false,
"url": "https://nodegear.io/ping", "monitors": [{
"metric_id": 0, // required, friendly name for your monitor
"component_id": 0, "name": "Name of your monitor",
"threshold": 80, // required, url to probe
"expected_status_code": 200, "url": "Ping URL",
"strict_tls": true // optional, http method (defaults GET)
} "method": "get",
], // optional, http Headers to add (default none)
"insecure_api": false "headers": [
// specify Name and Value of Http-Header, eg. Authorization
{ "name": "Authorization", "value": "Basic <hash>" }
],
// self-signed ssl certificate
"strict_tls": true,
// seconds between checks
"interval": 10,
// seconds for http timeout
"timeout": 5,
// post lag to cachet metric (graph)
// note either metric ID or component ID are required
"metric_id": <metric id>,
// post incidents to this component
"component_id": <component id>,
// If % of downtime is over this threshold, open an incident
"threshold": 80,
// optional, expected status code (either status code or body must be supplied)
"expected_status_code": 200,
// optional, regular expression to match body content
"expected_body": "P.*NG"
}],
// optional, system name to identify bot (uses hostname by default)
"system_name": "",
// optional, defaults to stdout
"log_path": ""
} }
``` ```
*Notes:* Installation
------------
- `metric_id` is optional 1. Download binary from [release page](https://github.com/CastawayLabs/cachet-monitor/releases)
- `insecure_api` if true it will ignore HTTPS certificate errors (eg if self-signed) 2. Create your configuration ([example](https://raw.githubusercontent.com/CastawayLabs/cachet-monitor/master/example.config.json))
- `strict_tls` if false (true is default) it will ignore HTTPS certificate errors (eg if monitor uses self-signed certificate) 3. `cachet-monitor -c /etc/cachet-monitor.config.json`
- `component_id` is optional
- `threshold` is a percentage
- `expected_status_code` is a http response code
- GET request will be performed on the `url`
How to run pro tip: run in background using `nohup cachet-monitor 2>&1 > /var/log/cachet-monitor.log &`
----------
Example:
1. Set up [Go](https://golang.org)
2. `go get -d github.com/castawaylabs/cachet-monitor`
3. `go install github.com/castawaylabs/cachet-monitor`
4. `cachet-monitor -c https://raw.githubusercontent.com/CastawayLabs/cachet-monitor/master/example.config.json`
Production:
1. Download the example config and save to `/etc/cachet-monitor.config.json`
2. Run in background: `nohup cachet-monitor 2>&1 > /var/log/cachet-monitor.log &`
``` ```
Usage of cachet-monitor: Usage of cachet-monitor:
@@ -85,7 +77,47 @@ Usage of cachet-monitor:
Environment variables Environment variables
--------------------- ---------------------
| Name | Example Value | Description | | Name | Example Value | Description |
| ------------ | --------------------------- | --------------------------- | | ------------ | ------------------------------ | --------------------------- |
| CACHET_API | http://demo.cachethq.io/api | URL endpoint for cachet api | | CACHET_API | http://demo.cachethq.io/api/v1 | URL endpoint for cachet api |
| CACHET_TOKEN | randomvalue | API Authentication token | | CACHET_TOKEN | APIToken123 | API Authentication token |
| CACHET_DEV | 1 | Strips logging |
Vision and goals
----------------
We made this tool because we felt the need to have our own monitoring software (leveraging on Cachet).
The idea is a stateless program which collects data and pushes it to a central cachet instance.
This gives us power to have an army of geographically distributed loggers and reveal issues in both latency & downtime on client websites.
Package usage
-------------
When using `cachet-monitor` as a package in another program, you should follow what `cli/main.go` does. It is important to call `ValidateConfiguration` on `CachetMonitor` and all the monitors inside.
[API Documentation](https://godoc.org/github.com/CastawayLabs/cachet-monitor)
## License
MIT License
Copyright (c) 2016 Castaway Labs LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,24 +0,0 @@
package system
import (
"net"
"os"
)
// GetHostname returns id of the current system
func GetHostname() string {
hostname, err := os.Hostname()
if err != nil || len(hostname) == 0 {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "unknown"
}
for _, addr := range addrs {
return addr.String()
}
}
return hostname
}

15
tcp.go Normal file
View File

@@ -0,0 +1,15 @@
package cachet
type TCPMonitor struct {
AbstractMonitor `mapstructure:",squash"`
// same as output from net.JoinHostPort
// defaults to parsed config from /etc/resolv.conf when empty
DNSServer string
// Will be converted to FQDN
Domain string
Type string
// expected answers (regex)
Expect []string
}

53
template.go Normal file
View File

@@ -0,0 +1,53 @@
package cachet
import (
"bytes"
"text/template"
)
type MessageTemplate struct {
Subject string `json:"subject"`
Message string `json:"message"`
subjectTpl *template.Template
messageTpl *template.Template
}
func (t *MessageTemplate) SetDefault(d MessageTemplate) {
if len(t.Subject) == 0 {
t.Subject = d.Subject
}
if len(t.Message) == 0 {
t.Message = d.Message
}
}
// TODO: test
func (t *MessageTemplate) Compile() error {
var err error
if len(t.Subject) > 0 {
t.subjectTpl, err = compileTemplate(t.Subject)
}
if err == nil && len(t.Message) > 0 {
t.messageTpl, err = compileTemplate(t.Message)
}
return err
}
func (t *MessageTemplate) Exec(data interface{}) (string, string) {
return t.exec(t.subjectTpl, data), t.exec(t.messageTpl, data)
}
func (t *MessageTemplate) exec(tpl *template.Template, data interface{}) string {
buf := new(bytes.Buffer)
tpl.Execute(buf, data)
return buf.String()
}
func compileTemplate(text string) (*template.Template, error) {
return template.New("").Parse(text)
}