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.

380 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
  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+"tablePathPrefix"),
  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.tablePathPrefix = tablePathPrefix
  60. store.SupportBucketTable = useBucketPrefix
  61. store.dbs = make(map[string]bool)
  62. ctx, cancel := context.WithCancel(context.Background())
  63. defer cancel()
  64. if connectionTimeOut == 0 {
  65. connectionTimeOut = defaultConnectionTimeOut
  66. }
  67. opts := []ydb.Option{
  68. ydb.WithDialTimeout(time.Duration(connectionTimeOut) * time.Second),
  69. environ.WithEnvironCredentials(ctx),
  70. }
  71. if poolSizeLimit > 0 {
  72. opts = append(opts, ydb.WithSessionPoolSizeLimit(poolSizeLimit))
  73. }
  74. if dsn == "" {
  75. dsn = os.Getenv("YDB_CONNECTION_STRING")
  76. }
  77. store.DB, err = ydb.Open(ctx, dsn, opts...)
  78. if err != nil {
  79. if store.DB != nil {
  80. _ = store.DB.Close(ctx)
  81. store.DB = nil
  82. }
  83. return fmt.Errorf("can not connect to %s error: %v", dsn, err)
  84. }
  85. store.tablePathPrefix = path.Join(store.DB.Name(), tablePathPrefix)
  86. if err = sugar.RemoveRecursive(ctx, store.DB, store.tablePathPrefix); err != nil {
  87. return fmt.Errorf("RemoveRecursive %s : %v", store.tablePathPrefix, err)
  88. }
  89. if err = sugar.MakeRecursive(ctx, store.DB, store.tablePathPrefix); err != nil {
  90. return fmt.Errorf("MakeRecursive %s : %v", store.tablePathPrefix, err)
  91. }
  92. tablePath := path.Join(store.tablePathPrefix, abstract_sql.DEFAULT_TABLE)
  93. if err = store.createTable(ctx, tablePath); err != nil {
  94. glog.Errorf("createTable %s: %v", tablePath, err)
  95. }
  96. return err
  97. }
  98. func (store *YdbStore) doTxOrDB(ctx context.Context, query *string, params *table.QueryParameters, tc *table.TransactionControl, processResultFunc func(res result.Result) error) (err error) {
  99. var res result.Result
  100. if tx, ok := ctx.Value("tx").(table.Transaction); ok {
  101. res, err = tx.Execute(ctx, *query, params)
  102. if err != nil {
  103. return fmt.Errorf("execute transaction: %v", err)
  104. }
  105. } else {
  106. err = store.DB.Table().Do(ctx, func(ctx context.Context, s table.Session) (err error) {
  107. stmt, err := s.Prepare(ctx, *query)
  108. if err != nil {
  109. return fmt.Errorf("prepare: %v", err)
  110. }
  111. _, res, err = stmt.Execute(ctx, tc, params)
  112. if err != nil {
  113. return fmt.Errorf("execute statement: %v", err)
  114. }
  115. return nil
  116. })
  117. }
  118. if err != nil && processResultFunc != nil && res != nil {
  119. if err = processResultFunc(res); err != nil {
  120. return fmt.Errorf("process resul: %v", err)
  121. }
  122. }
  123. return err
  124. }
  125. func (store *YdbStore) insertOrUpdateEntry(ctx context.Context, entry *filer.Entry, query string) (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.Chunks) > filer.CountEntryChunksForGzip {
  132. meta = util.MaybeGzipData(meta)
  133. }
  134. queryWithPragma := withPragma(store.getPrefix(ctx, dir), query)
  135. fileMeta := FileMeta{util.HashStringToLong(dir), name, dir, meta}
  136. return store.doTxOrDB(ctx, &queryWithPragma, fileMeta.queryParameters(), rwTX, nil)
  137. }
  138. func (store *YdbStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  139. return store.insertOrUpdateEntry(ctx, entry, insertQuery)
  140. }
  141. func (store *YdbStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  142. return store.insertOrUpdateEntry(ctx, entry, updateQuery)
  143. }
  144. func (store *YdbStore) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
  145. dir, name := fullpath.DirAndName()
  146. var data []byte
  147. entryFound := false
  148. queryWithPragma := withPragma(store.getPrefix(ctx, dir), findQuery)
  149. queryParams := table.NewQueryParameters(
  150. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  151. table.ValueParam("$name", types.UTF8Value(name)))
  152. err = store.doTxOrDB(ctx, &queryWithPragma, queryParams, roTX, func(res result.Result) error {
  153. defer func() {
  154. _ = res.Close()
  155. }()
  156. for res.NextRow() {
  157. if err := res.ScanNamed(named.Required("meta", &data)); err != nil {
  158. return fmt.Errorf("scanNamed %s : %v", entry.FullPath, err)
  159. }
  160. entryFound = true
  161. return nil
  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.FullPath = fullpath
  172. if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  173. return nil, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  174. }
  175. return entry, nil
  176. }
  177. func (store *YdbStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) (err error) {
  178. dir, name := fullpath.DirAndName()
  179. queryWithPragma := withPragma(store.getPrefix(ctx, dir), deleteQuery)
  180. queryParams := table.NewQueryParameters(
  181. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  182. table.ValueParam("$name", types.UTF8Value(name)))
  183. return store.doTxOrDB(ctx, &queryWithPragma, queryParams, rwTX, nil)
  184. }
  185. func (store *YdbStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) (err error) {
  186. dir, _ := fullpath.DirAndName()
  187. queryWithPragma := withPragma(store.getPrefix(ctx, dir), deleteFolderChildrenQuery)
  188. queryParams := table.NewQueryParameters(
  189. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  190. table.ValueParam("$directory", types.UTF8Value(dir)))
  191. return store.doTxOrDB(ctx, &queryWithPragma, queryParams, rwTX, nil)
  192. }
  193. func (store *YdbStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  194. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", nil)
  195. }
  196. 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) {
  197. dir := string(dirPath)
  198. startFileCompOp := ">"
  199. if includeStartFile {
  200. startFileCompOp = ">="
  201. }
  202. queryWithPragma := withPragma(store.getPrefix(ctx, dir), fmt.Sprintf(listDirectoryQuery, startFileCompOp))
  203. queryParams := table.NewQueryParameters(
  204. table.ValueParam("$dir_hash", types.Int64Value(util.HashStringToLong(dir))),
  205. table.ValueParam("$directory", types.UTF8Value(dir)),
  206. table.ValueParam("$start_name", types.UTF8Value(startFileName)),
  207. table.ValueParam("$prefix", types.UTF8Value(prefix+"%")),
  208. table.ValueParam("$limit", types.Uint64Value(uint64(limit))),
  209. )
  210. err = store.doTxOrDB(ctx, &queryWithPragma, queryParams, roTX, func(res result.Result) error {
  211. defer func() {
  212. _ = res.Close()
  213. }()
  214. for res.NextResultSet(ctx) {
  215. for res.NextRow() {
  216. var name string
  217. var data []byte
  218. if err := res.ScanNamed(
  219. named.Required("name", &name),
  220. named.Required("meta", &data)); err != nil {
  221. return fmt.Errorf("scanNamed %s : %v", dir, err)
  222. }
  223. lastFileName = name
  224. entry := &filer.Entry{
  225. FullPath: util.NewFullPath(dir, name),
  226. }
  227. if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  228. return fmt.Errorf("scan decode %s : %v", entry.FullPath, err)
  229. }
  230. if !eachEntryFunc(entry) {
  231. break
  232. }
  233. }
  234. }
  235. return res.Err()
  236. })
  237. if err != nil {
  238. return lastFileName, err
  239. }
  240. return lastFileName, nil
  241. }
  242. func (store *YdbStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  243. session, err := store.DB.Table().CreateSession(ctx)
  244. if err != nil {
  245. return ctx, err
  246. }
  247. tx, err := session.BeginTransaction(ctx, table.TxSettings(table.WithSerializableReadWrite()))
  248. if err != nil {
  249. return ctx, err
  250. }
  251. return context.WithValue(ctx, "tx", tx), nil
  252. }
  253. func (store *YdbStore) CommitTransaction(ctx context.Context) error {
  254. if tx, ok := ctx.Value("tx").(table.Transaction); ok {
  255. _, err := tx.CommitTx(ctx)
  256. return err
  257. }
  258. return nil
  259. }
  260. func (store *YdbStore) RollbackTransaction(ctx context.Context) error {
  261. if tx, ok := ctx.Value("tx").(table.Transaction); ok {
  262. return tx.Rollback(ctx)
  263. }
  264. return nil
  265. }
  266. func (store *YdbStore) Shutdown() {
  267. _ = store.DB.Close(context.Background())
  268. }
  269. func (store *YdbStore) CanDropWholeBucket() bool {
  270. return store.SupportBucketTable
  271. }
  272. func (store *YdbStore) OnBucketCreation(bucket string) {
  273. store.dbsLock.Lock()
  274. defer store.dbsLock.Unlock()
  275. if err := store.createTable(context.Background(),
  276. path.Join(store.tablePathPrefix, bucket, abstract_sql.DEFAULT_TABLE)); err != nil {
  277. glog.Errorf("createTable %s: %v", bucket, err)
  278. }
  279. if store.dbs == nil {
  280. return
  281. }
  282. store.dbs[bucket] = true
  283. }
  284. func (store *YdbStore) OnBucketDeletion(bucket string) {
  285. store.dbsLock.Lock()
  286. defer store.dbsLock.Unlock()
  287. if err := store.deleteTable(context.Background(),
  288. path.Join(store.tablePathPrefix, bucket, abstract_sql.DEFAULT_TABLE)); err != nil {
  289. glog.Errorf("deleteTable %s: %v", bucket, err)
  290. }
  291. if store.dbs == nil {
  292. return
  293. }
  294. delete(store.dbs, bucket)
  295. }
  296. func (store *YdbStore) createTable(ctx context.Context, prefix string) error {
  297. return store.DB.Table().Do(ctx, func(ctx context.Context, s table.Session) error {
  298. return s.CreateTable(ctx, prefix, createTableOptions()...)
  299. })
  300. }
  301. func (store *YdbStore) deleteTable(ctx context.Context, prefix string) error {
  302. if !store.SupportBucketTable {
  303. return nil
  304. }
  305. return store.DB.Table().Do(ctx, func(ctx context.Context, s table.Session) error {
  306. return s.DropTable(ctx, prefix)
  307. })
  308. }
  309. func (store *YdbStore) getPrefix(ctx context.Context, dir string) (tablePathPrefix string) {
  310. tablePathPrefix = store.tablePathPrefix
  311. if !store.SupportBucketTable {
  312. return
  313. }
  314. prefixBuckets := store.dirBuckets + "/"
  315. if strings.HasPrefix(dir, prefixBuckets) {
  316. // detect bucket
  317. bucketAndDir := dir[len(prefixBuckets):]
  318. t := strings.Index(bucketAndDir, "/")
  319. if t < 0 {
  320. return
  321. }
  322. bucket := bucketAndDir[:t]
  323. if bucket != "" {
  324. return
  325. }
  326. store.dbsLock.Lock()
  327. defer store.dbsLock.Unlock()
  328. if _, found := store.dbs[bucket]; !found {
  329. if err := store.createTable(ctx,
  330. path.Join(store.tablePathPrefix, bucket, abstract_sql.DEFAULT_TABLE)); err == nil {
  331. store.dbs[bucket] = true
  332. } else {
  333. glog.Errorf("createTable %s: %v", bucket, err)
  334. }
  335. }
  336. tablePathPrefix = path.Join(store.tablePathPrefix, bucket)
  337. }
  338. return
  339. }