This repository has been archived by the owner on Jul 1, 2021. It is now read-only.
/
mongodb_ds.go
224 lines (177 loc) · 4.71 KB
/
mongodb_ds.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
// Copyright © 2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: BSD-2-Clause
package vds
import (
"fmt"
"log"
"strings"
"github.com/vmware/virtual-security-module/config"
"github.com/vmware/virtual-security-module/util"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const (
mongoDSType = "MongoDBDataStore"
dbCollectionName = "VSMEntries"
)
func init() {
if err := DataStoreRegistrar.Register(mongoDSType, NewMongoDBDS()); err != nil {
panic(fmt.Sprintf("Failed to register data store type %v: %v", mongoDSType, err))
}
}
// An implementation of a datastore based on MongoDB.
type MongoDBDS struct {
dbSession *mgo.Session
location string
}
func NewMongoDBDS() *MongoDBDS {
return &MongoDBDS{}
}
func (ds *MongoDBDS) Init(cfg *config.DataStoreConfig) error {
connectionString := cfg.ConnectionString
if connectionString == "" {
return util.ErrBadConfig
}
connectStrAndSettings := strings.Split(connectionString, ";")
if len(connectStrAndSettings) == 0 {
return util.ErrBadConfig
}
connectStr := connectStrAndSettings[0]
session, err := mgo.Dial(connectStr)
if err != nil {
return err
}
for i := 1; i < len(connectStrAndSettings); i++ {
keyVal := strings.SplitN(connectStrAndSettings[i], "=", 2)
if len(keyVal) != 2 {
log.Printf("%s: bad key-val %v\n", mongoDSType, keyVal)
return util.ErrBadConfig
}
key := keyVal[0]
val := keyVal[1]
switch strings.ToUpper(key) {
case "WRITE_CONCERN":
safe := session.Safe()
safe.WMode = val
session.SetSafe(safe)
default:
log.Printf("%s: connectionString: unrecognized key: %s\n", mongoDSType, key)
return util.ErrBadConfig
}
}
ds.dbSession = session
ds.location = connectStr
return nil
}
func (ds *MongoDBDS) CompleteInit(cfg *config.DataStoreConfig) error {
return nil
}
func (ds *MongoDBDS) Initialized() bool {
return ds.dbSession != nil
}
func (ds *MongoDBDS) CreateEntry(entry *DataStoreEntry) error {
session, collection := ds.getSessionAndCollection()
defer session.Close()
doc := translateToMongoDocument(entry)
err := collection.Insert(doc)
if err != nil {
return translateMongoError(err)
}
return nil
}
func (ds *MongoDBDS) ReadEntry(entryId string) (*DataStoreEntry, error) {
session, collection := ds.getSessionAndCollection()
defer session.Close()
doc := bson.M{}
err := collection.Find(bson.M{"_id": entryId}).One(&doc)
if err != nil {
return nil, translateMongoError(err)
}
dsEntry, err := translatefromMongoDocument(&doc)
if err != nil {
return nil, err
}
return dsEntry, nil
}
func (ds *MongoDBDS) DeleteEntry(entryId string) error {
session, collection := ds.getSessionAndCollection()
defer session.Close()
err := collection.Remove(bson.M{"_id": entryId})
if err != nil {
return translateMongoError(err)
}
return err
}
func (ds *MongoDBDS) SearchChildEntries(parentEntryId string) ([]*DataStoreEntry, error) {
session, collection := ds.getSessionAndCollection()
defer session.Close()
suffix := "([^/]+)"
if !strings.HasSuffix(parentEntryId, "/") {
suffix = "/" + suffix
}
pattern := "^" + parentEntryId + suffix + "$"
var docs []*bson.M
err := collection.Find(bson.M{"_id": bson.M{"$regex": bson.RegEx{Pattern: pattern}}}).All(&docs)
if err != nil {
return []*DataStoreEntry{}, translateMongoError(err)
}
dsEntries := make([]*DataStoreEntry, 0, len(docs))
for _, doc := range docs {
dsEntry, err := translatefromMongoDocument(doc)
if err != nil {
return []*DataStoreEntry{}, err
}
dsEntries = append(dsEntries, dsEntry)
}
return dsEntries, err
}
func (ds *MongoDBDS) Type() string {
return mongoDSType
}
func (ds *MongoDBDS) Location() string {
return ds.location
}
func (ds *MongoDBDS) getSessionAndCollection() (*mgo.Session, *mgo.Collection) {
session := ds.dbSession.Copy()
db := session.DB("")
collection := db.C(dbCollectionName)
return session, collection
}
func translateToMongoDocument(dsEntry *DataStoreEntry) *bson.M {
return &bson.M{
"_id": dsEntry.Id,
"data": dsEntry.Data,
"metaData": dsEntry.MetaData,
}
}
func translatefromMongoDocument(mongoDoc *bson.M) (*DataStoreEntry, error) {
doc := map[string]interface{}(*mongoDoc)
id, ok := doc["_id"].(string)
if !ok {
return nil, util.ErrInternal
}
data, ok := doc["data"].([]byte)
if !ok {
return nil, util.ErrInternal
}
metaData, ok := doc["metaData"].(string)
if !ok {
return nil, util.ErrInternal
}
return &DataStoreEntry{
Id: id,
Data: data,
MetaData: metaData,
}, nil
}
func translateMongoError(mongoError error) error {
switch mongoError {
case mgo.ErrNotFound:
return util.ErrNotFound
default:
if strings.Contains(mongoError.Error(), "E11000 duplicate key error") {
return util.ErrAlreadyExists
}
return mongoError
}
}