/
database.go
238 lines (204 loc) · 5.61 KB
/
database.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"fmt"
"github.com/RangelReale/appstatsd/data"
"github.com/RangelReale/gostatsd/statsd"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"strings"
"time"
)
var (
dbsession *mgo.Session
dbdb *mgo.Database
dblogc *mgo.Collection
DatabaseChan chan DBMessage
)
// message to send on DatabaseChan to notify of new data
type DBMessage struct {
metrics *statsd.Metric
log *data.LogData
}
func init() {
DatabaseChan = make(chan DBMessage, 1000)
}
func ServerDatabase() {
dbConnect()
for proc := range DatabaseChan {
if err := dbConnect(); err != nil {
log.Error("Could not connect to database: %s", err)
continue
}
if proc.metrics != nil {
dbHandleMetrics(proc.metrics)
}
if proc.log != nil {
dblogc.Insert(proc.log)
}
}
}
// handle metrics received from statsd
// bucket name must be in this format:
// appname.info1#param1#param2.info2#param1.infoX.field
// data is saved for day, hour, and 15 minute intervals
func dbHandleMetrics(m *statsd.Metric) {
values := strings.Split(m.Bucket, ".")
if len(values) < 3 {
log.Error("Invalid bucket name - at least 3 items dot-separated items are required: %s", m.Bucket)
return
}
if strings.HasPrefix(m.Bucket, "_") {
log.Error("Invalid bucket name - cannot start with underline: %s", m.Bucket)
return
}
// first item - app
app := values[0]
// last item - field name
name := values[len(values)-1]
// sanitization
if !data.ValidateName(app) {
log.Error("Invalid bucket name - name not validated: %s", app)
return
}
if !data.ValidateValueName(name) {
log.Error("Invalid bucket name - name not validated: %s", name)
return
}
// remove first and last item
values = values[1 : len(values)-1]
tm := time.Now().UTC()
// 15 minute aggregation
minute := int(tm.Minute()/15.0) * 15
var idata *bson.M
switch m.Type {
case statsd.COUNTER:
idata = &bson.M{
"$inc": bson.M{
fmt.Sprintf("_dy.c_%s", name): m.Value,
fmt.Sprintf("_hr.h_%d.c_%s", tm.Hour(), name): m.Value,
fmt.Sprintf("_hr.h_%d.mn.m_%d.c_%s", tm.Hour(), minute, name): m.Value,
},
}
case statsd.TIMER:
idata = &bson.M{
"$inc": bson.M{
fmt.Sprintf("_dy.t_%s", name): m.Value,
fmt.Sprintf("_dy.tc_%s", name): 1,
fmt.Sprintf("_hr.h_%d.t_%s", tm.Hour(), name): m.Value,
fmt.Sprintf("_hr.h_%d.tc_%s", tm.Hour(), name): 1,
fmt.Sprintf("_hr.h_%d.mn.m_%d.t_%s", tm.Hour(), minute, name): m.Value,
fmt.Sprintf("_hr.h_%d.mn.m_%d.tc_%s", tm.Hour(), minute, name): 1,
},
}
case statsd.GAUGE:
idata = &bson.M{
"$inc": bson.M{
fmt.Sprintf("_dy.g_%s", name): m.Value,
fmt.Sprintf("_dy.gc_%s", name): 1,
fmt.Sprintf("_hr.h_%d.g_%s", tm.Hour(), name): m.Value,
fmt.Sprintf("_hr.h_%d.gc_%s", tm.Hour(), name): 1,
fmt.Sprintf("_hr.h_%d.mn.m_%d.g_%s", tm.Hour(), minute, name): m.Value,
fmt.Sprintf("_hr.h_%d.mn.m_%d.gc_%s", tm.Hour(), minute, name): 1,
},
}
}
if idata != nil {
baseq := bson.M{
"_dt": tm.Format("2006-01-02"),
}
baseqapp := bson.M{
"_dt": tm.Format("2006-01-02"),
"_app": app,
}
// all collections start with stat_
c_base := "stat"
// loop on info. Each can have parameters separated by #
for _, iv := range values {
info := strings.Split(iv, "#")
if strings.HasPrefix(info[0], "_") {
log.Error("Invalid bucket name - info cannot start with underline: %s", info[0])
return
}
// sanitize
if !data.ValidateName(info[0]) {
log.Error("Invalid bucket name - name not validated: %s", info[0])
return
}
c_base = c_base + "_" + info[0]
if len(c_base) == 0 {
log.Error("Invalid bucket name - info cannot be blank: %s", m.Bucket)
return
}
// separate database for total and per-app
c := dbdb.C(c_base)
capp := dbdb.C(fmt.Sprintf("%s-app", c_base))
// loop parameters
for ridx, rv := range info[1:] {
if rv != "" {
var pname string
// from second parameter on, add index to parameter name, starting from 1
if ridx > 0 {
pname = fmt.Sprintf("%s%d", info[0], ridx)
} else {
pname = info[0]
}
// sanitize
if !data.ValidateName(pname) {
log.Error("Invalid param name - name not validated: %s", pname)
return
}
// add parameter to queries
baseq[pname] = rv
baseqapp[pname] = rv
}
}
// general
_, err := c.Upsert(baseq, *idata)
if err != nil {
log.Error("Error saving log record: %s", err)
}
// by app
if app != "" {
_, err = capp.Upsert(baseqapp, *idata)
if err != nil {
log.Error("Error saving connection app record: %s", err)
}
}
}
}
}
func dbConnect() error {
if dbsession != nil {
return nil
}
log.Debug("Connecting to database")
var mgourl string
if Configuration.MGOUsername != "" {
mgourl = fmt.Sprintf("mongodb://%s:%s@%s:%s/%s",
Configuration.MGOUsername, Configuration.MGOPassword,
Configuration.MGOHost, Configuration.MGOPort,
Configuration.MGODBName)
} else {
mgourl = fmt.Sprintf("mongodb://%s:%s/%s",
Configuration.MGOHost, Configuration.MGOPort,
Configuration.MGODBName)
}
var err error
dbsession, err = mgo.Dial(mgourl)
if err == nil {
dbdb = dbsession.DB(Configuration.MGODBName)
dblogc = dbdb.C("log")
} else {
dbsession = nil
}
return err
}
func DBConnectClone() (*mgo.Session, error) {
if dbsession == nil {
err := dbConnect()
if err != nil {
return nil, err
}
}
return dbsession.Clone(), nil
}