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.

247 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. var lastFileName string
  142. for count < limit {
  143. for _, entry := range notPrefixed {
  144. lastFileName = entry.Name()
  145. if strings.HasPrefix(entry.Name(), prefix) {
  146. count++
  147. entries = append(entries, entry)
  148. }
  149. }
  150. if count >= limit {
  151. break
  152. }
  153. notPrefixed, err = store.ListDirectoryEntries(ctx, fullpath, lastFileName, inclusive, limit)
  154. if err != nil {
  155. return nil, err
  156. }
  157. if len(notPrefixed) == 0 {
  158. break
  159. }
  160. }
  161. return entries, nil
  162. }
  163. func (store *MongodbStore) ListDirectoryEntries(ctx context.Context, fullpath util.FullPath, startFileName string, inclusive bool, limit int) (entries []*filer2.Entry, err error) {
  164. var where = bson.M{"directory": string(fullpath), "name": bson.M{"$gt": startFileName}}
  165. if inclusive {
  166. where["name"] = bson.M{
  167. "$gte": startFileName,
  168. }
  169. }
  170. optLimit := int64(limit)
  171. opts := &options.FindOptions{Limit: &optLimit, Sort: bson.M{"name": 1}}
  172. cur, err := store.connect.Database(store.database).Collection(store.collectionName).Find(ctx, where, opts)
  173. for cur.Next(ctx) {
  174. var data Model
  175. err := cur.Decode(&data)
  176. if err != nil && err != mongo.ErrNoDocuments {
  177. return nil, err
  178. }
  179. entry := &filer2.Entry{
  180. FullPath: util.NewFullPath(string(fullpath), data.Name),
  181. }
  182. if decodeErr := entry.DecodeAttributesAndChunks(data.Meta); decodeErr != nil {
  183. err = decodeErr
  184. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  185. break
  186. }
  187. entries = append(entries, entry)
  188. }
  189. if err := cur.Close(ctx); err != nil {
  190. glog.V(0).Infof("list iterator close: %v", err)
  191. }
  192. return entries, err
  193. }
  194. func (store *MongodbStore) Shutdown() {
  195. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  196. store.connect.Disconnect(ctx)
  197. }