health

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2023 License: MIT Imports: 10 Imported by: 1

README

health

import "codeberg.org/mgkeller/go-health"

Overview

Package health provides standardized means for generating healthchecks, and consuming them from JSON. The included schema files allow for validation of generation, regardless of the source.

Index

Package files

checksandmetrics.go health.go schema.go status.go statusregistry.go

Constants

const (
    OK       = StatusString("OK")
    UP       = StatusString("UP")
    WARNING  = StatusString("WARNING")
    BAD      = StatusString("BAD")
    DOWN     = StatusString("DOWN")
    CRITICAL = StatusString("CRITICAL")
    UNKNOWN  = StatusString("UNKNOWN")
    ERROR    = StatusString("ERROR")
)

Status constants to prevent fat-fingered-oopsies

Variables

var (
    // ErrNoSuchEntryError is returned when the requested element does not exist in the Registry
    ErrNoSuchEntryError = errors.New("no such element exists")
)
var SchemaJSON = []byte(`
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "http://example.com/product.schema.json",
    "title": "Go Healthcheck",
    "description": "The Go Healthcheck (health.Check) is output by HTTP services wishing to provide consumable healthcheck output",
    "type": "object",
    "properties": {
        "overallStatus": {
      "description": "The declared status of the system",
      "type": "string",
      "enum": [
        "OK",
        "WARNING",
        "ERROR",
                "BAD",
                "CRITICAL",
                "UNKNOWN"
      ]
    },
    "metrics": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/metric"
      }
    },
    "services": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/service"
      }
    },
    "systems": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/system"
      }
    }
  },
  "required": [
    "overallStatus"
  ],
  "definitions": {
    "health": {
      "type": "object",
      "required": [
        "name"
      ],
      "additionalProperties": true,
      "properties": {
        "name": {
          "type": "string",
          "description": "The name of the service"
        },
        "status": {
          "description": "The declared status of the service",
          "type": "string",
          "enum": [
            "OK",
                        "UP",
            "WARNING",
                        "ERROR",
                        "BAD",
                        "DOWN",
                        "CRITICAL",
                        "UNKNOWN"
          ]
        },
        "timeStamp": {
          "description": "The UNIX epoch timestamp for when this value was last fetched",
          "type": ["integer", "null"]
        },
        "timeout": {
          "description": "The number of milliseconds allowed to lapse between 'timeStamp' and 'now' before the metric is declared stale",
          "type": ["integer", "null"]
        },
        "message": {
            "type": ["string", "null"],
          "description": "A message explaining why the status is what it is (often exception message)"
        }
      }
    },
    "metric": {
      "type": "object",
      "required": [
        "name",
        "value"
      ],
      "extends" : {
        "$ref": "#/definitions/health"
      },
      "allOf": [{ "$ref": "#/definitions/health" }],
      "additionalProperties": true,
      "properties": {
        "value": {
          "description": "The current value for this metric",
          "type": "number"
        },
        "expectedValue": {
          "description": "The declared value that was expected for this metric",
          "type": ["number", "null"]
        },
        "minValue": {
          "description": "The declared minimum value that for this metric (graph floor)",
          "type": ["number", "null"]
        },
        "maxValue": {
          "description": "The declared maximum value that for this metric (graph ceiling)",
          "type": ["number", "null"]
        },
        "warnOver": {
          "description": "The value at which exceeding values generate WARNING status (graph yellow-line)",
          "type": ["number", "null"]
        },
        "badOver": {
          "description": "The value at which exceeding values generate CRITICAL status (graph red-line)",
          "type": ["number", "null"]
        }
      }
    },
    "service": {
      "type": "object",
      "required": [
        "name",
        "status"
      ],
      "extends" : {
        "$ref": "#/definitions/health"
      },
      "allOf": [{ "$ref": "#/definitions/health" }],
      "additionalProperties": true,
      "properties": {
      }
    },
    "system": {
      "type": "object",
      "required": [
        "name"
      ],
      "extends" : {
        "$ref": "#/definitions/health"
      },
      "allOf": [{ "$ref": "#/definitions/health" }],
      "additionalProperties": true,
      "properties": {
      }
    }
  }
}
`)

