forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
analytics.go
259 lines (218 loc) · 6.6 KB
/
analytics.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main
import (
"encoding/csv"
"fmt"
"github.com/nu7hatch/gouuid"
"gopkg.in/vmihailenco/msgpack.v2"
"labix.org/v2/mgo"
"os"
"strconv"
"time"
)
// AnalyticsRecord encodes the details of a request
type AnalyticsRecord struct {
Method string
Path string
ContentLength int64
UserAgent string
Day int
Month time.Month
Year int
Hour int
ResponseCode int
APIKey string
TimeStamp time.Time
APIVersion string
APIName string
APIID string
OrgID string
OauthID string
RequestTime int64
ExpireAt time.Time `bson:"expireAt" json:"expireAt"`
}
func (a *AnalyticsRecord) SetExpiry(expiresInSeconds int64) {
var expiry time.Duration
expiry = time.Duration(expiresInSeconds) * time.Second
if expiresInSeconds == 0 {
// Expiry is set to 100 years
expiry = (24 * time.Hour) * (365 * 100)
}
t := time.Now()
t2 := t.Add(expiry)
a.ExpireAt = t2
}
// AnalyticsError is an error for when writing to the storage engine fails
type AnalyticsError struct{}
func (e AnalyticsError) Error() string {
return "Recording request failed!"
}
// AnalyticsHandler is an interface to record analytics data to a writer.
type AnalyticsHandler interface {
RecordHit(AnalyticsRecord) error
}
// Purger is an interface that will define how the in-memory store will be purged
// of analytics data to prevent it growing too large
type Purger interface {
PurgeCache()
StartPurgeLoop(int)
}
// RedisAnalyticsHandler implements AnalyticsHandler and will record analytics
// data to a redis back end as defined in the Config object
type RedisAnalyticsHandler struct {
Store *RedisStorageManager
Clean Purger
}
// RecordHit will store an AnalyticsRecord in Redis
func (r RedisAnalyticsHandler) RecordHit(thisRecord AnalyticsRecord) error {
// If we are obfuscating API Keys, store the hashed representation (config check handled in hashing function)
thisRecord.APIKey = getHash(thisRecord.APIKey)
encoded, err := msgpack.Marshal(thisRecord)
u5, _ := uuid.NewV4()
keyName := fmt.Sprintf("%d%d%d%d-%s", thisRecord.Year, thisRecord.Month, thisRecord.Day, thisRecord.Hour, u5.String())
if err != nil {
log.Error("Error encoding analytics data:")
log.Error(err)
return AnalyticsError{}
}
r.Store.SetKey(keyName, string(encoded), 0)
return nil
}
// CSVPurger purges the in-memory analytics store to a CSV file as defined in the Config object
type CSVPurger struct {
Store *RedisStorageManager
}
// StartPurgeLoop is used as a goroutine to ensure that the cache is purged
// of analytics data (assuring size is small).
func (c CSVPurger) StartPurgeLoop(nextCount int) {
time.Sleep(time.Duration(nextCount) * time.Second)
c.PurgeCache()
c.StartPurgeLoop(nextCount)
}
// PurgeCache Will pull all the analytics data from the
// cache and drop it to a storage engine, in this case a CSV file
func (c CSVPurger) PurgeCache() {
curtime := time.Now()
fname := fmt.Sprintf("%s%d-%s-%d-%d-%d.csv", config.AnalyticsConfig.CSVDir, curtime.Year(), curtime.Month().String(), curtime.Day(), curtime.Hour(), curtime.Minute())
ferr := os.MkdirAll(config.AnalyticsConfig.CSVDir, 0777)
if ferr != nil {
log.Error(ferr)
}
outfile, _ := os.Create(fname)
defer outfile.Close()
writer := csv.NewWriter(outfile)
var headers = []string{"METHOD", "PATH", "SIZE", "UA", "DAY", "MONTH", "YEAR", "HOUR", "RESPONSE", "APINAME", "APIVERSION"}
err := writer.Write(headers)
if err != nil {
log.Error("Failed to write file headers!")
log.Error(err)
} else {
KeyValueMap := c.Store.GetKeysAndValues()
keys := []string{}
for k, v := range KeyValueMap {
keys = append(keys, k)
decoded := AnalyticsRecord{}
err := msgpack.Unmarshal([]byte(v), &decoded)
if err != nil {
log.Error("Couldn't unmarshal analytics data:")
log.Error(err)
} else {
toWrite := []string{
decoded.Method,
decoded.Path,
strconv.FormatInt(decoded.ContentLength, 10),
decoded.UserAgent,
strconv.Itoa(decoded.Day),
decoded.Month.String(),
strconv.Itoa(decoded.Year),
strconv.Itoa(decoded.Hour),
strconv.Itoa(decoded.ResponseCode),
decoded.APIName,
decoded.APIVersion}
err := writer.Write(toWrite)
if err != nil {
log.Error("File write failed!")
log.Error(err)
}
}
}
writer.Flush()
c.Store.DeleteKeys(keys)
}
}
// MongoPurger will purge analytics data into a Mongo database, requires that the Mongo DB string is specified
// in the Config object
type MongoPurger struct {
Store *RedisStorageManager
dbSession *mgo.Session
}
// Connect Connects to Mongo
func (m *MongoPurger) Connect() {
var err error
m.dbSession, err = mgo.Dial(config.AnalyticsConfig.MongoURL)
if err != nil {
log.Error("Mongo connection failed:")
log.Panic(err)
}
}
// StartPurgeLoop starts the loop that will be started as a goroutine and pull data out of the in-memory
// store and into MongoDB
func (m MongoPurger) StartPurgeLoop(nextCount int) {
time.Sleep(time.Duration(nextCount) * time.Second)
m.PurgeCache()
m.StartPurgeLoop(nextCount)
}
// PurgeCache will pull the data from the in-memory store and drop it into the specified MongoDB collection
func (m *MongoPurger) PurgeCache() {
if m.dbSession == nil {
log.Info("Not connected to analytics store, connecting...")
m.Connect()
m.PurgeCache()
} else {
analyticsCollection := m.dbSession.DB("").C(config.AnalyticsConfig.MongoCollection)
KeyValueMap := m.Store.GetKeysAndValues()
if len(KeyValueMap) > 0 {
keys := make([]interface{}, len(KeyValueMap), len(KeyValueMap))
keyNames := make([]string, len(KeyValueMap), len(KeyValueMap))
i := 0
for k, v := range KeyValueMap {
keyNames[i] = k
decoded := AnalyticsRecord{}
err := msgpack.Unmarshal([]byte(v), &decoded)
if err != nil {
log.Error("Couldn't unmarshal analytics data:")
log.Error(err)
} else {
keys[i] = interface{}(decoded)
}
i++
}
err := analyticsCollection.Insert(keys...)
if err != nil {
log.Error("Problem inserting to mongo collection")
log.Error(err)
} else {
m.Store.DeleteRawKeys(keyNames, "analytics-")
}
}
}
}
type MockPurger struct {
Store *RedisStorageManager
}
// Connect does nothing
func (m *MockPurger) Connect() {}
// StartPurgeLoop does nothing
func (m MockPurger) StartPurgeLoop(nextCount int) {}
// PurgeCache will just empty redis
func (m *MockPurger) PurgeCache() {
KeyValueMap := m.Store.GetKeysAndValues()
if len(KeyValueMap) > 0 {
keyNames := make([]string, len(KeyValueMap), len(KeyValueMap))
i := 0
for k, _ := range KeyValueMap {
keyNames[i] = k
i++
}
m.Store.DeleteKeys(keyNames)
}
}