You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

241 lines
6.4 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. package mongodb
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer2"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  8. "github.com/chrislusf/seaweedfs/weed/util"
  9. "go.mongodb.org/mongo-driver/bson"
  10. "go.mongodb.org/mongo-driver/mongo"
  11. "go.mongodb.org/mongo-driver/mongo/options"
  12. "go.mongodb.org/mongo-driver/x/bsonx"
  13. "strings"
  14. "time"
  15. )
  16. func init() {
  17. filer2.Stores = append(filer2.Stores, &MongodbStore{})
  18. }
  19. type MongodbStore struct {
  20. connect *mongo.Client
  21. database string
  22. collectionName string
  23. }
  24. type Model struct {
  25. Directory string `bson:"directory"`
  26. Name string `bson:"name"`
  27. Meta []byte `bson:"meta"`
  28. }
  29. func (store *MongodbStore) GetName() string {
  30. return "mongodb"
  31. }
  32. func (store *MongodbStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  33. store.database = configuration.GetString(prefix + "database")
  34. store.collectionName = "filemeta"
  35. poolSize := configuration.GetInt(prefix + "option_pool_size")
  36. return store.connection(configuration.GetString(prefix+"uri"), uint64(poolSize))
  37. }
  38. func (store *MongodbStore) connection(uri string, poolSize uint64) (err error) {
  39. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  40. opts := options.Client().ApplyURI(uri)
  41. if poolSize > 0 {
  42. opts.SetMaxPoolSize(poolSize)
  43. }
  44. client, err := mongo.Connect(ctx, opts)
  45. if err != nil {
  46. return err
  47. }
  48. c := client.Database(store.database).Collection(store.collectionName)
  49. err = store.indexUnique(c)
  50. store.connect = client
  51. return err
  52. }
  53. func (store *MongodbStore) createIndex(c *mongo.Collection, index mongo.IndexModel, opts *options.CreateIndexesOptions) error {
  54. _, err := c.Indexes().CreateOne(context.Background(), index, opts)
  55. return err
  56. }
  57. func (store *MongodbStore) indexUnique(c *mongo.Collection) error {
  58. opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
  59. unique := new(bool)
  60. *unique = true
  61. index := mongo.IndexModel{
  62. Keys: bsonx.Doc{{Key: "directory", Value: bsonx.Int32(1)}, {Key: "name", Value: bsonx.Int32(1)}},
  63. Options: &options.IndexOptions{
  64. Unique: unique,
  65. },
  66. }
  67. return store.createIndex(c, index, opts)
  68. }
  69. func (store *MongodbStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  70. return ctx, nil
  71. }
  72. func (store *MongodbStore) CommitTransaction(ctx context.Context) error {
  73. return nil
  74. }
  75. func (store *MongodbStore) RollbackTransaction(ctx context.Context) error {
  76. return nil
  77. }
  78. func (store *MongodbStore) InsertEntry(ctx context.Context, entry *filer2.Entry) (err error) {
  79. dir, name := entry.FullPath.DirAndName()
  80. meta, err := entry.EncodeAttributesAndChunks()
  81. if err != nil {
  82. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  83. }
  84. c := store.connect.Database(store.database).Collection(store.collectionName)
  85. _, err = c.InsertOne(ctx, Model{
  86. Directory: dir,
  87. Name: name,
  88. Meta: meta,
  89. })
  90. return nil
  91. }
  92. func (store *MongodbStore) UpdateEntry(ctx context.Context, entry *filer2.Entry) (err error) {
  93. return store.InsertEntry(ctx, entry)
  94. }
  95. func (store *MongodbStore) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer2.Entry, err error) {
  96. dir, name := fullpath.DirAndName()
  97. var data Model
  98. var where = bson.M{"directory": dir, "name": name}
  99. err = store.connect.Database(store.database).Collection(store.collectionName).FindOne(ctx, where).Decode(&data)
  100. if err != mongo.ErrNoDocuments && err != nil {
  101. return nil, filer_pb.ErrNotFound
  102. }
  103. if len(data.Meta) == 0 {
  104. return nil, filer_pb.ErrNotFound
  105. }
  106. entry = &filer2.Entry{
  107. FullPath: fullpath,
  108. }
  109. err = entry.DecodeAttributesAndChunks(data.Meta)
  110. if err != nil {
  111. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  112. }
  113. return entry, nil
  114. }
  115. func (store *MongodbStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) error {
  116. dir, name := fullpath.DirAndName()
  117. where := bson.M{"directory": dir, "name": name}
  118. _, err := store.connect.Database(store.database).Collection(store.collectionName).DeleteOne(ctx, where)
  119. if err != nil {
  120. return fmt.Errorf("delete %s : %v", fullpath, err)
  121. }
  122. return nil
  123. }
  124. func (store *MongodbStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) error {
  125. where := bson.M{"directory": fullpath}
  126. _, err := store.connect.Database(store.database).Collection(store.collectionName).DeleteMany(ctx, where)
  127. if err != nil {
  128. return fmt.Errorf("delete %s : %v", fullpath, err)
  129. }
  130. return nil
  131. }
  132. func (store *MongodbStore) ListDirectoryPrefixedEntries(ctx context.Context, fullpath util.FullPath, startFileName string, inclusive bool, limit int, prefix string) (entries []*filer2.Entry, err error) {
  133. count := 0
  134. notPrefixed, err := store.ListDirectoryEntries(ctx, fullpath, startFileName, inclusive, limit)
  135. if err != nil {
  136. return nil, err
  137. }
  138. if prefix == "" {
  139. return notPrefixed, nil
  140. }
  141. for count < limit {
  142. for _, entry := range notPrefixed {
  143. if strings.HasPrefix(entry.Name(), prefix) {
  144. count++
  145. entries = append(entries, entry)
  146. }
  147. }
  148. if count >= limit {
  149. break
  150. }
  151. notPrefixed, err = store.ListDirectoryEntries(ctx, fullpath, startFileName, inclusive, limit)
  152. if err != nil {
  153. return nil, err
  154. }
  155. }
  156. return entries, nil
  157. }
  158. func (store *MongodbStore) ListDirectoryEntries(ctx context.Context, fullpath util.FullPath, startFileName string, inclusive bool, limit int) (entries []*filer2.Entry, err error) {
  159. var where = bson.M{"directory": string(fullpath), "name": bson.M{"$gt": startFileName}}
  160. if inclusive {
  161. where["name"] = bson.M{
  162. "$gte": startFileName,
  163. }
  164. }
  165. optLimit := int64(limit)
  166. opts := &options.FindOptions{Limit: &optLimit, Sort: bson.M{"name": 1}}
  167. cur, err := store.connect.Database(store.database).Collection(store.collectionName).Find(ctx, where, opts)
  168. for cur.Next(ctx) {
  169. var data Model
  170. err := cur.Decode(&data)
  171. if err != nil && err != mongo.ErrNoDocuments {
  172. return nil, err
  173. }
  174. entry := &filer2.Entry{
  175. FullPath: util.NewFullPath(string(fullpath), data.Name),
  176. }
  177. if decodeErr := entry.DecodeAttributesAndChunks(data.Meta); decodeErr != nil {
  178. err = decodeErr
  179. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  180. break
  181. }
  182. entries = append(entries, entry)
  183. }
  184. if err := cur.Close(ctx); err != nil {
  185. glog.V(0).Infof("list iterator close: %v", err)
  186. }
  187. return entries, err
  188. }
  189. func (store *MongodbStore) Shutdown() {
  190. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  191. store.connect.Disconnect(ctx)
  192. }