ayd

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2022 License: MIT Imports: 12 Imported by: 7

Documentation

Overview

The library for making Ayd plugin or client.

Example (AlertPlugin)
args, err := ayd.ParseAlertPluginArgs()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

logger := ayd.NewLogger(args.AlertURL).StartTimer()

// send alert to somewhere

logger.Healthy("alert sent")
Example (ApiClient)
aydURL, _ := url.Parse("http://localhost:9000")

// fetch status from Ayd server
report, err := ayd.Fetch(aydURL)
if err != nil {
	panic(err)
}

for target, status := range report.ProbeHistory {
	// show target name
	fmt.Printf("# %s\n", target)

	// show status history
	for _, x := range status.Records {
		fmt.Println(x.Status)
	}
}
Example (ProbePlugin)
args, err := ayd.ParseProbePluginArgs()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

logger := ayd.NewLogger(args.TargetURL).StartTimer()

// check your target here
ok := true

if ok {
	logger.Healthy("target is healthy!")
} else {
	logger.Failure("target is down")
}

Index

Examples

Constants

View Source
const (
	// StatusFailure means the target is in FAILURE, but status check is success.
	// System administrators have to do something action to the target system when this status.
	StatusFailure Status = -2

	// StatusDegrade means success to status check and the target is worked but partially features or stability is DEGRADE.
	// System administrators have to do something action to the target system when this status, but might not urgency.
	StatusDegrade = -1

	// StatusUnknown means UNKNOWN current status because failed to check the target status.
	// System administrators have to fix Ayd settings, or do something to the target system, when this status.
	StatusUnknown = 0

	// StatusAborted means the status check ABORTED because stop by system administrator or other system program like systemd.
	// System administrators don't have to do something on this status.
	StatusAborted = 1

	// StatusHealthy means success to status check and the target is HEALTHY.
	StatusHealthy = 2
)

Variables

View Source
var (
	// ErrInvalidArgument is a error for if the argument was wrong.
	ErrInvalidArgumentValue = errors.New("invalid argument value")

	// ErrArgumentCount is a error for if the count of arguments was wrong.
	ErrArgumentCount = errors.New("unexpected count of arguments")

	// ErrCommunicate is a error for if connect or communicate with the Ayd server.
	ErrCommunicate = errors.New("server communication error")

	// ErrInvalidRecord is a error for if failed to parse log because it was invalid format.
	ErrInvalidRecord = errors.New("invalid record")

	// ErrIO is a error for if failed to wread/write log.
	ErrIO = errors.New("failed to read/write log")

	// ErrEmptyTarget is a error for if the target URL of Record was empty.
	ErrEmptyTarget = errors.New("invalid record: the target URL is required")
)

The errors in Ayd library can check the error type via errors.Is function.

Functions

func SortProbeHistories added in v0.10.0

func SortProbeHistories(hs []ProbeHistory)

SortProbeHistories sorts list of ProbeHistory by latest status and target URL.

This function will edit slice directly.

Types

type AlertPluginArgs

type AlertPluginArgs struct {
	AlertURL  *url.URL
	CheckedAt time.Time
	Status    Status
	Latency   time.Duration
	TargetURL *url.URL
	Message   string
}

AlertPluginArgs is arguments for alert plugin

func ParseAlertPluginArgs

func ParseAlertPluginArgs() (AlertPluginArgs, error)

ParseAlertPluginArgs is get arguments for alert plugin

This function is shorthand of `ayd.ParseAlertPluginArgs(os.Args)`.

func ParseAlertPluginArgsFrom

func ParseAlertPluginArgsFrom(args []string) (AlertPluginArgs, error)

ParseAlertPluginArgsFrom is parse arguments for alert plugin

type Incident

type Incident struct {
	Target *URL

	Status Status

	Message string

	// CausedAt is the first detected time the target is unhealthy status
	CausedAt time.Time

	// ResolvedAt is the earliest time that detected the target back to healthy status
	ResolvedAt time.Time
}

