2020-09-02 04:58:57 +00:00
|
|
|
package mongodb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-09-03 00:19:14 +00:00
|
|
|
"fmt"
|
2020-09-02 04:58:57 +00:00
|
|
|
"github.com/chrislusf/seaweedfs/weed/filer"
|
2020-09-03 00:19:14 +00:00
|
|
|
"github.com/chrislusf/seaweedfs/weed/glog"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
2021-06-06 20:12:01 +00:00
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
2020-09-02 04:58:57 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func (store *MongodbStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
|
2020-09-03 00:19:14 +00:00
|
|
|
|
|
|
|
dir, name := genDirAndName(key)
|
|
|
|
|
|
|
|
c := store.connect.Database(store.database).Collection(store.collectionName)
|
|
|
|
|
2021-06-06 20:12:01 +00:00
|
|
|
opts := options.Update().SetUpsert(true)
|
|
|
|
filter := bson.D{{"directory", dir}, {"name", name}}
|
|
|
|
update := bson.D{{"$set", bson.D{{"meta", value}}}}
|
|
|
|
|
|
|
|
_, err = c.UpdateOne(ctx, filter, update, opts)
|
2020-09-03 00:19:14 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("kv put: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2020-09-02 04:58:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (store *MongodbStore) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
|
2020-09-03 00:19:14 +00:00
|
|
|
dir, name := genDirAndName(key)
|
|
|
|
|
|
|
|
var data Model
|
|
|
|
|
|
|
|
var where = bson.M{"directory": dir, "name": name}
|
|
|
|
err = store.connect.Database(store.database).Collection(store.collectionName).FindOne(ctx, where).Decode(&data)
|
|
|
|
if err != mongo.ErrNoDocuments && err != nil {
|
2020-09-03 04:42:12 +00:00
|
|
|
glog.Errorf("kv get: %v", err)
|
2020-09-03 00:19:14 +00:00
|
|
|
return nil, filer.ErrKvNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(data.Meta) == 0 {
|
|
|
|
return nil, filer.ErrKvNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return data.Meta, nil
|
2020-09-02 04:58:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (store *MongodbStore) KvDelete(ctx context.Context, key []byte) (err error) {
|
2020-09-03 00:19:14 +00:00
|
|
|
|
|
|
|
dir, name := genDirAndName(key)
|
|
|
|
|
|
|
|
where := bson.M{"directory": dir, "name": name}
|
|
|
|
_, err = store.connect.Database(store.database).Collection(store.collectionName).DeleteOne(ctx, where)
|
|
|
|
if err != nil {
|
2020-09-03 04:42:12 +00:00
|
|
|
return fmt.Errorf("kv delete: %v", err)
|
2020-09-03 00:19:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func genDirAndName(key []byte) (dir string, name string) {
|
|
|
|
for len(key) < 8 {
|
|
|
|
key = append(key, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
dir = string(key[:8])
|
|
|
|
name = string(key[8:])
|
|
|
|
|
|
|
|
return
|
2020-09-02 04:58:57 +00:00
|
|
|
}
|