summaryrefslogtreecommitdiffstats
path: root/pkg/types/notification_states.go
blob: ff5760a33516c028b59c8f21abaeadbda38e1b4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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)
)