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.

282 lines
8.6 KiB

  1. package ydb
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  8. "github.com/chrislusf/seaweedfs/weed/util"
  9. "github.com/yandex-cloud/ydb-go-sdk/v2"
  10. "github.com/yandex-cloud/ydb-go-sdk/v2/connect"
  11. "github.com/yandex-cloud/ydb-go-sdk/v2/table"
  12. "path"
  13. "strings"
  14. "time"
  15. )
  16. var (
  17. roTX = table.TxControl(
  18. table.BeginTx(table.WithOnlineReadOnly()),
  19. table.CommitTx(),
  20. )
  21. rwTX = table.TxControl(
  22. table.BeginTx(table.WithSerializableReadWrite()),
  23. table.CommitTx(),
  24. )
  25. )
  26. type YdbStore struct {
  27. SupportBucketTable bool
  28. DB *connect.Connection
  29. connParams connect.ConnectParams
  30. connCtx context.Context
  31. dirBuckets string
  32. tablePathPrefix string
  33. }
  34. func init() {
  35. filer.Stores = append(filer.Stores, &YdbStore{})
  36. }
  37. func (store *YdbStore) GetName() string {
  38. return "ydb"
  39. }
  40. func (store *YdbStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  41. return store.initialize(configuration.GetString(prefix + "coonectionUrl"))
  42. }
  43. func (store *YdbStore) initialize(sqlUrl string) (err error) {
  44. store.SupportBucketTable = false
  45. var cancel context.CancelFunc
  46. store.connCtx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
  47. defer cancel()
  48. store.connParams = connect.MustConnectionString(sqlUrl)
  49. store.DB, err = connect.New(store.connCtx, store.connParams)
  50. if err != nil {
  51. store.DB.Close()
  52. store.DB = nil
  53. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  54. }
  55. defer store.DB.Close()
  56. if err = store.DB.EnsurePathExists(store.connCtx, store.connParams.Database()); err != nil {
  57. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  58. }
  59. return nil
  60. }
  61. func (store *YdbStore) insertOrUpdateEntry(ctx context.Context, entry *filer.Entry, query string) (err error) {
  62. dir, name := entry.FullPath.DirAndName()
  63. meta, err := entry.EncodeAttributesAndChunks()
  64. if err != nil {
  65. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  66. }
  67. fileMeta := FileMeta{util.HashStringToLong(dir), name, dir, meta}
  68. return table.Retry(ctx, store.DB.Table().Pool(),
  69. table.OperationFunc(func(ctx context.Context, s *table.Session) (err error) {
  70. stmt, err := s.Prepare(ctx, store.withPragma(store.getPrefix(dir), query))
  71. if err != nil {
  72. return err
  73. }
  74. _, _, err = stmt.Execute(ctx, rwTX, fileMeta.QueryParameters())
  75. return err
  76. }),
  77. )
  78. }
  79. func (store *YdbStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  80. return store.insertOrUpdateEntry(ctx, entry, insertQuery)
  81. }
  82. func (store *YdbStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  83. return store.insertOrUpdateEntry(ctx, entry, updateQuery)
  84. }
  85. func (store *YdbStore) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
  86. dir, name := fullpath.DirAndName()
  87. var res *table.Result
  88. err = table.Retry(ctx, store.DB.Table().Pool(),
  89. table.OperationFunc(func(ctx context.Context, s *table.Session) (err error) {
  90. stmt, err := s.Prepare(ctx, store.withPragma(store.getPrefix(dir), findQuery))
  91. if err != nil {
  92. return err
  93. }
  94. _, res, err = stmt.Execute(ctx, roTX, table.NewQueryParameters(
  95. table.ValueParam("$dir_hash", ydb.Int64Value(util.HashStringToLong(dir))),
  96. table.ValueParam("$name", ydb.UTF8Value(name))))
  97. return err
  98. }),
  99. )
  100. if err != nil {
  101. return nil, err
  102. }
  103. defer res.Close()
  104. for res.NextSet() {
  105. for res.NextRow() {
  106. res.SeekItem("meta")
  107. entry.FullPath = fullpath
  108. if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(res.String())); err != nil {
  109. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  110. }
  111. return entry, nil
  112. }
  113. }
  114. return nil, filer_pb.ErrNotFound
  115. }
  116. func (store *YdbStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) (err error) {
  117. dir, name := fullpath.DirAndName()
  118. return table.Retry(ctx, store.DB.Table().Pool(),
  119. table.OperationFunc(func(ctx context.Context, s *table.Session) (err error) {
  120. stmt, err := s.Prepare(ctx, store.withPragma(store.getPrefix(dir), deleteQuery))
  121. if err != nil {
  122. return err
  123. }
  124. _, _, err = stmt.Execute(ctx, rwTX, table.NewQueryParameters(
  125. table.ValueParam("$dir_hash", ydb.Int64Value(util.HashStringToLong(dir))),
  126. table.ValueParam("$name", ydb.UTF8Value(name))))
  127. return err
  128. }),
  129. )
  130. }
  131. func (store *YdbStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) (err error) {
  132. dir, _ := fullpath.DirAndName()
  133. return table.Retry(ctx, store.DB.Table().Pool(),
  134. table.OperationFunc(func(ctx context.Context, s *table.Session) (err error) {
  135. stmt, err := s.Prepare(ctx, store.withPragma(store.getPrefix(dir), deleteFolderChildrenQuery))
  136. if err != nil {
  137. return err
  138. }
  139. _, _, err = stmt.Execute(ctx, rwTX, table.NewQueryParameters(
  140. table.ValueParam("$dir_hash", ydb.Int64Value(util.HashStringToLong(dir))),
  141. table.ValueParam("$directory", ydb.UTF8Value(dir))))
  142. return err
  143. }),
  144. )
  145. }
  146. func (store *YdbStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  147. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", nil)
  148. }
  149. func (store *YdbStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  150. dir := string(dirPath)
  151. var res *table.Result
  152. startFileCompOp := ">"
  153. if includeStartFile {
  154. startFileCompOp = ">="
  155. }
  156. err = table.Retry(ctx, store.DB.Table().Pool(),
  157. table.OperationFunc(func(ctx context.Context, s *table.Session) (err error) {
  158. stmt, err := s.Prepare(ctx, store.withPragma(store.getPrefix(dir), fmt.Sprintf(ListDirectoryQuery, startFileCompOp)))
  159. if err != nil {
  160. return err
  161. }
  162. _, res, err = stmt.Execute(ctx, roTX, table.NewQueryParameters(
  163. table.ValueParam("$dir_hash", ydb.Int64Value(util.HashStringToLong(dir))),
  164. table.ValueParam("$directory", ydb.UTF8Value(dir)),
  165. table.ValueParam("$start_name", ydb.UTF8Value(startFileName)),
  166. table.ValueParam("$prefix", ydb.UTF8Value(prefix)),
  167. table.ValueParam("$limit", ydb.Int64Value(limit)),
  168. ))
  169. return err
  170. }),
  171. )
  172. if err != nil {
  173. return lastFileName, err
  174. }
  175. defer res.Close()
  176. for res.NextSet() {
  177. for res.NextRow() {
  178. res.SeekItem("name")
  179. name := res.UTF8()
  180. res.SeekItem("meta")
  181. data := res.String()
  182. if res.Err() != nil {
  183. glog.V(0).Infof("scan %s : %v", dirPath, err)
  184. return lastFileName, fmt.Errorf("scan %s: %v", dirPath, err)
  185. }
  186. lastFileName = name
  187. entry := &filer.Entry{
  188. FullPath: util.NewFullPath(dir, name),
  189. }
  190. if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  191. glog.V(0).Infof("scan decode %s : %v", entry.FullPath, err)
  192. return lastFileName, fmt.Errorf("scan decode %s : %v", entry.FullPath, err)
  193. }
  194. if !eachEntryFunc(entry) {
  195. break
  196. }
  197. }
  198. }
  199. return lastFileName, nil
  200. }
  201. func (store *YdbStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  202. session, err := store.DB.Table().Pool().Create(ctx)
  203. if err != nil {
  204. return ctx, err
  205. }
  206. tx, err := session.BeginTransaction(ctx, table.TxSettings(table.WithSerializableReadWrite()))
  207. if err != nil {
  208. return ctx, err
  209. }
  210. return context.WithValue(ctx, "tx", tx), nil
  211. }
  212. func (store *YdbStore) CommitTransaction(ctx context.Context) error {
  213. if tx, ok := ctx.Value("tx").(*table.Transaction); ok {
  214. return tx.Commit(ctx)
  215. }
  216. return nil
  217. }
  218. func (store *YdbStore) RollbackTransaction(ctx context.Context) error {
  219. if tx, ok := ctx.Value("tx").(*table.Transaction); ok {
  220. return tx.Rollback(ctx)
  221. }
  222. return nil
  223. }
  224. func (store *YdbStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) {
  225. //TODO implement me
  226. panic("implement me")
  227. }
  228. func (store *YdbStore) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
  229. //TODO implement me
  230. panic("implement me")
  231. }
  232. func (store *YdbStore) KvDelete(ctx context.Context, key []byte) (err error) {
  233. //TODO implement me
  234. panic("implement me")
  235. }
  236. func (store *YdbStore) Shutdown() {
  237. store.DB.Close()
  238. }
  239. func (store *YdbStore) getPrefix(dir string) string {
  240. prefixBuckets := store.dirBuckets + "/"
  241. if strings.HasPrefix(dir, prefixBuckets) {
  242. // detect bucket
  243. bucketAndDir := dir[len(prefixBuckets):]
  244. if t := strings.Index(bucketAndDir, "/"); t > 0 {
  245. return bucketAndDir[:t]
  246. }
  247. }
  248. return ""
  249. }
  250. func (store *YdbStore) withPragma(prefix, query string) string {
  251. return `PRAGMA TablePathPrefix("` + path.Join(store.tablePathPrefix, prefix) + `");` + query
  252. }