ayd

package
v0.16.7 Latest Latest
Warning

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

Go to latest
Published: May 16, 2024 License: MIT Imports: 14 Imported by: 6

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", nil)
Output:

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)
	}
}
Output:

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!", nil)
} else {
	logger.Failure("target is down", nil)
}
Output:

Index

Examples

Constants

This section is empty.

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.

View Source
var (
	ErrInvalidTime = errors.New("invalid format")
)

Functions

func ParseTime added in v0.15.1

func ParseTime(s string) (time.Time, error)

ParseTime parses time string in Ayd way. This function supports RFC3339 and some variant formats.

func SortProbeHistories deprecated 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.

Deprecated: this struct will removed in future version.

Types

type AlertPluginArgs deprecated

type AlertPluginArgs struct {
	AlertURL  *URL
	Time      time.Time
	Status    Status
	Latency   time.Duration
	TargetURL *URL
	Message   string
	Extra     map[string]interface{}
}

AlertPluginArgs is arguments for alert plugin

Deprecated: since version 0.16. This struct will removed in future version. Please parse using ParseURL and ParseRecord instead of this.

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 ExtraPair added in v0.15.0

type ExtraPair struct {
	Key   string
	Value string
}

ExtraPair is a pair of string, for Record.StringExtra..

type Incident deprecated

type Incident struct {
	Target *URL

	Status Status

	Message string

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

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

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

Deprecated: this struct will removed in future version.

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 deprecated 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.

Deprecated: this interface will removed in future version. After version 0.15, you can read log file using combination of the bufio.Scanner and the json.Unmarshal in the standard library of Go.

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(`
{"time":"2001-02-03T16:05:06Z", "status":"HEALTHY", "latency":1.234, "target":"https://example.com", "message":"200 OK"}
{"time":"2001-02-03T16:15:06Z", "status":"HEALTHY", "latency":2.345, "target":"https://example.com", "message":"200 OK"}
{"time":"2001-02-03T16:25:06Z", "status":"HEALTHY", "latency":3.456, "target":"https://example.com", "message":"200 OK"}
`))

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