Incident is a period of failure or unknown status that has the same status and message

func (Incident) MarshalJSON added in v0.10.0

func (i Incident) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Incident) UnmarshalJSON added in v0.10.0

func (i *Incident) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type LogScanner added in v0.14.0

type LogScanner interface {
	// Close closes the scanner.
	Close() error

	// Scan scans the next line of log. If there is no more log, it returns false.
	Scan() bool

	// Record returns current record.
	Record() Record
}

LogScanner is the interface to read ayd's log format.

func NewLogScanner added in v0.14.0

func NewLogScanner(f io.ReadCloser) LogScanner

NewLogScanner creates a new LogScanner from io.ReadCloser.

Example
f := io.NopCloser(strings.NewReader(`
2001-02-03T16:05:06Z	HEALTHY	1.234	https://example.com	200 OK
2001-02-03T16:15:06Z	HEALTHY	2.345	https://example.com	200 OK
2001-02-03T16:25:06Z	HEALTHY	3.456	https://example.com	200 OK
`))

s := ayd.NewLogScanner(f)
defer s.Close()

for s.Scan() {
	fmt.Println(s.Record().CheckedAt)
}
Output:

2001-02-03 16:05:06 +0000 UTC
2001-02-03 16:15:06 +0000 UTC
2001-02-03 16:25:06 +0000 UTC

func NewLogScannerWithPeriod added in v0.14.0

func NewLogScannerWithPeriod(f io.ReadCloser, since, until time.Time) LogScanner

NewLogScannerWithPeriod creates a new LogScanner from io.ReadCloser, with period specification.

Example
f := io.NopCloser(strings.NewReader(`
2001-02-03T16:05:06Z	HEALTHY	1.234	https://example.com	200 OK
2001-02-03T16:15:06Z	HEALTHY	2.345	https://example.com	200 OK
2001-02-03T16:25:06Z	HEALTHY	3.456	https://example.com	200 OK
`))

s := ayd.NewLogScannerWithPeriod(
	f,
	time.Date(2001, 2, 3, 16, 7, 0, 0, time.UTC),
	time.Date(2001, 2, 3, 16, 25, 0, 0, time.UTC),
)
defer s.Close()

for s.Scan() {
	fmt.Println(s.Record().CheckedAt)
}
Output:

2001-02-03 16:15:06 +0000 UTC

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is the logger for Ayd plugin

Example
target, _ := url.Parse("foobar:your-plugin-url")

logger := ayd.NewLogger(target)

logger.Healthy("hello world")
Example (SetExtraValues)
logger := ayd.NewLogger(nil)

// change target URL
target, _ := url.Parse("foobar:your-plugin-url")
logger = logger.WithTarget(target)

// set check time and latency of the target
startTime, _ := time.Parse(time.RFC3339, "2001-02-03T16:05:06+09:00")
latency := 123 * time.Millisecond
logger = logger.WithTime(startTime, latency)

// report target status with a message
logger.Healthy("target is healthy")
logger.Degrade("target is partialy working")
logger.Failure("target seems down")
logger.Unknown("failed to check, so target status is unknown")
logger.Aborted("the check was aborted by user or something")
Output:

2001-02-03T16:05:06+09:00	HEALTHY	123.000	foobar:your-plugin-url	target is healthy
2001-02-03T16:05:06+09:00	DEGRADE	123.000	foobar:your-plugin-url	target is partialy working
2001-02-03T16:05:06+09:00	FAILURE	123.000	foobar:your-plugin-url	target seems down
2001-02-03T16:05:06+09:00	UNKNOWN	123.000	foobar:your-plugin-url	failed to check, so target status is unknown
2001-02-03T16:05:06+09:00	ABORTED	123.000	foobar:your-plugin-url	the check was aborted by user or something

func NewLogger

func NewLogger(target *url.URL) Logger

NewLogger makes new Logger

