mongodb_store.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package mongodb
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "fmt"
  7. "os"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/filer"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  12. "github.com/seaweedfs/seaweedfs/weed/util"
  13. "go.mongodb.org/mongo-driver/bson"
  14. "go.mongodb.org/mongo-driver/mongo"
  15. "go.mongodb.org/mongo-driver/mongo/options"
  16. )
  17. func init() {
  18. filer.Stores = append(filer.Stores, &MongodbStore{})
  19. }
  20. type MongodbStore struct {
  21. connect *mongo.Client
  22. database string
  23. collectionName string
  24. }
  25. type Model struct {
  26. Directory string `bson:"directory"`
  27. Name string `bson:"name"`
  28. Meta []byte `bson:"meta"`
  29. }
  30. func (store *MongodbStore) GetName() string {
  31. return "mongodb"
  32. }
  33. func (store *MongodbStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  34. store.database = configuration.GetString(prefix + "database")
  35. store.collectionName = "filemeta"
  36. poolSize := configuration.GetInt(prefix + "option_pool_size")
  37. uri := configuration.GetString(prefix + "uri")
  38. ssl := configuration.GetBool(prefix + "ssl")
  39. sslCAFile := configuration.GetString(prefix + "ssl_ca_file")
  40. sslCertFile := configuration.GetString(prefix + "ssl_cert_file")
  41. sslKeyFile := configuration.GetString(prefix + "ssl_key_file")
  42. username := configuration.GetString(prefix + "username")
  43. password := configuration.GetString(prefix + "password")
  44. insecure_skip_verify := configuration.GetBool(prefix + "insecure_skip_verify")
  45. return store.connection(uri, uint64(poolSize), ssl, sslCAFile, sslCertFile, sslKeyFile, username, password, insecure_skip_verify)
  46. }
  47. func (store *MongodbStore) connection(uri string, poolSize uint64, ssl bool, sslCAFile, sslCertFile, sslKeyFile string, username, password string, insecure bool) (err error) {
  48. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  49. defer cancel()
  50. opts := options.Client().ApplyURI(uri)
  51. if poolSize > 0 {
  52. opts.SetMaxPoolSize(poolSize)
  53. }
  54. if ssl {
  55. tlsConfig, err := configureTLS(sslCAFile, sslCertFile, sslKeyFile, insecure)
  56. if err != nil {
  57. return err
  58. }
  59. opts.SetTLSConfig(tlsConfig)
  60. }
  61. if username != "" && password != "" {
  62. creds := options.Credential{
  63. Username: username,
  64. Password: password,
  65. }
  66. opts.SetAuth(creds)
  67. }
  68. client, err := mongo.Connect(ctx, opts)
  69. if err != nil {
  70. return err
  71. }
  72. c := client.Database(store.database).Collection(store.collectionName)
  73. err = store.indexUnique(c)
  74. store.connect = client
  75. return err
  76. }
  77. func configureTLS(caFile, certFile, keyFile string, insecure bool) (*tls.Config, error) {
  78. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  79. if err != nil {
  80. return nil, fmt.Errorf("could not load client key pair: %s", err)
  81. }
  82. caCert, err := os.ReadFile(caFile)
  83. if err != nil {
  84. return nil, fmt.Errorf("could not read CA certificate: %s", err)
  85. }
  86. caCertPool := x509.NewCertPool()
  87. if !caCertPool.AppendCertsFromPEM(caCert) {
  88. return nil, fmt.Errorf("failed to append CA certificate")
  89. }
  90. tlsConfig := &tls.Config{
  91. Certificates: []tls.Certificate{cert},
  92. RootCAs: caCertPool,
  93. InsecureSkipVerify: insecure,
  94. }
  95. return tlsConfig, nil
  96. }
  97. func (store *MongodbStore) createIndex(c *mongo.Collection, index mongo.IndexModel, opts *options.CreateIndexesOptions) error {
  98. _, err := c.Indexes().CreateOne(context.Background(), index, opts)
  99. return err
  100. }
  101. func (store *MongodbStore) indexUnique(c *mongo.Collection) error {
  102. opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
  103. unique := new(bool)
  104. *unique = true
  105. index := mongo.IndexModel{
  106. Keys: bson.D{{Key: "directory", Value: int32(1)}, {Key: "name", Value: int32(1)}},
  107. Options: &options.IndexOptions{
  108. Unique: unique,
  109. },
  110. }
  111. return store.createIndex(c, index, opts)
  112. }
  113. func (store *MongodbStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  114. return ctx, nil
  115. }
  116. func (store *MongodbStore) CommitTransaction(ctx context.Context) error {
  117. return nil
  118. }
  119. func (store *MongodbStore) RollbackTransaction(ctx context.Context) error {
  120. return nil
  121. }
  122. func (store *MongodbStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  123. return store.UpdateEntry(ctx, entry)
  124. }
  125. func (store *MongodbStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  126. dir, name := entry.FullPath.DirAndName()
  127. meta, err := entry.EncodeAttributesAndChunks()
  128. if err != nil {
  129. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  130. }
  131. if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
  132. meta = util.MaybeGzipData(meta)
  133. }
  134. c := store.connect.Database(store.database).Collection(store.collectionName)
  135. opts := options.Update().SetUpsert(true)
  136. filter := bson.D{{"directory", dir}, {"name", name}}
  137. update := bson.D{{"$set", bson.D{{"meta", meta}}}}
  138. _, err = c.UpdateOne(ctx, filter, update, opts)
  139. if err != nil {
  140. return fmt.Errorf("UpdateEntry %s: %v", entry.FullPath, err)
  141. }
  142. return nil
  143. }
  144. func (store *MongodbStore) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
  145. dir, name := fullpath.DirAndName()
  146. var data Model
  147. var where = bson.M{"directory": dir, "name": name}
  148. err = store.connect.Database(store.database).Collection(store.collectionName).FindOne(ctx, where).Decode(&data)
  149. if err != mongo.ErrNoDocuments && err != nil {
  150. glog.Errorf("find %s: %v", fullpath, err)
  151. return nil, filer_pb.ErrNotFound
  152. }
  153. if len(data.Meta) == 0 {
  154. return nil, filer_pb.ErrNotFound
  155. }
  156. entry = &filer.Entry{
  157. FullPath: fullpath,
  158. }
  159. err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data.Meta))
  160. if err != nil {
  161. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  162. }
  163. return entry, nil
  164. }
  165. func (store *MongodbStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) error {
  166. dir, name := fullpath.DirAndName()
  167. where := bson.M{"directory": dir, "name": name}
  168. _, err := store.connect.Database(store.database).Collection(store.collectionName).DeleteMany(ctx, where)
  169. if err != nil {
  170. return fmt.Errorf("delete %s : %v", fullpath, err)
  171. }
  172. return nil
  173. }
  174. func (store *MongodbStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) error {
  175. where := bson.M{"directory": fullpath}
  176. _, err := store.connect.Database(store.database).Collection(store.collectionName).DeleteMany(ctx, where)
  177. if err != nil {
  178. return fmt.Errorf("delete %s : %v", fullpath, err)
  179. }
  180. return nil
  181. }
  182. func (store *MongodbStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  183. return lastFileName, filer.ErrUnsupportedListDirectoryPrefixed
  184. }
  185. func (store *MongodbStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  186. var where = bson.M{"directory": string(dirPath), "name": bson.M{"$gt": startFileName}}
  187. if includeStartFile {
  188. where["name"] = bson.M{
  189. "$gte": startFileName,
  190. }
  191. }
  192. optLimit := int64(limit)
  193. opts := &options.FindOptions{Limit: &optLimit, Sort: bson.M{"name": 1}}
  194. cur, err := store.connect.Database(store.database).Collection(store.collectionName).Find(ctx, where, opts)
  195. if err != nil {
  196. return lastFileName, fmt.Errorf("failed to list directory entries: find error: %w", err)
  197. }
  198. for cur.Next(ctx) {
  199. var data Model
  200. err = cur.Decode(&data)
  201. if err != nil {
  202. break
  203. }
  204. entry := &filer.Entry{
  205. FullPath: util.NewFullPath(string(dirPath), data.Name),
  206. }
  207. lastFileName = data.Name
  208. if decodeErr := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data.Meta)); decodeErr != nil {
  209. err = decodeErr
  210. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  211. break
  212. }
  213. if !eachEntryFunc(entry) {
  214. break
  215. }
  216. }
  217. if err := cur.Close(ctx); err != nil {
  218. glog.V(0).Infof("list iterator close: %v", err)
  219. }
  220. return lastFileName, err
  221. }
  222. func (store *MongodbStore) Shutdown() {
  223. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  224. store.connect.Disconnect(ctx)
  225. }