for s.Scan() {
	fmt.Println(s.Record().Time)
}
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(`
{"time":"2001-02-03T16:05:06Z", "status":"HEALTHY", "latency":1.234, "target":"https://example.com", "message":"200 OK"}
{"time":"2001-02-03T16:15:06Z", "status":"HEALTHY", "latency":2.345, "target":"https://example.com", "message":"200 OK"}
{"time":"2001-02-03T16:25:06Z", "status":"HEALTHY", "latency":3.456, "target":"https://example.com", "message":"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().Time)
}
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, _ := ayd.ParseURL("foobar:your-plugin-url")

logger := ayd.NewLogger(target)

logger.Healthy("hello world", nil)
logger.Failure("hello world", map[string]interface{}{
	"extra": "information",
})
Output:

Example (SetExtraValues)
logger := ayd.NewLogger(nil)

// change target URL
target, _ := ayd.ParseURL("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", map[string]interface{}{
	"hello": "world",
})
logger.Degrade("target is partialy working", map[string]interface{}{
	"number": 42,
})
logger.Failure("target seems down", map[string]interface{}{
	"list": []string{"hello", "world"},
})
logger.Unknown("failed to check, so target status is unknown", map[string]interface{}{
	"obj": map[string]string{"hello": "world"},
})
logger.Aborted("the check was aborted by user or something", nil)
Output:

{"time":"2001-02-03T16:05:06+09:00", "status":"HEALTHY", "latency":123.000, "target":"foobar:your-plugin-url", "message":"target is healthy", "hello":"world"}
{"time":"2001-02-03T16:05:06+09:00", "status":"DEGRADE", "latency":123.000, "target":"foobar:your-plugin-url", "message":"target is partialy working", "number":42}
{"time":"2001-02-03T16:05:06+09:00", "status":"FAILURE", "latency":123.000, "target":"foobar:your-plugin-url", "message":"target seems down", "list":["hello","world"]}
{"time":"2001-02-03T16:05:06+09:00", "status":"UNKNOWN", "latency":123.000, "target":"foobar:your-plugin-url", "message":"failed to check, so target status is unknown", "obj":{"hello":"world"}}
{"time":"2001-02-03T16:05:06+09:00", "status":"ABORTED", "latency":123.000, "target":"foobar:your-plugin-url", "message":"the check was aborted by user or something"}

func NewLogger

func NewLogger(target *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) Logger

NewLoggerWithWriter makes new Logger with a io.Writer

func (Logger) Aborted

func (l Logger) Aborted(message string, extra map[string]interface{}) error

Aborted prints Aborted status record.

Seealso StatusAborted.

func (Logger) Degrade added in v0.14.0

func (l Logger) Degrade(message string, extra map[string]interface{}) error

Degrade prints Degrade status record.

Seealso StatusDegrade.

func (Logger) Failure

func (l Logger) Failure(message string, extra map[string]interface{}) error

Failure prints Failure status record.

Seealso StatusFailure.

func (Logger) Healthy

func (l Logger) Healthy(message string, extra map[string]interface{}) 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,
	Time:    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"},
	Time:    time.Date(2001, 2, 3, 16, 5, 7, 0, time.UTC),
	Message: "without status",
})

logger.Print(ayd.Record{
	Target:  &ayd.URL{Scheme: "foo", Host: "bar"},
	Status:  ayd.StatusHealthy,
	Time:    time.Date(2001, 2, 3, 16, 5, 6, 7, time.UTC),
	Message: "with extra",
	Extra: map[string]interface{}{
		"hello": "world",
	},
})

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

{"time":"2001-02-03T16:05:06Z", "status":"HEALTHY", "latency":0.000, "target":"foo://bar", "message":"hello world"}
{"time":"2001-02-03T16:05:07Z", "status":"UNKNOWN", "latency":0.000, "target":"foo://bar", "message":"without status"}
{"time":"2001-02-03T16:05:06Z", "status":"HEALTHY", "latency":0.000, "target":"foo://bar", "message":"with extra", "hello":"world"}
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, _ := ayd.ParseURL("foobar:your-plugin-url")

logger := ayd.NewLogger(target)

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

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, _ := ayd.ParseURL("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", nil)
Output:

func (Logger) Unknown

func (l Logger) Unknown(message string, extra map[string]interface{}) error

Unknown prints Unknown status record.

Seealso StatusUnknown.

func (Logger) WithTarget

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

WithTarget makes new Logger with new target URL

Example
logger := ayd.NewLogger(nil)

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

logger.WithTarget(target).Healthy("hello world", nil)
Output:

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, _ := ayd.ParseURL("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", nil)
Output:

{"time":"2001-02-03T16:05:06+09:00", "status":"HEALTHY", "latency":123.000, "target":"foobar:your-plugin-url", "message":"hello world"}

type ProbeHistory deprecated 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 Time of the latest History record
	Updated time.Time

	Records []Record
}

ProbeHistory is the status history data of single target

Deprecated: this struct will removed in future version.

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 deprecated

type ProbePluginArgs struct {
	TargetURL *URL
}

ProbePluginArgs is arguments for probe plugin

Deprecated: since version 0.16. This struct will removed in future version. Please parse using ParseURL instead of this.

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 {
	Time    time.Time
	Status  Status
	Latency time.Duration
	Target  *URL
	Message string
	Extra   map[string]interface{}
}

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) ReadableExtra added in v0.15.0

func (r Record) ReadableExtra() []ExtraPair

ReadableExtra returns Extra map but encode each values as string.

func (Record) ReadableMessage added in v0.15.0

func (r Record) ReadableMessage() string

ReadableMessage returns human readable message of the message field and extra fields.

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) (err error)

UnmarshalJSON implements the json.Unmarshaler interface.

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

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

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 Status = -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 Status = 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 Status = 1

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

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) MarshalText added in v0.15.0

func (u URL) MarshalText() ([]byte, error)

MarshalText encodes a URL to []byte.

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.

func (*URL) UnmarshalText added in v0.15.0

func (u *URL) UnmarshalText(text []byte) error

UnmarshalText parser raw text as a URL.

Jump to

Keyboard shortcuts

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