This is the shorthand to `ayd.NewLoggerWithWriter(os.Stdout, target)`.

func NewLoggerWithWriter

func NewLoggerWithWriter(w io.Writer, target *url.URL) Logger

NewLoggerWithWriter makes new Logger with a io.Writer

func (Logger) Aborted

func (l Logger) Aborted(message string) error

Aborted prints Aborted status record.

Seealso StatusAborted.

func (Logger) Degrade added in v0.14.0

func (l Logger) Degrade(message string) error

Degrade prints Degrade status record.

Seealso StatusDegrade.

func (Logger) Failure

func (l Logger) Failure(message string) error

Failure prints Failure status record.

Seealso StatusFailure.

func (Logger) Healthy

func (l Logger) Healthy(message string) error

Healthy prints Healthy status record.

Seealso StatusHealthy.

func (Logger) Print

func (l Logger) Print(r Record) error

Print prints a Record

Example
logger := ayd.NewLogger(nil)

logger.Print(ayd.Record{
	Target:    &ayd.URL{Scheme: "foo", Host: "bar"},
	Status:    ayd.StatusHealthy,
	CheckedAt: time.Date(2001, 2, 3, 16, 5, 6, 7, time.UTC),
	Message:   "hello world",
})

logger.Print(ayd.Record{
	Target:    &ayd.URL{Scheme: "foo", Host: "bar"},
	CheckedAt: time.Date(2001, 2, 3, 16, 5, 7, 0, time.UTC),
	Message:   "without status",
})

err := logger.Print(ayd.Record{
	CheckedAt: time.Date(2001, 2, 3, 16, 5, 8, 0, time.UTC),
	Message:   "without target",
})
fmt.Println("error:", err)
Output:

2001-02-03T16:05:06Z	HEALTHY	0.000	foo://bar	hello world
2001-02-03T16:05:07Z	UNKNOWN	0.000	foo://bar	without status
error: invalid record: the target URL is required

func (Logger) StartTimer

func (l Logger) StartTimer() Logger

StartTimer makes new Logger that set start time as current time, and start timer for latency from now.

You can stop the timer with StopTimer method, or just call print method like Healthy or Failure.

Example
target, _ := url.Parse("foobar:your-plugin-url")

logger := ayd.NewLogger(target)

l := logger.StartTimer()
// check your target status
l.Healthy("hello world")

func (Logger) StopTimer

func (l Logger) StopTimer() Logger

StopTimer stops latency timer that started by StartTimer method, and makes new Logger with measured latency.

Example
target, _ := url.Parse("foobar:your-plugin-url")

logger := ayd.NewLogger(target)

l := logger.StartTimer()
// check your target status
l = l.StopTimer()

// do something, for example calculate result of the check

l.Healthy("hello world")

func (Logger) Unknown

func (l Logger) Unknown(message string) error

Unknown prints Unknown status record.

Seealso StatusUnknown.

func (Logger) WithTarget

func (l Logger) WithTarget(target *url.URL) Logger

WithTarget makes new Logger with new target URL

Example
logger := ayd.NewLogger(nil)

target, _ := url.Parse("foobar:your-plugin-url")

logger.WithTarget(target).Healthy("hello world")

func (Logger) WithTime

func (l Logger) WithTime(startTime time.Time, latency time.Duration) Logger

WithTime makes new Logger with start time and latency value

Example
target, _ := url.Parse("foobar:your-plugin-url")

logger := ayd.NewLogger(target)

startTime, _ := time.Parse(time.RFC3339, "2001-02-03T16:05:06+09:00")
latency := 123 * time.Millisecond

logger.WithTime(startTime, latency).Healthy("hello world")
Output:

2001-02-03T16:05:06+09:00	HEALTHY	123.000	foobar:your-plugin-url	hello world

type ProbeHistory added in v0.10.0

type ProbeHistory struct {
	Target *URL

	// Status is the latest status of the target
	Status Status

	// Status is the same as CheckedAt of the latest History record
	Updated time.Time

	Records []Record
}

ProbeHistory is the status history data of single target

func (ProbeHistory) MarshalJSON added in v0.10.0

func (ph ProbeHistory) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*ProbeHistory) UnmarshalJSON added in v0.10.0

func (ph *ProbeHistory) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type ProbePluginArgs

type ProbePluginArgs struct {
	TargetURL *url.URL
}

ProbePluginArgs is arguments for probe plugin

func ParseProbePluginArgs

func ParseProbePluginArgs() (ProbePluginArgs, error)

ParseProbePluginArgs is get arguments for probe plugin

This function is shorthand of `ayd.ParseProbePluginArgs(os.Args)`.

func ParseProbePluginArgsFrom

func ParseProbePluginArgsFrom(args []string) (ProbePluginArgs, error)

ParseProbePluginArgsFrom is parse arguments for probe plugin

type Record

type Record struct {
	// CheckedAt is the time the check started
	CheckedAt time.Time

	Status Status

	Latency time.Duration

	Target *URL

	// Message is the reason of the status, or extra informations of the check
	Message string
}

Record is a record in Ayd log

func ParseRecord

func ParseRecord(s string) (Record, error)

ParseRecord is parse string as a Record row in the log

func (Record) MarshalJSON added in v0.10.0

func (r Record) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Record) MarshalText added in v0.8.0

func (r Record) MarshalText() (text []byte, err error)

MarshalText is marshal to text

func (Record) String

func (r Record) String() string

String is make Result a string for row in the log

func (*Record) UnmarshalJSON added in v0.10.0

func (r *Record) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Record) UnmarshalText added in v0.8.0

func (r *Record) UnmarshalText(text []byte) (err error)

UnmarshalText is unmarshal from text

type Report deprecated added in v0.10.0

type Report struct {
	// ProbeHistory is the map of ProbeHistory.
	// The key is target URL string, and the value is struct ProbeHistory.
	ProbeHistory map[string]ProbeHistory

	// CurrentIncidents is the list of Incident that current causing.
	CurrentIncidents []Incident

	// IncidentHistory is the list of Incident that already resolved.
	//
	// If you want get current causing incidents, please use CurrentIncidents.
	IncidentHistory []Incident

	// ReportedAt is the time the report created in server.
	ReportedAt time.Time
}

Report is a report from Ayd server.

Deprecated: this struct planed be removed in future version.

func Fetch

func Fetch(u *url.URL) (Report, error)

Fetch is fetch Ayd json API and returns Report

func (Report) MarshalJSON added in v0.10.0

func (r Report) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Report) TargetURLs added in v0.10.0

func (r Report) TargetURLs() []*url.URL

TargetURLs returns target URLs that to status checking

func (*Report) UnmarshalJSON added in v0.10.0

func (r *Report) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type Status

type Status int8

Status is the status of target service

func ParseStatus

func ParseStatus(raw string) Status

ParseStatus is parse status string

If passed unsupported status, it will returns StatusUnknown

func (Status) MarshalText

func (s Status) MarshalText() ([]byte, error)

MarshalText is marshal Status as text

func (Status) String

func (s Status) String() string

String is make Status a string

func (*Status) UnmarshalText

func (s *Status) UnmarshalText(text []byte) error

UnmarshalText is unmarshal text as status

This function always returns nil. This parses as StatusUnknown instead of returns error if unsupported status passed.

type URL added in v0.14.0

type URL url.URL

URL is a target URL.

func ParseURL added in v0.14.0

func ParseURL(s string) (*URL, error)

ParseURL parses string as a URL.

func (*URL) String added in v0.14.0

func (u *URL) String() string

String returns string version of the URL. The password in the URL will be masked.

func (*URL) ToURL added in v0.14.0

func (u *URL) ToURL() *url.URL

ToURL converts Ayd URL to *url.URL in standard library.

Jump to

Keyboard shortcuts

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