SchemaJSON was generated from schema.json at Sun Apr 17 12:23:48 PM EDT 2022

func Checks

func Checks(n *nagios.Nagios, maxAge int64, checkMap []interface{}, noisy bool)

Checks takes a status document, escalate the status, and appends Nagios-compatible information to the message

func Metrics

func Metrics(n *nagios.Nagios, checkMap []interface{}, noisy bool)

Metrics takes a "metrics" document and appends Nagios-compatible metrics information to the message

func SafeLabel

func SafeLabel(label string) string

SafeLabel returns a label that is safe to use with modern RRD

func ValidateJSON

func ValidateJSON(jsonBody string) error

ValidateJSON runs provided JSON against the JSON-Schema validator

type Check

type Check struct {
    // OverallStatus must be one of OK,WARNING,BAD/ERROR/CRITICAL, or UNKNOWN
    OverallStatus string                 `json:"overallStatus,omitempty"`
    Services      []Status               `json:"services,omitempty"`
    Systems       []Status               `json:"systems,omitempty"`
    Metrics       []Status               `json:"metrics,omitempty"`
    Properties    map[string]interface{} `json:"properties,omitempty"`
}

Check is a type used to define healthcheck statuses

func NewCheck
func NewCheck() Check

NewCheck returns an empty Check

func NewCheckfromJSON
func NewCheckfromJSON(hcjson []byte) (Check, error)

NewCheckfromJSON returns an Check populated from an Check JSON

func (*Check) AddMetric
func (s *Check) AddMetric(status *Status)

AddMetric adds the provided Status to the Metrics array

func (*Check) AddService
func (s *Check) AddService(status *Status)

AddService adds the provided Status to the Services array

func (*Check) AddSystem
func (s *Check) AddSystem(status *Status)

AddSystem adds the provided Status to the Systems array

func (*Check) Calculate
func (s *Check) Calculate()

Calculate walks the tree and updates OverallStatus if applicable

func (*Check) JSON
func (s *Check) JSON() string

JSON returns the JSON-encoded version of the Check

func (*Check) Merge
func (s *Check) Merge(hc *Check)

Merge integrates one Check into this Check. Does not merge metrics. Does not dedupe

func (*Check) PrefixedMerge
func (s *Check) PrefixedMerge(prefix string, hc *Check)

PrefixedMerge integrates one Check into this Check, prefixing all named items in the source hc before merging.

func (*Check) Terse
func (s *Check) Terse() string

Terse returns the JSON-encoded version of just the overall status of the Check

func (*Check) Validate
func (s *Check) Validate() error

Validate runs the Check.JSON() output against a JSON-Schema validator

type JSON

type JSON map[string]interface{}

JSON is an encapsulating type for "jmap"-based structures

type Status

type Status struct {
    // Name is univerally required
    Name string `json:"name,omitempty"`
    // Status is universally required, one of: OK,WARNING,
    // BAD/ERROR/CRITICAL, or UNKNOWN
    Status string `json:"status,omitempty"`
    // Value is optional for all but Metrics, and is used to convey a
    // numeric-type representation
    Value interface{} `json:"value,omitempty"`
    // ExpectedValue is optional, generally used with Services to represent what
    // Value should be, to understand deviations
    ExpectedValue interface{} `json:"expectedValue,omitempty"`
    // WarnOver is only for Metrics, and is used to represent the Value at which a
    // WARNING state will be triggered
    WarnOver interface{} `json:"warnOver,omitempty"`
    // BadOver is ony for Metrics, and is used to represent the Value at which a
    // CRITICAL state will be triggered
    BadOver interface{} `json:"badOver,omitempty"`
    // TimeStamp is optional, and is used to convey the time the Status or Value
    // was retrieved
    TimeStamp *time.Time `json:"timestamp,omitempty"`
    // TimeOut is optional, and is used to set the amount of time TimeStamp can
    // drift before it is considered stale, tiggering an alert
    TimeOut *time.Duration `json:"timeout,omitempty"`
    // Suffix is optional, and is used appended to Value for metrics
    Suffix string `json:"suffix,omitempty"`
}

