forked from perkeep/perkeep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongokv.go
274 lines (240 loc) · 6.64 KB
/
mongokv.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
/*
Copyright 2013 The Camlistore Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package mongo provides an implementation of sorted.KeyValue
// using MongoDB.
package mongo
import (
"bytes"
"errors"
"sync"
"time"
"camlistore.org/pkg/jsonconfig"
"camlistore.org/pkg/sorted"
"camlistore.org/third_party/labix.org/v2/mgo"
"camlistore.org/third_party/labix.org/v2/mgo/bson"
)
// We explicitely separate the key and the value in a document,
// instead of simply storing as key:value, to avoid problems
// such as "." being an illegal char in a key name. Also because
// there is no way to do partial matching for key names (one can
// only check for their existence with bson.M{$exists: true}).
const (
CollectionName = "keys" // MongoDB collection, equiv. to SQL table
mgoKey = "k"
mgoValue = "v"
)
func init() {
sorted.RegisterKeyValue("mongo", newKeyValueFromJSONConfig)
}
func newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) {
ins := &instance{
server: cfg.OptionalString("host", "localhost"),
database: cfg.RequiredString("database"),
user: cfg.OptionalString("user", ""),
password: cfg.OptionalString("password", ""),
}
if err := cfg.Validate(); err != nil {
return nil, err
}
db, err := ins.getCollection()
if err != nil {
return nil, err
}
return &keyValue{db: db, session: ins.session}, nil
}
// Implementation of Iterator
type iter struct {
res bson.M
*mgo.Iter
end []byte
}
func (it *iter) Next() bool {
if !it.Iter.Next(&it.res) {
return false
}
if len(it.end) > 0 && bytes.Compare(it.KeyBytes(), it.end) >= 0 {
return false
}
return true
}
func (it *iter) Key() string {
key, ok := (it.res[mgoKey]).(string)
if !ok {
return ""
}
return key
}
func (it *iter) KeyBytes() []byte {
// TODO(bradfitz,mpl): this is less efficient than the string way. we should
// do better here, somehow, like all the other KeyValue iterators.
// For now:
return []byte(it.Key())
}
func (it *iter) Value() string {
value, ok := (it.res[mgoValue]).(string)
if !ok {
return ""
}
return value
}
func (it *iter) ValueBytes() []byte {
// TODO(bradfitz,mpl): this is less efficient than the string way. we should
// do better here, somehow, like all the other KeyValue iterators.
// For now:
return []byte(it.Value())
}
func (it *iter) Close() error {
return it.Iter.Close()
}
// Implementation of KeyValue
type keyValue struct {
session *mgo.Session // so we can close it
mu sync.Mutex // guards db
db *mgo.Collection
}
func (kv *keyValue) Get(key string) (string, error) {
kv.mu.Lock()
defer kv.mu.Unlock()
res := bson.M{}
q := kv.db.Find(&bson.M{mgoKey: key})
err := q.One(&res)
if err != nil {
if err == mgo.ErrNotFound {
return "", sorted.ErrNotFound
} else {
return "", err
}
}
return res[mgoValue].(string), err
}
func (kv *keyValue) Find(start, end string) sorted.Iterator {
kv.mu.Lock()
defer kv.mu.Unlock()
it := kv.db.Find(&bson.M{mgoKey: &bson.M{"$gte": start}}).Sort(mgoKey).Iter()
return &iter{res: bson.M{}, Iter: it, end: []byte(end)}
}
func (kv *keyValue) Set(key, value string) error {
kv.mu.Lock()
defer kv.mu.Unlock()
_, err := kv.db.Upsert(&bson.M{mgoKey: key}, &bson.M{mgoKey: key, mgoValue: value})
return err
}
// Delete removes the document with the matching key.
func (kv *keyValue) Delete(key string) error {
kv.mu.Lock()
defer kv.mu.Unlock()
err := kv.db.Remove(&bson.M{mgoKey: key})
if err == mgo.ErrNotFound {
return nil
}
return err
}
// Wipe removes all documents from the collection.
func (kv *keyValue) Wipe() error {
kv.mu.Lock()
defer kv.mu.Unlock()
_, err := kv.db.RemoveAll(nil)
return err
}
type batch interface {
Mutations() []sorted.Mutation
}
func (kv *keyValue) BeginBatch() sorted.BatchMutation {
return sorted.NewBatchMutation()
}
func (kv *keyValue) CommitBatch(bm sorted.BatchMutation) error {
b, ok := bm.(batch)
if !ok {
return errors.New("invalid batch type")
}
kv.mu.Lock()
defer kv.mu.Unlock()
for _, m := range b.Mutations() {
if m.IsDelete() {
if err := kv.db.Remove(bson.M{mgoKey: m.Key()}); err != nil {
return err
}
} else {
if _, err := kv.db.Upsert(&bson.M{mgoKey: m.Key()}, &bson.M{mgoKey: m.Key(), mgoValue: m.Value()}); err != nil {
return err
}
}
}
return nil
}
func (kv *keyValue) Close() error {
kv.session.Close()
return nil
}
// Ping tests if MongoDB on host can be dialed.
func Ping(host string, timeout time.Duration) bool {
return (&instance{server: host}).ping(timeout)
}
// instance helps with the low level details about
// the connection to MongoDB.
type instance struct {
server string
database string
user string
password string
session *mgo.Session
}
func (ins *instance) url() string {
if ins.user == "" || ins.password == "" {
return ins.server
}
return ins.user + ":" + ins.password + "@" + ins.server + "/" + ins.database
}
// ping won't work with old (1.2) mongo servers.
func (ins *instance) ping(timeout time.Duration) bool {
session, err := mgo.DialWithTimeout(ins.url(), timeout)
if err != nil {
return false
}
defer session.Close()
session.SetSyncTimeout(timeout)
if err = session.Ping(); err != nil {
return false
}
return true
}
func (ins *instance) getConnection() (*mgo.Session, error) {
if ins.session != nil {
return ins.session, nil
}
// TODO(mpl): do some "client caching" as in mysql, to avoid systematically dialing?
session, err := mgo.Dial(ins.url())
if err != nil {
return nil, err
}
session.SetMode(mgo.Monotonic, true)
session.SetSafe(&mgo.Safe{}) // so we get an ErrNotFound error when deleting an absent key
ins.session = session
return session, nil
}
// TODO(mpl): I'm only calling getCollection at the beginning, and
// keeping the collection around and reusing it everywhere, instead
// of calling getCollection everytime, because that's the easiest.
// But I can easily change that. Gustavo says it does not make
// much difference either way.
// Brad, what do you think?
func (ins *instance) getCollection() (*mgo.Collection, error) {
session, err := ins.getConnection()
if err != nil {
return nil, err
}
session.SetSafe(&mgo.Safe{})
session.SetMode(mgo.Strong, true)
c := session.DB(ins.database).C(CollectionName)
return c, nil
}