-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmds.go
129 lines (101 loc) · 2.1 KB
/
mds.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
package mds
import (
"errors"
"fmt"
"github.com/mitchellh/mapstructure"
"strings"
)
const (
// mds version
VERSION = "0.0.1"
// type: MongoDB
MONGODB = "MongoDB"
// type: Redis
//REDIS = "Redis"
)
type (
// Global Mds
Mds struct {
DataStores map[string]interface{}
Version string
Setuped bool
}
)
// mds to string
func String() string {
return fmt.Sprintf("Version: %s, DataStores Count:%d", mds.Version, len(mds.DataStores))
}
// Debug flag
var DEBUG = false
// Debug output
func Debug(f string, msgs ...string) {
if DEBUG {
fmt.Printf(""+f, strings.Join(([]string)(msgs), " "))
}
}
// Global Mds instance
var mds *Mds = &Mds{
Version: VERSION,
DataStores: make(map[string]interface{}),
Setuped: false,
}
// Mds info
func Get() *Mds {
return mds
}
// Add a datastore
func AddDataStore(dn string, value interface{}) interface{} {
mds.DataStores[dn] = value
Debug("Add the datastore. dn=%s\n", dn)
return value
}
// Get a datastore
func GetDataStore(dn string) (interface{}, error) {
ds := mds.DataStores[dn]
if ds == nil {
return nil, errors.New("Datastore not found")
}
return ds, nil
}
// Get the Mongodb datastore
func GetDataStoreMongoDB(dn string) (*MongoDB, error) {
ds, err := GetDataStore(dn)
if err != nil {
return nil, err
}
if ret, ok := ds.(*MongoDB); ok {
return ret, nil
}
return nil, errors.New("Internal data store type is invalid")
}
// mds setup (Once)
// autoconnect: connect automatically
func Setup(dss []map[string]interface{}, autoconnect bool) error {
if mds.Setuped {
return errors.New("Already setup performed")
}
for _, ds := range dss {
if !ds["Use"].(bool) {
Debug("Skip the datastore. dn=%s\n", ds["Dn"].(string))
continue
}
switch ds["Type"].(string) {
case MONGODB:
mongodb := &MongoDB{}
err := mapstructure.Decode(ds, mongodb)
if err != nil {
return err
}
if autoconnect == true {
Debug("auto-connecting dn=%s\n", ds["Dn"].(string))
err := mongodb.Connect()
if err != nil {
return err
}
}
AddDataStore(mongodb.Dn, mongodb)
}
}
mds.Setuped = true
return nil
}