Status is a type used to convey status-related information about a Service, System, or Metric

func StatusSliceFromJmap
func StatusSliceFromJmap(jmap []interface{}) []Status

StatusSliceFromJmap is a hacky function that might take a slice of interfaces, and return a same-sized slice of Status

func (*Status) MarshalJSON
func (s *Status) MarshalJSON() ([]byte, error)

MarshalJSON is a custom marshaller for JSON encoding, to output TimeStamp and TimeOut as numbers instead of pretty strings.

func (*Status) MetricString
func (s *Status) MetricString() string

MetricString returns a Nagios Performance Data -compatible representation of Status

type StatusRegistry

type StatusRegistry struct {
    sync.RWMutex
    // contains filtered or unexported fields
}

StatusRegistry is a gorosafe map of services to their Status objects

func NewStatusRegistry
func NewStatusRegistry() *StatusRegistry

NewStatusRegistry returns an initialized StatusRegistry

func (*StatusRegistry) Add
func (s *StatusRegistry) Add(name, status string, Value, ExpectedValue interface{})

Add or update an entry in StatusRegistry

func (*StatusRegistry) Get
func (s *StatusRegistry) Get(name string) (*Status, error)

Get returns the requested Status, or ErrNoSuchEntryError

func (*StatusRegistry) Keys
func (s *StatusRegistry) Keys() []string

Keys returns a list of names from the StatusRegistry

func (*StatusRegistry) Remove
func (s *StatusRegistry) Remove(name string)

Remove an entry from the StatusRegistry

type StatusString

type StatusString = string

StatusString is a string type for static string consistency


Generated by godoc2md

Documentation

Overview

Package health provides standardized means for generating healthchecks, and consuming them from JSON. The included schema files allow for validation of generation, regardless of the source.

Index

Constants

View Source
const (
	OK       = StatusString("OK")
	UP       = StatusString("UP")
	WARNING  = StatusString("WARNING")
	BAD      = StatusString("BAD")
	DOWN     = StatusString("DOWN")
	CRITICAL = StatusString("CRITICAL")
	UNKNOWN  = StatusString("UNKNOWN")
	ERROR    = StatusString("ERROR")
)

Status constants to prevent fat-fingered-oopsies

Variables

