From b09c6d56832eb1718c07d74abf3bc6ae3fe4e030 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 28 Apr 2024 14:36:04 +0200 Subject: Adding upstream version 1.1.0. Signed-off-by: Daniel Baumann --- pkg/types/notification_states.go | 78 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 pkg/types/notification_states.go (limited to 'pkg/types/notification_states.go') diff --git a/pkg/types/notification_states.go b/pkg/types/notification_states.go new file mode 100644 index 0000000..ff5760a --- /dev/null +++ b/pkg/types/notification_states.go @@ -0,0 +1,78 @@ +package types + +import ( + "database/sql/driver" + "encoding" + "encoding/json" + "github.com/icinga/icingadb/internal" + "github.com/pkg/errors" +) + +// NotificationStates specifies the set of states a notification may be sent for. +type NotificationStates uint8 + +// UnmarshalJSON implements the json.Unmarshaler interface. +func (nst *NotificationStates) UnmarshalJSON(data []byte) error { + var states []string + if err := internal.UnmarshalJSON(data, &states); err != nil { + return err + } + + var n NotificationStates + for _, state := range states { + if v, ok := notificationStateNames[state]; ok { + n |= v + } else { + return badNotificationStates(states) + } + } + + *nst = n + return nil +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +func (nst *NotificationStates) UnmarshalText(text []byte) error { + return nst.UnmarshalJSON(text) +} + +// Value implements the driver.Valuer interface. +func (nst NotificationStates) Value() (driver.Value, error) { + if nst&^allNotificationStates == 0 { + return int64(nst), nil + } else { + return nil, badNotificationStates(nst) + } +} + +// badNotificationStates returns an error about syntactically, but not semantically valid NotificationStates. +func badNotificationStates(s interface{}) error { + return errors.Errorf("bad notification states: %#v", s) +} + +// notificationStateNames maps all valid NotificationStates values to their SQL representation. +var notificationStateNames = map[string]NotificationStates{ + "OK": 1, + "Warning": 2, + "Critical": 4, + "Unknown": 8, + "Up": 16, + "Down": 32, +} + +// allNotificationStates is the largest valid NotificationStates value. +var allNotificationStates = func() NotificationStates { + var nt NotificationStates + for _, v := range notificationStateNames { + nt |= v + } + + return nt +}() + +// Assert interface compliance. +var ( + _ json.Unmarshaler = (*NotificationStates)(nil) + _ encoding.TextUnmarshaler = (*NotificationStates)(nil) + _ driver.Valuer = NotificationStates(0) +) -- cgit v1.2.3