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.

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