-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.go
646 lines (581 loc) · 14.9 KB
/
mongo.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
package pfftdb
import (
"fmt"
"io"
"math/rand"
//lg "log"
//"os"
"sync"
"time"
log "github.com/golang/glog"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
// isEmpty just checks if the value given is empty.
func isEmpty(val interface{}) bool {
if val == "" || val == nil {
return true
}
return false
}
// MongoGraph
type MongoGraph struct {
Graph *Graph
ColName string
}
// Mongo
type Mongo struct {
Session *mgo.Session
Hosts string
DBName string // db name
Graphs map[string]*MongoGraph
muGraph sync.Mutex
}
// TripleDoc represents the triplestore, where Objs is a set of interface{}
type TripleDoc struct {
//GraphID string "g"
Sub string "s"
Pred string "p"
Obj interface{} "o"
}
// NewMongo
func NewMongo(hosts, dbName string, graphs []string) (*Mongo, error) {
m := &Mongo{
Hosts: hosts,
DBName: dbName,
Graphs: map[string]*MongoGraph{},
muGraph: sync.Mutex{},
}
m.Connect(hosts)
for _, graphName := range graphs {
_, err := m.Create(graphName)
if err != nil {
log.Error(err)
continue
}
}
return m, nil
}
// Graphs returns a list of created graphs.
// TODO run through collections as well and get distinct graphs.
func (m *Mongo) GraphsList() []string {
graphs := []string{}
graphsSet := map[string]bool{}
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
db := sessionCopy.DB(m.DBName)
names, err := db.CollectionNames()
if err != nil {
log.Error(err)
return graphs
}
for _, name := range names {
if name == "system.indexes" {
continue
}
graphsSet[name] = true
c := db.C(name)
var gNames []string
c.Find(bson.M{}).Distinct("g", gNames)
for _, gName := range gNames {
graphsSet[gName] = true
}
}
for k, _ := range graphsSet {
graphs = append(graphs, k)
}
return graphs
}
// Graph returns the internal graph given a name.
func (m *Mongo) Graph(name string) (*Graph, bool) {
m.muGraph.Lock()
defer m.muGraph.Unlock()
g, ok := m.Graphs[name]
if ok {
return g.Graph, true
}
return nil, false
}
// Drop drops a collection
func (m *Mongo) Drop(gid string) error {
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(gid)
err := col.DropCollection()
if err != nil {
log.Error(err, " graph:", gid)
return err
}
return nil
}
// Index creates the default indeces for the graph.
func (m *Mongo) Index(gid string, background bool) error {
m.Session.ResetIndexCache()
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(gid)
cInfo := &mgo.CollectionInfo{DisableIdIndex: true}
err := col.Create(cInfo)
if err != nil {
log.Error(err)
}
/*
// TODO figure out the magic of mongo indexes
index := mgo.Index{
Key: []string{"g", "s", "p", "o"},
Background: false,
Sparse: true,
Unique: true,
DropDups: true,
}
err := col.EnsureIndex(index)
return err
*/
index := mgo.Index{
Key: []string{"g", "s"},
Background: background,
Sparse: true,
}
err = col.EnsureIndex(index)
if err != nil {
log.Error(err)
//return err
}
log.V(2).Infof("%+v", index)
index.Key = []string{"g", "o"}
err = col.EnsureIndex(index)
if err != nil {
log.Error(err)
//return err
}
log.V(2).Infof("%+v", index)
index.Key = []string{"g", "p"}
err = col.EnsureIndex(index)
if err != nil {
log.Error(err)
//return err
}
log.V(2).Infof("%+v", index)
index.Key = []string{"g", "s", "p"}
err = col.EnsureIndex(index)
if err != nil {
log.Error(err)
//return err
}
log.V(2).Infof("%+v", index)
index.Key = []string{"g", "s", "o"}
err = col.EnsureIndex(index)
if err != nil {
log.Error(err)
//return err
}
log.V(2).Infof("%+v", index)
index.Key = []string{"g", "p", "o"}
err = col.EnsureIndex(index)
if err != nil {
log.Error(err)
//return err
}
log.V(2).Infof("%+v", index)
index.Key = []string{"g", "s", "p", "o"}
index.Unique = true
index.DropDups = true
err = col.EnsureIndex(index)
if err != nil {
log.Error(err)
//return err
}
log.V(2).Infof("%+v", index)
return nil
}
// Create adds a graph
func (m *Mongo) Create(name string) (*Graph, error) {
if name == "" {
return nil, fmt.Errorf("missing name")
}
m.muGraph.Lock()
defer m.muGraph.Unlock()
// Check if graph already exists
g, ok := m.Graphs[name]
if ok {
return g.Graph, nil
}
err := m.Index(name, true)
if err != nil {
log.Error(err)
return nil, err
}
m.Graphs[name] = &MongoGraph{}
m.Graphs[name].Graph, err = NewGraph(name, m)
if err != nil {
log.Error(err)
delete(m.Graphs, name)
return nil, err
}
m.Graphs[name].ColName = name
return m.Graphs[name].Graph, nil
}
// Connect establishes a database connection.
func (m *Mongo) Connect(hosts string) {
log.Infof("connecting session to hosts:%s", hosts)
for {
session, err := mgo.DialWithTimeout(m.Hosts, 10*time.Second)
if err != nil {
log.Error(err)
time.Sleep(time.Second)
continue
}
session.SetMode(mgo.Strong, true)
//mgo.SetDebug(true)
//mgo.SetLogger(lg.New(os.Stderr, "", lg.LstdFlags))
session.SetSocketTimeout(120 * time.Second)
m.Session = session
go m.Pinger()
return
}
}
// AddBulk bulk inserts documents. It removes invalid ones and returns the number inserted.
// This has inconsistency issues with inserting bulk and error handling because of mongo.
// If a bulk insert fails mongo stops, the driver doesnt currently support continue on error.
// if the err is EOF there is no way to know the number of documents inserted, so the total
// returned may be zero, but there may have still been inserts......
func (m *Mongo) AddBulk(graph string, triples []*Triple) (int, error) {
g, ok := m.Graphs[graph]
if !ok {
return 0, fmt.Errorf("graph not found %s", graph)
}
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(g.ColName)
tripleDocs := []interface{}{}
for _, tr := range triples {
if tr == nil {
continue
}
sub, ok := tr[0].(string)
if !ok || sub == "" {
continue
}
pred, ok := tr[1].(string)
if !ok || pred == "" {
continue
}
if isEmpty(tr[2]) {
continue
}
tripleDocs = append(tripleDocs, bson.M{"g": graph, "s": tr[0], "p": tr[1], "o": tr[2]})
}
// TODO go back to bulk insert when continueOnError added to Insert in mgo driver
total := len(tripleDocs)
if total == 0 {
return 0, nil
}
var err error
// mongo has a maxMessageSizeBytes, so split up if docs too large.
// tries bulk insert, then if err occurs does individual inserts.
if total > 10000 {
start := 0
const inc = 10000
for start < total {
if start+inc > total {
// finish off remainder
err = col.Insert(tripleDocs[start:]...)
if err == io.EOF {
return 0, err
}
if err != nil {
for _, t := range tripleDocs[start:] {
err = col.Insert(t)
if err != nil {
total--
}
}
}
break
}
err = col.Insert(tripleDocs[start : start+inc]...)
if err == io.EOF {
return 0, err
}
if err != nil {
for _, t := range tripleDocs[start : start+inc] {
err = col.Insert(t)
if err != nil {
total--
}
}
}
start += inc
}
} else if total > 0 {
err = col.Insert(tripleDocs...)
if err != nil {
for _, t := range tripleDocs {
err = col.Insert(t)
total--
}
}
}
if err != nil {
errStr := err.Error()
// ignore duplicate key error
if len(errStr) > 6 && errStr[:6] == "E11000" {
return total, nil
}
log.Error(err)
}
return total, err
}
// Add upserts a triple with the given graph ID. Currently not in use, AddBulk instead.
func (m *Mongo) Add(graph, sub, pred string, obj interface{}) error {
g, ok := m.Graphs[graph]
if !ok {
return fmt.Errorf("graph not found %s", graph)
}
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(g.ColName)
if graph == "" || sub == "" || pred == "" || isEmpty(obj) {
return fmt.Errorf("missing components graph:%s sub:%s pred:%s obj:%s", graph, sub, pred, obj)
}
trDoc := bson.M{"g": graph, "s": sub, "p": pred, "o": obj}
_, err := col.Upsert(trDoc, trDoc)
if err != nil {
log.Error(err)
}
return err
}
// RemoveBulk builds each query from a triple and calls remove. $or doesn't use the index
func (m *Mongo) RemoveBulk(graph string, triples []*Triple) error {
g, ok := m.Graphs[graph]
if !ok {
return fmt.Errorf("graph not found %s", graph)
}
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(g.ColName)
for _, tr := range triples {
if tr == nil {
continue
}
if sub, ok := tr[0].(string); ok {
if pred, ok := tr[1].(string); ok {
query := m.BuildQuery(graph, sub, pred, tr[2], nil)
if sub == "" && pred == "" && (tr[2] == nil || tr[2] == "") {
return m.RemoveAll(graph)
} else {
_, err := col.RemoveAll(query)
if err == io.EOF {
return err
}
}
}
}
}
return nil
}
// RemoveAll clears out a collection named graph. It then rebuilds the indexes.
func (m *Mongo) RemoveAll(graph string) error {
if _, ok := m.Graphs[graph]; ok {
err := m.Drop(graph)
if err != nil {
log.Error(err)
return err
}
err = m.Index(graph, true)
if err != nil {
log.Error(err)
return err
}
}
return nil
}
// Remove removes set of triples from a graph depending on the given sub, pred, obj.
func (m *Mongo) Remove(graph, sub, pred string, obj interface{}) error {
g, ok := m.Graphs[graph]
if !ok {
return fmt.Errorf("graph not found %s", graph)
}
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(g.ColName)
var err error
sEmpty := isEmpty(sub)
pEmpty := isEmpty(pred)
oEmpty := isEmpty(obj)
// TODO move switches to most likely order.
switch {
case sEmpty && pEmpty && oEmpty:
// nil nil nil
_, err = col.RemoveAll(bson.M{"g": graph})
case sEmpty && pEmpty && !oEmpty:
// nil nil obj
_, err = col.RemoveAll(bson.M{"g": graph, "o": obj})
case sEmpty && !pEmpty && !oEmpty:
// nil pred obj
_, err = col.RemoveAll(bson.M{"g": graph, "p": pred, "o": obj})
case !sEmpty && !pEmpty && !oEmpty:
// sub pred obj
_, err = col.RemoveAll(bson.M{"g": graph, "s": sub, "p": pred, "o": obj})
case !sEmpty && pEmpty && oEmpty:
// sub nil nil
_, err = col.RemoveAll(bson.M{"g": graph, "s": sub})
case !sEmpty && !pEmpty && oEmpty:
// sub pred nil
_, err = col.RemoveAll(bson.M{"g": graph, "s": sub, "p": pred})
case !sEmpty && pEmpty && !oEmpty:
// sub nil obj
_, err = col.RemoveAll(bson.M{"g": graph, "s": sub, "o": obj})
}
return err
}
// Count
func (m *Mongo) Count(graph, sub, pred string, obj interface{}) (uint, error) {
g, ok := m.Graphs[graph]
if !ok {
log.Error("missing graph ", graph)
return 0, fmt.Errorf("missing graph %s", graph)
}
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(g.ColName)
query := m.BuildQuery(graph, sub, pred, obj, nil)
count, err := col.Find(query).Count()
return uint(count), err
}
// Build query creates a mongo query from the given sub, pred, obj
func (m *Mongo) BuildQuery(graph, sub, pred string, obj interface{}, overrides *Overrides) bson.M {
query := bson.M{"g": graph}
sEmpty := isEmpty(sub)
pEmpty := isEmpty(pred)
oEmpty := isEmpty(obj)
switch {
case graph == "":
// all items in collection, never executed
case sEmpty && pEmpty && oEmpty:
// nil nil nil
case !sEmpty && pEmpty && oEmpty:
// sub nil nil
query["s"] = sub
case !sEmpty && !pEmpty && oEmpty:
// sub pred nil
query["s"] = sub
query["p"] = pred
case !sEmpty && pEmpty && !oEmpty:
// sub nil obj
query["s"] = sub
query["o"] = obj
case !sEmpty && !pEmpty && !oEmpty:
// sub pred obj
query["s"] = sub
query["p"] = pred
query["o"] = obj
case sEmpty && !pEmpty && oEmpty:
// nil pred nil
query["p"] = pred
case sEmpty && pEmpty && !oEmpty:
// nil nil obj
query["o"] = obj
case sEmpty && !pEmpty && !oEmpty:
// nil pred obj
query["p"] = pred
query["o"] = obj
}
if overrides != nil {
if len(overrides.Subs) > 0 {
query["s"] = bson.M{"$in": overrides.Subs}
}
if len(overrides.Preds) > 0 {
query["p"] = bson.M{"$in": overrides.Preds}
}
if len(overrides.Objs) > 0 {
query["o"] = bson.M{"$in": overrides.Objs}
}
}
return query
}
// Triples
func (m *Mongo) Triples(graph, sub, pred string, obj interface{}, options *Options) []*Triple {
g, ok := m.Graphs[graph]
if !ok {
log.Error("missing graph ", graph)
return nil
}
sessionCopy := m.Session.Copy()
defer sessionCopy.Close()
col := sessionCopy.DB(m.DBName).C(g.ColName)
var query bson.M
if options != nil {
query = m.BuildQuery(graph, sub, pred, obj, options.TripleOverrides)
} else {
query = m.BuildQuery(graph, sub, pred, obj, nil)
}
// Note that skip only makes sense in the case of sorted results, so if
// no orderby is given a default subject is used.
var iter *mgo.Iter
switch {
default:
// no options
iter = col.Find(query).Iter()
case options == nil:
// no options
iter = col.Find(query).Iter()
case options.Limit == 0 && options.Offset == 0 && options.OrderBy == "":
// no options
iter = col.Find(query).Iter()
case options.Limit != 0 && options.Offset != 0 && options.OrderBy != "":
// limit, orderby
iter = col.Find(query).Limit(int(options.Limit)).Skip(int(options.Offset)).Sort(options.OrderBy).Iter()
case options.Limit != 0 && options.Offset != 0 && options.OrderBy == "":
// limit, skip
iter = col.Find(query).Limit(int(options.Limit)).Skip(int(options.Offset)).Sort("s").Iter()
case options.Limit != 0 && options.Offset == 0 && options.OrderBy != "":
// limit, orderby
iter = col.Find(query).Limit(int(options.Limit)).Sort(options.OrderBy).Iter()
case options.Limit != 0 && options.Offset == 0 && options.OrderBy == "":
// limit
iter = col.Find(query).Limit(int(options.Limit)).Iter()
case options.Limit == 0 && options.Offset != 0 && options.OrderBy != "":
// skip, orderby
iter = col.Find(query).Skip(int(options.Offset)).Sort(options.OrderBy).Iter()
case options.Limit == 0 && options.Offset != 0 && options.OrderBy == "":
// skip
iter = col.Find(query).Skip(int(options.Offset)).Sort("s").Iter()
case options.Limit == 0 && options.Offset == 0 && options.OrderBy != "":
// orderby
iter = col.Find(query).Sort(options.OrderBy).Iter()
}
tripleDocs := []*TripleDoc{}
err := iter.All(&tripleDocs)
if err != nil {
log.Error(err)
return nil
}
results := []*Triple{}
for _, res := range tripleDocs {
results = append(results, &Triple{res.Sub, res.Pred, res.Obj})
}
return results
}
// Pinger checks for connection loss. It starts at a random
// time to prevent all apps pinging simultaneously. Pings are
// sent every 5 seconds.
func (m *Mongo) Pinger() {
rand.Seed(time.Now().UTC().UnixNano())
// Start pinger on a random schedule
time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
for {
log.Infof("ping hosts:%s", m.Hosts)
err := m.Session.Ping()
if err != nil {
log.Error(err)
m.Connect(m.Hosts)
return
}
time.Sleep(40 * time.Second)
}
}
// Close shuts down the mongo db session.
func (m *Mongo) Close() {
m.Session.Close()
}