-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
122 lines (98 loc) · 2.57 KB
/
monitor.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"fmt"
"piot-server/config"
"time"
"github.com/op/go-logging"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type Monitor struct {
log *logging.Logger
db *mongo.Database
mailClient IMailClient
things *Things
params *config.Parameters
users *Users
orgs *Orgs
}
func NewMonitor(log *logging.Logger,
db *mongo.Database,
mailClient IMailClient,
things *Things,
params *config.Parameters,
users *Users,
orgs *Orgs) *Monitor {
return &Monitor{
log: log,
db: db,
mailClient: mailClient,
things: things,
params: params,
users: users,
orgs: orgs}
}
func (m *Monitor) Check() {
m.log.Infof("Monitor check started")
var msgLines []string
// get all enabled things
filter := bson.M{"enabled": true}
things, err := m.things.GetFiltered(filter)
if err != nil {
m.log.Errorf("Monitor check error, falied fetching of things: %s", err.Error())
return
}
orgs, err := m.orgs.GetAll()
if err != nil {
m.log.Errorf("Monitor check error, falied fetching of orgs: %s", err.Error())
return
}
for i := 0; i < len(things); i++ {
thing := things[i]
// skip things where last seen interval is not set
if thing.LastSeenInterval == 0 {
continue
}
diff := int32(time.Now().Unix()) - thing.LastSeen
if diff > thing.LastSeenInterval {
m.log.Infof("thing %v", thing.OrgId)
lastSeen := time.Unix(int64(thing.LastSeen), 0)
// look for org
orgName := "n/a"
for j := 0; j < len(orgs); j++ {
if orgs[j].Id == thing.OrgId {
orgName = orgs[j].Name
}
}
msgLine := fmt.Sprintf("%s/%s (LastSeen: %s, LastSeenInterval: %d sec., Id: %s)",
orgName,
thing.Name,
lastSeen,
thing.LastSeenInterval,
thing.Id.Hex())
m.log.Warningf("Thing %s did not respond in defined interval", msgLine)
msgLines = append(msgLines, msgLine)
}
}
m.log.Infof("Monitor check - %d (out of %d) not responding things detected", len(msgLines), len(things))
if len(msgLines) > 0 {
msg := "Following things didn't respond in defined interval:\n\n"
for i := 0; i < len(msgLines); i++ {
msg += msgLines[i] + "\n"
}
// get admin users
var adminEmails []string
admins, err := m.users.GetAdmins()
if err != nil {
m.log.Error(err)
}
for i := 0; i < len(admins); i++ {
adminEmails = append(adminEmails, admins[i].Email)
}
err = m.mailClient.SendMail("[piot][alarm] Not Available Devices", m.params.MailFrom, adminEmails, msg)
if err != nil {
m.log.Error(err)
}
}
m.log.Infof("Monitor check finished")
}