-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
db.go
376 lines (305 loc) · 8.04 KB
/
db.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package utils
import (
"context"
"os"
"errors"
"sync"
"time"
"strings"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/bson"
lungo "github.com/256dpi/lungo"
)
var client *mongo.Client
var DBContainerName string
var DBStatus bool
func DB() error {
config := GetMainConfig()
if(config.DisableUserManagement) {
DBStatus = false
return errors.New("User Management is disabled")
}
mongoURL := config.MongoDB
if(client != nil && client.Ping(context.TODO(), readpref.Primary()) == nil) {
DBStatus = true
return nil
}
Log("(Re) Connecting to the database...")
DBContainerName = ""
isPuppetMode := config.Database.PuppetMode
puppetHostname := config.Database.Hostname
username := config.Database.Username
password := config.Database.Password
if isPuppetMode {
mongoURL = "mongodb://" + username + ":" + password + "@" + puppetHostname + ":27017"
DBContainerName = puppetHostname
}
if mongoURL == "" {
DBStatus = false
return errors.New("MongoDB URL is not set, cannot connect to the database.")
}
var err error
opts := options.Client().ApplyURI(mongoURL).SetRetryWrites(true).SetWriteConcern(writeconcern.New(writeconcern.WMajority()))
opts.SetConnectTimeout(5 * time.Second)
hostname := ""
port := "27017"
if !isPuppetMode {
hostname = opts.Hosts[0]
// split port
hostnameParts := strings.Split(hostname, ":")
hostname = hostnameParts[0]
if len(hostnameParts) > 1 {
port = hostnameParts[1]
}
} else {
hostname = puppetHostname
}
if os.Getenv("HOSTNAME") == "" || IsHostNetwork {
Log("Getting Mongo DB IP from name : " + hostname + " (port " + port + ")")
ip, _ := GetContainerIPByName(hostname)
if ip != "" {
DBContainerName = hostname
opts.SetHosts([]string{ip + ":" + port})
Log("Mongo DB IP : " + ip)
}
} else {
if DoesContainerExist(hostname) {
Debug("MongoDB is running in a container")
DBContainerName = hostname
}
}
client, err = mongo.Connect(context.TODO(), opts)
if err != nil {
DBStatus = false
return err
}
// Ping the primary
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
DBStatus = false
return err
}
initDB()
DBStatus = true
Log("Successfully connected to the database.")
return nil
}
func DisconnectDB() {
if client == nil {
return
}
if err := client.Disconnect(context.TODO()); err != nil {
Error("DB", err)
}
client = nil
}
var embeddedClient lungo.IClient
var embeddedClientClose func()
func GetEmbeddedCollection(applicationId string, collection string) (lungo.ICollection, func(), error) {
opts := lungo.Options{
Store: lungo.NewFileStore(CONFIGFOLDER + "database", 700),
}
name := os.Getenv("MONGODB_NAME"); if name == "" {
name = "COSMOS"
}
if embeddedClient != nil {
c := embeddedClient.Database(name).Collection(applicationId + "_" + collection)
return c, func() {
//engine.Close()
}, nil
}
// open database
client, engine, err := lungo.Open(nil, opts)
if err != nil {
return nil, nil, err
}
// ensure engine is closed
// defer engine.Close()
c := client.Database(name).Collection(applicationId + "_" + collection)
embeddedClient = client
embeddedClientClose = engine.Close
return c, func() {
//engine.Close()
}, nil
}
func GetCollection(applicationId string, collection string) (*mongo.Collection, error) {
if client == nil {
errCo := DB()
if errCo != nil {
return nil, errCo
}
}
DBStatus = true
name := os.Getenv("MONGODB_NAME"); if name == "" {
name = "COSMOS"
}
// Debug("Getting collection " + applicationId + "_" + collection + " from database " + name)
c := client.Database(name).Collection(applicationId + "_" + collection)
return c, nil
}
// func query(q string) (*sql.Rows, error) {
// return db.Query(q)
// }
var (
bufferLock sync.Mutex
writeBuffer = make(map[string][]map[string]interface{})
bufferTicker = time.NewTicker(1 * time.Minute)
bufferCapacity = 100
)
func GetWriteBuffer() map[string][]map[string]interface{} {
return writeBuffer
}
func GetWriteBufferLength() int {
result := 0
for _, objects := range writeBuffer {
buflen := 0
for _, _ = range objects {
buflen++
}
result += len(objects)
}
return result
}
func InitDBBuffers() {
go func() {
for {
select {
case <-bufferTicker.C:
flushAllBuffers()
}
}
}()
}
func flushBuffer(collectionName string) {
bufferLock.Lock()
defer bufferLock.Unlock()
objects, exists := writeBuffer[collectionName]
if exists && len(objects) > 0 {
collection, errG := GetCollection(GetRootAppId(), collectionName)
if errG != nil {
Error("BulkDBWritter: Error getting collection", errG)
} else {
if err := WriteToDatabase(collection, objects); err != nil {
Error("BulkDBWritter: Error writing to database", err)
}
writeBuffer[collectionName] = make([]map[string]interface{}, 0)
}
}
}
func flushAllBuffers() {
bufferLock.Lock()
defer bufferLock.Unlock()
for collectionName, objects := range writeBuffer {
if len(objects) > 0 {
collection, errG := GetCollection(GetRootAppId(), collectionName)
if errG != nil {
Error("BulkDBWritter: Error getting collection", errG)
} else {
if err := WriteToDatabase(collection, objects); err != nil {
Error("BulkDBWritter: Error writing to database: ", err)
}
writeBuffer[collectionName] = make([]map[string]interface{}, 0)
}
}
}
}
func BufferedDBWrite(collectionName string, object map[string]interface{}) {
bufferLock.Lock()
writeBuffer[collectionName] = append(writeBuffer[collectionName], object)
if len(writeBuffer[collectionName]) >= bufferCapacity {
bufferLock.Unlock()
flushBuffer(collectionName)
} else {
bufferLock.Unlock()
}
}
func WriteToDatabase(collection *mongo.Collection, objects []map[string]interface{}) error {
if len(objects) == 0 {
return nil // Nothing to write
}
// Convert to a slice of interface{} for insertion
interfaceSlice := make([]interface{}, len(objects))
for i, v := range objects {
interfaceSlice[i] = v
}
_, err := collection.InsertMany(context.Background(), interfaceSlice)
if err != nil {
return err
}
return nil
}
func ListAllUsers(role string) []User {
// list all users
c, closeDb, errCo := GetEmbeddedCollection(GetRootAppId(), "users")
defer closeDb()
if errCo != nil {
Error("Database Connect", errCo)
return []User{}
}
users := []User{}
condition := map[string]interface{}{}
if role == "admin" {
condition = map[string]interface{}{
"Role": 2,
}
} else if role == "user" {
condition = map[string]interface{}{
"Role": 1,
}
}
cursor, err := c.Find(nil, condition)
defer cursor.Close(nil)
if err != nil {
Error("Database: Error while getting users", err)
return []User{}
}
if err = cursor.All(nil, &users); err != nil {
Error("Database: Error while decoding users", err)
return []User{}
}
return users
}
func initDB() {
c, errCo := GetCollection(GetRootAppId(), "events")
if errCo != nil {
Error("Metrics - Database Connect", errCo)
} else {
// Create a text index on the _search field
model := mongo.IndexModel{
Keys: bson.M{"_search": "text"},
}
// Creating the index
_, err := c.Indexes().CreateOne(context.Background(), model)
if err != nil {
Error("Metrics - Create Index", err)
return // Handle error appropriately
}
// Create a date index
model = mongo.IndexModel{
Keys: bson.M{"Date": -1},
}
// Creating the index
_, err = c.Indexes().CreateOne(context.Background(), model)
if err != nil {
Error("Metrics - Create Index", err)
return // Handle error appropriately
}
}
c, errCo = GetCollection(GetRootAppId(), "metrics")
if errCo != nil {
Error("Metrics - Database Connect", errCo)
} else {
// create search index on metrics key
model := mongo.IndexModel{
Keys: bson.M{"Key": 1},
}
// Creating the index
_, err := c.Indexes().CreateOne(context.Background(), model)
if err != nil {
Error("Metrics - Create Index", err)
return // Handle error appropriately
}
}
}