View Source
var (
	// ErrNoSuchEntryError is returned when the requested element does not exist in the Registry
	ErrNoSuchEntryError = errors.New("no such element exists")
)
View Source
var SchemaJSON = []byte(`
{
	"$schema": "http://json-schema.org/draft-07/schema#",
	"$id": "http://example.com/product.schema.json",
	"title": "Go Healthcheck",
	"description": "The Go Healthcheck (health.Check) is output by HTTP services wishing to provide consumable healthcheck output",
	"type": "object",
	"properties": {
		"overallStatus": {
      "description": "The declared status of the system",
      "type": "string",
      "enum": [
        "OK",
        "WARNING",
        "ERROR",
				"BAD",
				"CRITICAL",
				"UNKNOWN"
      ]
    },
    "metrics": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/metric"
      }
    },
    "services": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/service"
      }
    },
    "systems": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/system"
      }
    }
  },
  "required": [
    "overallStatus"
  ],
  "definitions": {
    "health": {
      "type": "object",
      "required": [
        "name"
      ],
      "additionalProperties": true,
      "properties": {
        "name": {
          "type": "string",
          "description": "The name of the service"
        },
        "status": {
          "description": "The declared status of the service",
          "type": "string",
          "enum": [
            "OK",
						"UP",
            "WARNING",
						"ERROR",
						"BAD",
						"DOWN",
						"CRITICAL",
						"UNKNOWN"
          ]
        },
        "timeStamp": {
          "description": "The UNIX epoch timestamp for when this value was last fetched",
          "type": ["integer", "null"]
        },
        "timeout": {
          "description": "The number of milliseconds allowed to lapse between 'timeStamp' and 'now' before the metric is declared stale",
          "type": ["integer", "null"]
        },
        "message": {
            "type": ["string", "null"],
          "description": "A message explaining why the status is what it is (often exception message)"
        }
      }
    },
    "metric": {
      "type": "object",
      "required": [
        "name",
        "value"
      ],
      "extends" : {
        "$ref": "#/definitions/health"
      },
      "allOf": [{ "$ref": "#/definitions/health" }],
      "additionalProperties": true,
      "properties": {
        "value": {
          "description": "The current value for this metric",
          "type": "number"
        },
        "expectedValue": {
          "description": "The declared value that was expected for this metric",
          "type": ["number", "null"]
        },
        "minValue": {
          "description": "The declared minimum value that for this metric (graph floor)",
          "type": ["number", "null"]
        },
        "maxValue": {
          "description": "The declared maximum value that for this metric (graph ceiling)",
          "type": ["number", "null"]
        },
        "warnOver": {
          "description": "The value at which exceeding values generate WARNING status (graph yellow-line)",
          "type": ["number", "null"]
        },
        "badOver": {
          "description": "The value at which exceeding values generate CRITICAL status (graph red-line)",
          "type": ["number", "null"]
        }
      }
    },
    "service": {
      "type": "object",
      "required": [
        "name",
        "status"
      ],
      "extends" : {
        "$ref": "#/definitions/health"
      },
      "allOf": [{ "$ref": "#/definitions/health" }],
      "additionalProperties": true,
      "properties": {
      }
    },
    "system": {
      "type": "object",
      "required": [
        "name"
      ],
      "extends" : {
        "$ref": "#/definitions/health"
      },
      "allOf": [{ "$ref": "#/definitions/health" }],
      "additionalProperties": true,
      "properties": {
      }
    }
  }
}
`)

SchemaJSON was generated from schema.json at Sun Apr 17 12:23:48 PM EDT 2022

Functions

func Checks

func Checks(n *nagios.Nagios, maxAge int64, checkMap []interface{}, noisy bool)

Checks takes a status document, escalate the status, and appends Nagios-compatible information to the message

func Metrics

func Metrics(n *nagios.Nagios, checkMap []interface{}, noisy bool)

Metrics takes a "metrics" document and appends Nagios-compatible metrics information to the message

func SafeLabel

func SafeLabel(label string) string

SafeLabel returns a label that is safe to use with modern RRD

func ValidateJSON

func ValidateJSON(jsonBody string) error

ValidateJSON runs provided JSON against the JSON-Schema validator

Types

type Check

type Check struct {
	// OverallStatus must be one of OK,WARNING,BAD/ERROR/CRITICAL, or UNKNOWN
	OverallStatus string                 `json:"overallStatus,omitempty"`
	Services      []Status               `json:"services,omitempty"`
	Systems       []Status               `json:"systems,omitempty"`
	Metrics       []Status               `json:"metrics,omitempty"`
	Properties    map[string]interface{} `json:"properties,omitempty"`
}

Check is a type used to define healthcheck statuses

func NewCheck

func NewCheck() Check

NewCheck returns an empty Check

func NewCheckfromJSON

func NewCheckfromJSON(hcjson []byte) (Check, error)

NewCheckfromJSON returns an Check populated from an Check JSON

func (*Check) AddMetric

func (s *Check) AddMetric(status *Status)

AddMetric adds the provided Status to the Metrics array

func (*Check) AddService

func (s *Check) AddService(status *Status)

AddService adds the provided Status to the Services array

func (*Check) AddSystem

