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.

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