-
Notifications
You must be signed in to change notification settings - Fork 0
/
creator.go
109 lines (94 loc) · 2.21 KB
/
creator.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
package main
import (
"fmt"
"log"
"strings"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
)
type dbCreator struct {
session *mgo.Session
}
func (d *dbCreator) Init() {
var err error
d.session, err = mgo.DialWithTimeout(daemonURL, writeTimeout)
if err != nil {
log.Fatal(err)
}
d.session.SetMode(mgo.Eventual, false)
}
func (d *dbCreator) DBExists(dbName string) bool {
dbs, err := d.session.DatabaseNames()
if err != nil {
log.Fatal(err)
}
for _, name := range dbs {
if name == dbName {
return true
}
}
return false
}
func (d *dbCreator) RemoveOldDB(dbName string) error {
collections, err := d.session.DB(dbName).CollectionNames()
if err != nil {
return err
}
for _, name := range collections {
d.session.DB(dbName).C(name).DropCollection()
}
return nil
}
func (d *dbCreator) CreateDB(dbName string) error {
cmd := make(bson.D, 0, 4)
cmd = append(cmd, bson.DocElem{"create", collectionName})
// wiredtiger settings
cmd = append(cmd, bson.DocElem{
"storageEngine", map[string]interface{}{
"wiredTiger": map[string]interface{}{
"configString": "block_compressor=snappy",
},
},
})
err := d.session.DB(dbName).Run(cmd, nil)
if err != nil {
if strings.Contains(err.Error(), "already exists") {
return nil
}
return fmt.Errorf("create collection err: %v", err)
}
collection := d.session.DB(dbName).C(collectionName)
var key []string
if documentPer {
key = []string{"measurement", "tags.hostname", timestampField}
} else {
key = []string{aggKeyID, "measurement", "tags.hostname"}
}
index := mgo.Index{
Key: key,
Unique: false, // Unique does not work on the entire array of tags!
Background: false,
Sparse: false,
}
err = collection.EnsureIndex(index)
if err != nil {
return fmt.Errorf("create basic index err: %v", err)
}
// To make updates for new records more efficient, we need a efficient doc
// lookup index
if !documentPer {
err = collection.EnsureIndex(mgo.Index{
Key: []string{aggDocID},
Unique: false,
Background: false,
Sparse: false,
})
if err != nil {
return fmt.Errorf("create agg doc index err: %v", err)
}
}
return nil
}
func (d *dbCreator) Close() {
d.session.Close()
}