nagios

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2018 License: MIT Imports: 15 Imported by: 3

README

godoc

go-nagios

Common data structures for nagios objects + generating them from environment

Reading nagios status file

Structures are json-annotated so they can be dumped directly into JSON. Package uses RWMutex to lock data structure on update so it should also be used when concurrent access is needed.

    file, _ := os.Open(cfg.NagiosStatusFile)
    st, err := nagios.LoadStatus(file)
    fmt.Printf("parse err: %+v\n", err)
    file.Close()

to update:

    file, _ := os.Open(cfg.NagiosStatusFile)
    st.UpdateStatus(file)

Lock is only set after parsing stage so actual locked time is very short

Generating nagios commands

Raw interface (command file is value of nagios's command_file config var):

    cmd, err := NewCmd(`/var/nagios/nagios.cmd`)
    err = cmd.Cmd(nagios.CmdScheduleHostServiceDowntimeAll, "10", "20")

It is async interface and Nagios provides no sane way to check if command was actually executed so lack of error just means that write was successful, not that nagios actually did something

Creating NRPE server/client

go-nagios have only packet serdes, to use it as client/server you need to wrap it. Simplest concurrent server looks like this:

package main

import (
    "fmt"
    "net"
    "github.com/efigence/go-nagios"
)

func main() {
    sock, _ := net.Listen("tcp", ":5666")
    for {
        conn, _ := sock.Accept()
        go func(conn net.Conn) {
            req, _ := nagios.ReadNrpe(conn)
            msg, _ := req.GetMessage()
            fmt.Printf("request: %s\n", msg)
            var resp nagios.NrpePacket
            resp.SetMessage("OK")
            resp.PrepareResponse()
            // send response
            resp.Generate(conn)
            // and close
            conn.Close()

        } (conn)
    }
}

Currently the encryption used by NRPE by default is not suppoted in go (anonymous DH/ECDH which is vulnerable to MITM) but latest NRPE have ability to use supporte

Documentation

Overview

Host definition

Service definition

Index

Examples

Constants

View Source
const (
	CmdAcknowledgeHostProblem    = "ACKNOWLEDGE_HOST_PROBLEM"
	CmdAcknowledgeServiceProblem = "ACKNOWLEDGE_SVC_PROBLEM"
	// Schedule downtime and propagate to children
	CmdScheduleRecursiveDowntime = "SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME"

	// Schedule downtime and propagate to childrenon trigger
	CmdScheduleRecursiveTriggeredDowntime = "SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME"
	CmdScheduleForcedHostCheck            = "SCHEDULE_FORCED_HOST_CHECK"
	CmdScheduleForcedServiceCheckAll      = "SCHEDULE_FORCED_HOST_SVC_CHECKS"
	CmdScheduleForcedServiceCheck         = "SCHEDULE_FORCED_SVC_CHECK"

	// Schedule downtime of all hosts in hostgroup
	CmdScheduleHostgroupHostsDowntime = "SCHEDULE_HOSTGROUP_HOST_DOWNTIME"

	// Schedule downtime of all services on hosts in hostgroup
	CmdScheduleHostgroupServiceDowntime = "SCHEDULE_HOSTGROUP_SVC_DOWNTIME"
	CmdScheduleHostCheck                = "SCHEDULE_HOST_CHECK"
	CmdScheduleHostDowntime             = "SCHEDULE_HOST_DOWNTIME"
	CmdScheduleHostServiceCheckAll      = "SCHEDULE_HOST_SVC_CHECKS"
	CmdScheduleHostServiceDowntimeAll   = "SCHEDULE_HOST_SVC_DOWNTIME"

	// schedule downtime for all hosts that have service in servicegroup
	CmdScheduleServicegroupHostDowntime = "SCHEDULE_SERVICEGROUP_HOST_DOWNTIME"

	// schedule downtime for all services in the servicegroup
	CmdScheduleServicegroupServiceDowntime = "SCHEDULE_SERVICEGROUP_SVC_DOWNTIME"
	CmdScheduleServiceCheck                = "SCHEDULE_SVC_CHECK"
	CmdScheduleServiceDowntime             = "SCHEDULE_SVC_DOWNTIME"

	// Process passive checks
	CmdProcessHostCheckResult    = "PROCESS_HOST_CHECK_RESULT"
	CmdProcessServiceCheckResult = "PROCESS_SERVICE_CHECK_RESULT"
)
View Source
const (
	NrpeTypeQuery    = 1
	NrpeTypeResponse = 2
)

Nrpe packet types

View Source
const NRPE_MAX_PACKETBUFFER_LENGTH = 1024 // this length is hardcoded in nrpe.c
View Source
const NrpePacketSize = 1036 // struct size + 2 bytes. No idea why, but nrpe C client requires it
View Source
const StateCritical = "CRITICAL"
View Source
const StateDown = "DOWN"
View Source
const StateOk = "OK"
View Source
const StateUnknown = "UNKNOWN"
View Source
const StateUnreachable = "UNREACHABLE"
View Source
const StateUp = "UP"
View Source
const StateWarning = "WARNING"

Variables

This section is empty.

Functions

func DecodeNagiosCmd added in v0.0.2

func DecodeNagiosCmd(cmd string) (name string, args []string, err error)

func EncodeHostCheck added in v0.0.2

func EncodeHostCheck(h Host) string

Encode host status into host check string (without PASSIVE_HOST_CHECK_RESULT header)

func EncodeServiceCheck added in v0.0.2

func EncodeServiceCheck(s Service) string

Types

type Command added in v0.0.2

type Command struct {
	Filename string
	// contains filtered or unexported fields
}

func NewCmd added in v0.0.2

func NewCmd(file string) (c *Command, err error)

NewCmd() creats command interface to a given command file. It should already exist (FIFO created by nagios)

func (*Command) Cmd added in v0.0.2

func (cmd *Command) Cmd(command string, params ...string) (err error)

func (*Command) Send added in v0.0.2

func (cmd *Command) Send(command string, params ...string) (err error)

type CommonFields added in v0.0.2

type CommonFields struct {
	sync.RWMutex
	Hostname             string    `json:"hostname,omitempty"`
	DisplayName          string    `json:"display_name,omitempty"`
	CheckMessage         string    `json:"check_message,omitempty"`
	State                string    `json:"state,omitempty"`
	PreviousState        string    `json:"previous_state,omitempty"`
	LastCheck            time.Time `json:"last_check,omitempty"`
	NextCheck            time.Time `json:"next_check,omitempty"`
	LastHardStateChange  time.Time `json:"last_hard_state_change,omitempty"`
	LastStateChange      time.Time `json:"last_state_change,omitempty"`
	StateHard            bool      `json:"state_hard"`
	Acknowledged         bool      `json:"ack"`
	Flapping             bool      `json:"flapping"`
	Downtime             bool      `json:"downtime"`
	NotificationsEnabled bool      `json:"notifications_enabled"`
}

update fields shared by host and service

func (*CommonFields) UpdateCommonFromMap added in v0.0.2

func (c *CommonFields) UpdateCommonFromMap(m map[string]string, dataType int) error

update common fields of service/host dataType should be either isService or isHost

func (*CommonFields) UpdateStatus added in v0.0.2

func (c *CommonFields) UpdateStatus(status string, message string)

type Host

type Host struct {
	CommonFields
	HostGroups []string `json:"hostgroups"`
	Address    string   `json:"address"`
	Parents    *[]Host  `json:"parents"`
}

func DecodeHostCheck added in v0.0.2

func DecodeHostCheck(check string) (Host, error)

Decode host check string

func NewHost

func NewHost() Host

func NewHostFromArgs added in v0.0.2

func NewHostFromArgs(args []string) (Host, error)

NewHostFromArgs creates host from nagios cmd args slice

func NewHostFromEnv

func NewHostFromEnv() (Host, error)

Create host object from nagios env variables

func NewHostFromMap added in v0.0.2

func NewHostFromMap(m map[string]string) (Host, error)

func (*Host) MarshalCmd added in v0.0.2

func (h *Host) MarshalCmd() string

type HostCount added in v0.0.2

type HostCount struct {
	All          int `json:"all"`
	Up           int `json:"up"`
	Down         int `json:"down"`
	Unreachable  int `json:"unreachable"`
	Downtime     int `json:"downtime"`
	Acknowledged int `json:"ack"`
}

type Notification

type Notification struct {
	Host                 Host          `json:"hostname"`
	Service              Service       `json:"service,omitempty"`
	Type                 string        `json:"type"`
	Recipients           []string      `json:"recipients,omitempty"`
	HostState            string        `json:"host_state"`
	HostStateHard        bool          `json:"host_state_hard"`
	HostStateDuration    time.Duration `json:"host_state_duration"`
	ServiceState         string        `json:"service_state,omitempty"`
	ServiceStateHard     bool          `json:"sevice_state_hard,omitempty"`
	ServiceStateDuration time.Duration `json:"service_state_duration,omitempty"`
	IsHost               bool          `json:"is_host,omitempty"`
	IsService            bool          `json:"is_service,omitempty"`
}

Notification types:

*

func NewNotification

func NewNotification() Notification

func NewNotificationFromEnv

func NewNotificationFromEnv() (Notification, error)

Create notification from env passed by nagios Intended to be used with nagios notification command

type NrpeConfig added in v0.0.2

type NrpeConfig struct {
	Config  map[string]string
	Command map[string]string
}

func ParseNrpeConfig added in v0.0.2

func ParseNrpeConfig(data io.Reader) (cfg NrpeConfig, err error)

Limitations: only key-value config so you can have config with only one include and only one include_dir

type NrpePacket added in v0.0.2

type NrpePacket struct {
	Version    int16
	Type       int16
	Crc        uint32
	ResultCore int16
	Buffer     [NRPE_MAX_PACKETBUFFER_LENGTH]byte
	Tail       [2]byte // doesn't work without it, even if common.h packet struct says it should be 1024, it only works when total buffer is 1026 bytes
}
Example
sock, _ := net.Listen("tcp", ":5666")
for {
	conn, _ := sock.Accept()
	go func(conn net.Conn) {
		req, _ := ReadNrpe(conn)
		msg, _ := req.GetMessage()
		fmt.Printf("request: %s\n", msg)
		var resp NrpePacket
		resp.SetMessage("OK")
		resp.PrepareResponse()
		// send response
		resp.Generate(conn)
		// and close
		conn.Close()

	}(conn)
}
Output:

func ReadNrpe added in v0.0.2

func ReadNrpe(r io.Reader) (p *NrpePacket, err error)

func ReadNrpeBytes added in v0.0.2

func ReadNrpeBytes(b []byte) (p *NrpePacket, err error)

func (*NrpePacket) CheckCRC added in v0.0.2

func (r *NrpePacket) CheckCRC()

func (*NrpePacket) Generate added in v0.0.2

func (r *NrpePacket) Generate(w io.Writer) (err error)

func (*NrpePacket) GenerateBytes added in v0.0.2

func (r *NrpePacket) GenerateBytes() (b []byte, err error)

func (*NrpePacket) GetMessage added in v0.0.2

func (r *NrpePacket) GetMessage() (str string, err error)

func (*NrpePacket) PrepareRequest added in v0.0.2

func (r *NrpePacket) PrepareRequest() (err error)

calculate crc, set version and type Should be called before generating packet

func (*NrpePacket) PrepareResponse added in v0.0.2

func (r *NrpePacket) PrepareResponse() (err error)

func (*NrpePacket) SetMessage added in v0.0.2

func (r *NrpePacket) SetMessage(msg string) (err error)

max 1023 BYTES(not characters), it WILL truncate it if you add more

type Service

type Service struct {
	CommonFields
	Description   string   `json:"description,omitempty"`
	ServiceGroups []string `json:"servicegroups,omitempty"` // list of service groups this service belongs to
	Volatile      bool     `json:"volatile,omitempty"`
	Contacts      []string `json:"contacts,omitempty"`      // list of service contacts
	ContactGroups []string `json:"contactgroups,omitempty"` // list of service contact groups
}

func DecodeServiceCheck added in v0.0.2

func DecodeServiceCheck(check string) (Service, error)

func NewService

func NewService() Service

func NewServiceFromArgs added in v0.0.2

func NewServiceFromArgs(args []string) (Service, error)

func NewServiceFromEnv

func NewServiceFromEnv() (Service, error)

create service from nagios env variables

func NewServiceFromMap added in v0.0.2

func NewServiceFromMap(m map[string]string) (Service, error)

Generate service data from key/value pairs in "status.dat" format

func (*Service) MarshalCmd added in v0.0.2

func (s *Service) MarshalCmd() string

type ServiceCount added in v0.0.2

type ServiceCount struct {
	All          int `json:"all"`
	Ok           int `json:"ok"`
	Warning      int `json:"warning"`
	Critical     int `json:"critical"`
	Unknown      int `json:"unknown"`
	Downtime     int `json:"downtime"`
	Acknowledged int `json:"ack"`
}

type Status added in v0.0.2

type Status struct {
	Host    map[string]Host               `json:"host"`
	Service map[string]map[string]Service `json:"service"`
	Summary Summary                       `json:"summary"`
	sync.RWMutex
}

func LoadStatus added in v0.0.2

func LoadStatus(r io.Reader) (Status, error)

func (*Status) UpdateStatus added in v0.0.2

func (s *Status) UpdateStatus(r io.Reader) error

type Summary added in v0.0.2

type Summary struct {
	HostCount    `json:"all_host"`
	ServiceCount `json:"all_service"`
}

func (*Summary) UpdateHost added in v0.0.2

func (sum *Summary) UpdateHost(hosts map[string]Host) error

func (*Summary) UpdateService added in v0.0.2

func (sum *Summary) UpdateService(services map[string]map[string]Service) error

Jump to

Keyboard shortcuts

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