func (s *Check) AddSystem(status *Status)

AddSystem adds the provided Status to the Systems array

func (*Check) Calculate

func (s *Check) Calculate()

Calculate walks the tree and updates OverallStatus if applicable

func (*Check) JSON

func (s *Check) JSON() string

JSON returns the JSON-encoded version of the Check

func (*Check) Merge

func (s *Check) Merge(hc *Check)

Merge integrates one Check into this Check. Does not merge metrics. Does not dedupe

func (*Check) PrefixedMerge

func (s *Check) PrefixedMerge(prefix string, hc *Check)

PrefixedMerge integrates one Check into this Check, prefixing all named items in the source hc before merging.

func (*Check) Terse

func (s *Check) Terse() string

Terse returns the JSON-encoded version of just the overall status of the Check

func (*Check) Validate

func (s *Check) Validate() error

Validate runs the Check.JSON() output against a JSON-Schema validator

type JSON

type JSON map[string]interface{}

JSON is an encapsulating type for "jmap"-based structures

type Status

type Status struct {
	// Name is univerally required
	Name string `json:"name,omitempty"`
	// Status is universally required, one of: OK,WARNING,
	// BAD/ERROR/CRITICAL, or UNKNOWN
	Status string `json:"status,omitempty"`
	// Value is optional for all but Metrics, and is used to convey a
	// numeric-type representation
	Value interface{} `json:"value,omitempty"`
	// ExpectedValue is optional, generally used with Services to represent what
	// Value should be, to understand deviations
	ExpectedValue interface{} `json:"expectedValue,omitempty"`
	// WarnOver is only for Metrics, and is used to represent the Value at which a
	// WARNING state will be triggered
	WarnOver interface{} `json:"warnOver,omitempty"`
	// BadOver is ony for Metrics, and is used to represent the Value at which a
	// CRITICAL state will be triggered
	BadOver interface{} `json:"badOver,omitempty"`
	// TimeStamp is optional, and is used to convey the time the Status or Value
	// was retrieved
	TimeStamp *time.Time `json:"timestamp,omitempty"`
	// TimeOut is optional, and is used to set the amount of time TimeStamp can
	// drift before it is considered stale, tiggering an alert
	TimeOut *time.Duration `json:"timeout,omitempty"`
	// Suffix is optional, and is used appended to Value for metrics
	Suffix string `json:"suffix,omitempty"`
}

Status is a type used to convey status-related information about a Service, System, or Metric

func StatusSliceFromJmap

func StatusSliceFromJmap(jmap []interface{}) []Status

StatusSliceFromJmap is a hacky function that might take a slice of interfaces, and return a same-sized slice of Status

func (*Status) MarshalJSON

func (s *Status) MarshalJSON() ([]byte, error)

MarshalJSON is a custom marshaller for JSON encoding, to output TimeStamp and TimeOut as numbers instead of pretty strings.

func (*Status) MetricString

func (s *Status) MetricString() string

MetricString returns a Nagios Performance Data -compatible representation of Status

type StatusRegistry

type StatusRegistry struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

StatusRegistry is a gorosafe map of services to their Status objects

func NewStatusRegistry

func NewStatusRegistry() *StatusRegistry

NewStatusRegistry returns an initialized StatusRegistry

func (*StatusRegistry) Add

func (s *StatusRegistry) Add(name, status string, Value, ExpectedValue interface{})

Add or update an entry in StatusRegistry

func (*StatusRegistry) Get

func (s *StatusRegistry) Get(name string) (*Status, error)

Get returns the requested Status, or ErrNoSuchEntryError

func (*StatusRegistry) Keys

func (s *StatusRegistry) Keys() []string

Keys returns a list of names from the StatusRegistry

func (*StatusRegistry) Remove

func (s *StatusRegistry) Remove(name string)

Remove an entry from the StatusRegistry

type StatusString

type StatusString = string

StatusString is a string type for static string consistency

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL