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.

379 lines
12 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package ydb
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "github.com/chrislusf/seaweedfs/weed/filer/abstract_sql"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. "github.com/chrislusf/seaweedfs/weed/util"
  10. environ "github.com/ydb-platform/ydb-go-sdk-auth-environ"
  11. "github.com/ydb-platform/ydb-go-sdk/v3"
  12. "github.com/ydb-platform/ydb-go-sdk/v3/sugar"
  13. "github.com/ydb-platform/ydb-go-sdk/v3/table"
  14. "github.com/ydb-platform/ydb-go-sdk/v3/table/result"
  15. "github.com/ydb-platform/ydb-go-sdk/v3/table/result/named"
  16. "github.com/ydb-platform/ydb-go-sdk/v3/table/types"
  17. "os"
  18. "path"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. const (
  24. defaultConnectionTimeOut = 10
  25. )
  26. var (
  27. roTX = table.TxControl(
  28. table.BeginTx(table.WithOnlineReadOnly()),
  29. table.CommitTx(),
  30. )
  31. rwTX = table.DefaultTxControl()
  32. )
  33. type YdbStore struct {
  34. DB ydb.Connection
  35. dirBuckets string
  36. tablePathPrefix string
  37. SupportBucketTable bool
  38. dbs map[string]bool
  39. dbsLock sync.Mutex
  40. }
  41. func init() {
  42. filer.Stores = append(filer.Stores, &YdbStore{})
  43. }
  44. func (store *YdbStore) GetName() string {
  45. return "ydb"
  46. }
  47. func (store *YdbStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  48. return store.initialize(
  49. configuration.GetString("filer.options.buckets_folder"),
  50. configuration.GetString(prefix+"dsn"),
  51. configuration.GetString(prefix+"prefix"),
  52. configuration.GetBool(prefix+"useBucketPrefix"),
  53. configuration.GetInt(prefix+"connectionTimeOut"),
  54. configuration.GetInt(prefix+"poolSizeLimit"),
  55. )
  56. }
  57. func (store *YdbStore) initialize(dirBuckets string, dsn string, tablePathPrefix string, useBucketPrefix bool, connectionTimeOut int, poolSizeLimit int) (err error) {
  58. store.dirBuckets = dirBuckets
  59. store.SupportBucketTable = useBucketPrefix
  60. store.dbs = make(map[string]bool)
  61. ctx, cancel := context.WithCancel(context.Background())
  62. defer cancel()
  63. if connectionTimeOut == 0 {
  64. connectionTimeOut = defaultConnectionTimeOut
  65. }
  66. opts := []ydb.Option{
  67. ydb.WithDialTimeout(time.Duration(connectionTimeOut) * time.Second),
  68. environ.WithEnvironCredentials(ctx),
  69. }
  70. if poolSizeLimit > 0 {
  71. opts = append(opts, ydb.WithSessionPoolSizeLimit(poolSizeLimit))
  72. }
  73. if dsn == "" {
  74. dsn = os.Getenv("YDB_CONNECTION_STRING")
  75. }
  76. store.DB, err = ydb.Open(ctx, dsn, opts...)
  77. if err != nil || store.DB == nil {
  78. if store.DB != nil {
  79. _ = store.DB.Close(ctx)
  80. store.DB = nil
  81. }
  82. return fmt.Errorf("can not connect to %s error: %v", dsn, err)
  83. }
  84. store.tablePathPrefix = path.Join(store.DB.Name(), tablePathPrefix)
  85. if err = sugar.MakeRecursive(ctx, store.DB, store.tablePathPrefix); err != nil {
  86. return fmt.Errorf("MakeRecursive %s : %v", store.tablePathPrefix, err)
  87. }
  88. if err = store.createTable(ctx, store.tablePathPrefix); err != nil {
  89. glog.Errorf("createTable %s: %v", store.tablePathPrefix, err)
  90. }
  91. return err
  92. }
  93. func (store *YdbStore) doTxOrDB(ctx context.Context, query *string, params *table.QueryParameters, tc *table.TransactionControl, processResultFunc func(res result.Result) error) (err error) {
  94. var res result.Result
  95. if tx, ok := ctx.Value("tx").(table.Transaction); ok {
  96. res, err = tx.Execute(ctx, *query, params)
  97. if err != nil {
  98. return fmt.Errorf("execute transaction: %v", err)
  99. }
  100. } else {
  101. err = store.DB.Table().Do(ctx, func(ctx context.Context, s table.Session) (err error) {
  102. stmt, err := s.Prepare(ctx, *query)
  103. if err != nil {
  104. return fmt.Errorf("prepare: %v", err)
  105. }
  106. _, res, err = stmt.Execute(ctx, tc, params)
  107. if err != nil {
  108. return fmt.Errorf("execute statement: %v", err)
  109. }
  110. return nil
  111. })
  112. }
  113. if err != nil {
  114. return err
  115. }
  116. if res != nil {
  117. defer func() { _ = res.Close() }()
  118. if processResultFunc != nil {
  119. if err = processResultFunc(res); err != nil {
  120. return fmt.Errorf("process result: %v", err)
  121. }
  122. }
  123. }
  124. return err
  125. }
  126. func (store *YdbStore) insertOrUpdateEntry(ctx context.Context, entry *filer.Entry, query string) (err error) {
  127. dir, name := entry.FullPath.DirAndName()
  128. meta, err := entry.EncodeAttributesAndChunks()
  129. if err != nil {
  130. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  131. }
  132. if len(entry.Chunks) > filer.CountEntryChunksForGzip {
  133. meta = util.MaybeGzipData(meta)
  134. }
  135. queryWithPragma := withPragma(store.getPrefix(ctx, dir), query)
  136. fileMeta := FileMeta{util.HashStringToLong(dir), name, dir, meta}
  137. return store.doTxOrDB(ctx, &queryWithPragma, fileMeta.queryParameters(), rwTX, nil)
  138. }
  139. func (store *YdbStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  140. return store.insertOrUpdateEntry(ctx, entry, insertQuery)
  141. }
  142. func (store *YdbStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  143. return store.insertOrUpdateEntry(ctx, entry, updateQuery)
  144. }
  145. func (store *YdbStore) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
  146. dir, name := fullpath.DirAndName()
  147. var data []byte
  148. entryFound := false
  149. queryWithPragma := withPragma(store.getPrefix(ctx, dir), findQuery)
  150. queryParams := table.NewQueryParameters(
  151. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  152. table.ValueParam("$name", types.UTF8Value(name)))
  153. err = store.doTxOrDB(ctx, &queryWithPragma, queryParams, roTX, func(res result.Result) error {
  154. for res.NextResultSet(ctx) {
  155. for res.NextRow() {
  156. if err = res.ScanNamed(named.OptionalWithDefault("meta", &data)); err != nil {
  157. return fmt.Errorf("scanNamed %s : %v", fullpath, err)
  158. }
  159. entryFound = true
  160. return nil
  161. }
  162. }
  163. return res.Err()
  164. })
  165. if err != nil {
  166. return nil, err
  167. }
  168. if !entryFound {
  169. return nil, filer_pb.ErrNotFound
  170. }
  171. entry = &filer.Entry{
  172. FullPath: fullpath,
  173. }
  174. if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  175. return nil, fmt.Errorf("decode %s : %v", fullpath, err)
  176. }
  177. return entry, nil
  178. }
  179. func (store *YdbStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) (err error) {
  180. dir, name := fullpath.DirAndName()
  181. queryWithPragma := withPragma(store.getPrefix(ctx, dir), deleteQuery)
  182. queryParams := table.NewQueryParameters(
  183. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  184. table.ValueParam("$name", types.UTF8Value(name)))
  185. return store.doTxOrDB(ctx, &queryWithPragma, queryParams, rwTX, nil)
  186. }
  187. func (store *YdbStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) (err error) {
  188. dir, _ := fullpath.DirAndName()
  189. queryWithPragma := withPragma(store.getPrefix(ctx, dir), deleteFolderChildrenQuery)
  190. queryParams := table.NewQueryParameters(
  191. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  192. table.ValueParam("$directory", types.UTF8Value(dir)))
  193. return store.doTxOrDB(ctx, &queryWithPragma, queryParams, rwTX, nil)
  194. }
  195. func (store *YdbStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  196. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", nil)
  197. }
  198. 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) {
  199. dir := string(dirPath)
  200. startFileCompOp := ">"
  201. if includeStartFile {
  202. startFileCompOp = ">="
  203. }
  204. queryWithPragma := withPragma(store.getPrefix(ctx, dir), fmt.Sprintf(listDirectoryQuery, startFileCompOp))
  205. queryParams := table.NewQueryParameters(
  206. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  207. table.ValueParam("$directory", types.UTF8Value(dir)),
  208. table.ValueParam("$start_name", types.UTF8Value(startFileName)),
  209. table.ValueParam("$prefix", types.UTF8Value(prefix+"%")),
  210. table.ValueParam("$limit", types.Uint64Value(uint64(limit))),
  211. )
  212. err = store.doTxOrDB(ctx, &queryWithPragma, queryParams, roTX, func(res result.Result) error {
  213. var name string
  214. var data []byte
  215. for res.NextResultSet(ctx) {
  216. for res.NextRow() {
  217. if err := res.ScanNamed(
  218. named.OptionalWithDefault("name", &name),
  219. named.OptionalWithDefault("meta", &data)); err != nil {
  220. return fmt.Errorf("list scanNamed %s : %v", dir, err)
  221. }
  222. lastFileName = name
  223. entry := &filer.Entry{
  224. FullPath: util.NewFullPath(dir, name),
  225. }
  226. if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  227. return fmt.Errorf("scan decode %s : %v", entry.FullPath, err)
  228. }
  229. if !eachEntryFunc(entry) {
  230. break
  231. }
  232. }
  233. }
  234. return res.Err()
  235. })
  236. if err != nil {
  237. return lastFileName, err
  238. }
  239. return lastFileName, nil
  240. }
  241. func (store *YdbStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  242. session, err := store.DB.Table().CreateSession(ctx)
  243. if err != nil {
  244. return ctx, err
  245. }
  246. tx, err := session.BeginTransaction(ctx, table.TxSettings(table.WithSerializableReadWrite()))
  247. if err != nil {
  248. return ctx, err
  249. }
  250. return context.WithValue(ctx, "tx", tx), nil
  251. }
  252. func (store *YdbStore) CommitTransaction(ctx context.Context) error {
  253. if tx, ok := ctx.Value("tx").(table.Transaction); ok {
  254. _, err := tx.CommitTx(ctx)
  255. return err
  256. }
  257. return nil
  258. }
  259. func (store *YdbStore) RollbackTransaction(ctx context.Context) error {
  260. if tx, ok := ctx.Value("tx").(table.Transaction); ok {
  261. return tx.Rollback(ctx)
  262. }
  263. return nil
  264. }
  265. func (store *YdbStore) Shutdown() {
  266. _ = store.DB.Close(context.Background())
  267. }
  268. func (store *YdbStore) CanDropWholeBucket() bool {
  269. return store.SupportBucketTable
  270. }
  271. func (store *YdbStore) OnBucketCreation(bucket string) {
  272. store.dbsLock.Lock()
  273. defer store.dbsLock.Unlock()
  274. if err := store.createTable(context.Background(),
  275. path.Join(store.tablePathPrefix, bucket)); err != nil {
  276. glog.Errorf("createTable %s: %v", bucket, err)
  277. }
  278. if store.dbs == nil {
  279. return
  280. }
  281. store.dbs[bucket] = true
  282. }
  283. func (store *YdbStore) OnBucketDeletion(bucket string) {
  284. store.dbsLock.Lock()
  285. defer store.dbsLock.Unlock()
  286. if err := store.deleteTable(context.Background(),
  287. path.Join(store.tablePathPrefix, bucket)); err != nil {
  288. glog.Errorf("deleteTable %s: %v", bucket, err)
  289. }
  290. if store.dbs == nil {
  291. return
  292. }
  293. delete(store.dbs, bucket)
  294. }
  295. func (store *YdbStore) createTable(ctx context.Context, prefix string) error {
  296. return store.DB.Table().Do(ctx, func(ctx context.Context, s table.Session) error {
  297. return s.CreateTable(ctx, path.Join(prefix, abstract_sql.DEFAULT_TABLE), createTableOptions()...)
  298. })
  299. }
  300. func (store *YdbStore) deleteTable(ctx context.Context, prefix string) error {
  301. if !store.SupportBucketTable {
  302. return nil
  303. }
  304. return store.DB.Table().Do(ctx, func(ctx context.Context, s table.Session) error {
  305. return s.DropTable(ctx, path.Join(prefix, abstract_sql.DEFAULT_TABLE))
  306. })
  307. }
  308. func (store *YdbStore) getPrefix(ctx context.Context, dir string) (tablePathPrefix string) {
  309. tablePathPrefix = store.tablePathPrefix
  310. if !store.SupportBucketTable {
  311. return
  312. }
  313. prefixBuckets := store.dirBuckets + "/"
  314. if strings.HasPrefix(dir, prefixBuckets) {
  315. // detect bucket
  316. bucketAndDir := dir[len(prefixBuckets):]
  317. t := strings.Index(bucketAndDir, "/")
  318. if t < 0 {
  319. return
  320. }
  321. bucket := bucketAndDir[:t]
  322. if bucket != "" {
  323. return
  324. }
  325. store.dbsLock.Lock()
  326. defer store.dbsLock.Unlock()
  327. tablePathPrefix = path.Join(store.tablePathPrefix, bucket)
  328. if _, found := store.dbs[bucket]; !found {
  329. if err := store.createTable(ctx, tablePathPrefix); err == nil {
  330. store.dbs[bucket] = true
  331. } else {
  332. glog.Errorf("createTable %s: %v", tablePathPrefix, err)
  333. }
  334. }
  335. }
  336. return
  337. }