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.

393 lines
8.9 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
  1. package tikv
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha1"
  6. "fmt"
  7. "io"
  8. "strings"
  9. "github.com/chrislusf/seaweedfs/weed/filer"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  12. "github.com/chrislusf/seaweedfs/weed/util"
  13. "github.com/tikv/client-go/v2/txnkv"
  14. )
  15. var (
  16. _ filer.FilerStore = ((*TikvStore)(nil))
  17. )
  18. func init() {
  19. filer.Stores = append(filer.Stores, &TikvStore{})
  20. }
  21. type TikvStore struct {
  22. client *txnkv.Client
  23. deleteRangeConcurrency int
  24. onePC bool
  25. }
  26. // Basic APIs
  27. func (store *TikvStore) GetName() string {
  28. return "tikv"
  29. }
  30. func (store *TikvStore) Initialize(config util.Configuration, prefix string) error {
  31. pdAddrs := []string{}
  32. pdAddrsStr := config.GetString(prefix + "pdaddrs")
  33. for _, item := range strings.Split(pdAddrsStr, ",") {
  34. pdAddrs = append(pdAddrs, strings.TrimSpace(item))
  35. }
  36. drc := config.GetInt(prefix + "deleterange_concurrency")
  37. if drc <= 0 {
  38. drc = 1
  39. }
  40. store.onePC = config.GetBool(prefix + "enable_1pc")
  41. store.deleteRangeConcurrency = drc
  42. return store.initialize(pdAddrs)
  43. }
  44. func (store *TikvStore) initialize(pdAddrs []string) error {
  45. client, err := txnkv.NewClient(pdAddrs)
  46. store.client = client
  47. return err
  48. }
  49. func (store *TikvStore) Shutdown() {
  50. err := store.client.Close()
  51. if err != nil {
  52. glog.V(0).Infof("Shutdown TiKV client got error: %v", err)
  53. }
  54. }
  55. // ~ Basic APIs
  56. // Entry APIs
  57. func (store *TikvStore) InsertEntry(ctx context.Context, entry *filer.Entry) error {
  58. dir, name := entry.DirAndName()
  59. key := generateKey(dir, name)
  60. value, err := entry.EncodeAttributesAndChunks()
  61. if err != nil {
  62. return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
  63. }
  64. txn, err := store.getTxn(ctx)
  65. if err != nil {
  66. return err
  67. }
  68. err = txn.RunInTxn(func(txn *txnkv.KVTxn) error {
  69. return txn.Set(key, value)
  70. })
  71. if err != nil {
  72. return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
  73. }
  74. return nil
  75. }
  76. func (store *TikvStore) UpdateEntry(ctx context.Context, entry *filer.Entry) error {
  77. return store.InsertEntry(ctx, entry)
  78. }
  79. func (store *TikvStore) FindEntry(ctx context.Context, path util.FullPath) (*filer.Entry, error) {
  80. dir, name := path.DirAndName()
  81. key := generateKey(dir, name)
  82. txn, err := store.getTxn(ctx)
  83. if err != nil {
  84. return nil, err
  85. }
  86. var value []byte = nil
  87. err = txn.RunInTxn(func(txn *txnkv.KVTxn) error {
  88. val, err := txn.Get(context.TODO(), key)
  89. if err == nil {
  90. value = val
  91. }
  92. return err
  93. })
  94. if isNotExists(err) || value == nil {
  95. return nil, filer_pb.ErrNotFound
  96. }
  97. if err != nil {
  98. return nil, fmt.Errorf("get %s : %v", path, err)
  99. }
  100. entry := &filer.Entry{
  101. FullPath: path,
  102. }
  103. err = entry.DecodeAttributesAndChunks(value)
  104. if err != nil {
  105. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  106. }
  107. return entry, nil
  108. }
  109. func (store *TikvStore) DeleteEntry(ctx context.Context, path util.FullPath) error {
  110. dir, name := path.DirAndName()
  111. key := generateKey(dir, name)
  112. txn, err := store.getTxn(ctx)
  113. if err != nil {
  114. return err
  115. }
  116. err = txn.RunInTxn(func(txn *txnkv.KVTxn) error {
  117. return txn.Delete(key)
  118. })
  119. if err != nil {
  120. return fmt.Errorf("delete %s : %v", path, err)
  121. }
  122. return nil
  123. }
  124. // ~ Entry APIs
  125. // Directory APIs
  126. func (store *TikvStore) DeleteFolderChildren(ctx context.Context, path util.FullPath) error {
  127. directoryPrefix := genDirectoryKeyPrefix(path, "")
  128. txn, err := store.getTxn(ctx)
  129. if err != nil {
  130. return err
  131. }
  132. var (
  133. startKey []byte = nil
  134. endKey []byte = nil
  135. )
  136. err = txn.RunInTxn(func(txn *txnkv.KVTxn) error {
  137. iter, err := txn.Iter(directoryPrefix, nil)
  138. if err != nil {
  139. return err
  140. }
  141. defer iter.Close()
  142. for iter.Valid() {
  143. key := iter.Key()
  144. endKey = key
  145. if !bytes.HasPrefix(key, directoryPrefix) {
  146. break
  147. }
  148. if startKey == nil {
  149. startKey = key
  150. }
  151. err = iter.Next()
  152. if err != nil {
  153. return err
  154. }
  155. }
  156. // Only one Key matched just delete it.
  157. if startKey != nil && bytes.Equal(startKey, endKey) {
  158. return txn.Delete(startKey)
  159. }
  160. return nil
  161. })
  162. if err != nil {
  163. return fmt.Errorf("delete %s : %v", path, err)
  164. }
  165. if startKey != nil && endKey != nil && !bytes.Equal(startKey, endKey) {
  166. // has startKey and endKey and they are not equals, so use delete range
  167. _, err = store.client.DeleteRange(context.Background(), startKey, endKey, store.deleteRangeConcurrency)
  168. if err != nil {
  169. return fmt.Errorf("delete %s : %v", path, err)
  170. }
  171. }
  172. return err
  173. }
  174. func (store *TikvStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (string, error) {
  175. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", eachEntryFunc)
  176. }
  177. func (store *TikvStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (string, error) {
  178. lastFileName := ""
  179. directoryPrefix := genDirectoryKeyPrefix(dirPath, prefix)
  180. lastFileStart := directoryPrefix
  181. if startFileName != "" {
  182. lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
  183. }
  184. txn, err := store.getTxn(ctx)
  185. if err != nil {
  186. return lastFileName, err
  187. }
  188. err = txn.RunInTxn(func(txn *txnkv.KVTxn) error {
  189. iter, err := txn.Iter(lastFileStart, nil)
  190. if err != nil {
  191. return err
  192. }
  193. defer iter.Close()
  194. i := int64(0)
  195. first := true
  196. for iter.Valid() {
  197. if first {
  198. first = false
  199. if !includeStartFile {
  200. if iter.Valid() {
  201. // Check first item is lastFileStart
  202. if bytes.Equal(iter.Key(), lastFileStart) {
  203. // Is lastFileStart and not include start file, just
  204. // ignore it.
  205. err = iter.Next()
  206. if err != nil {
  207. return err
  208. }
  209. continue
  210. }
  211. }
  212. }
  213. }
  214. // Check for limitation
  215. if limit > 0 {
  216. i++
  217. if i > limit {
  218. break
  219. }
  220. }
  221. // Validate key prefix
  222. key := iter.Key()
  223. if !bytes.HasPrefix(key, directoryPrefix) {
  224. break
  225. }
  226. value := iter.Value()
  227. // Start process
  228. fileName := getNameFromKey(key)
  229. if fileName != "" {
  230. // Got file name, then generate the Entry
  231. entry := &filer.Entry{
  232. FullPath: util.NewFullPath(string(dirPath), fileName),
  233. }
  234. // Update lastFileName
  235. lastFileName = fileName
  236. // Check for decode value.
  237. if decodeErr := entry.DecodeAttributesAndChunks(value); decodeErr != nil {
  238. // Got error just return the error
  239. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  240. return err
  241. }
  242. // Run for each callback if return false just break the iteration
  243. if !eachEntryFunc(entry) {
  244. break
  245. }
  246. }
  247. // End process
  248. err = iter.Next()
  249. if err != nil {
  250. return err
  251. }
  252. }
  253. return nil
  254. })
  255. if err != nil {
  256. return lastFileName, fmt.Errorf("prefix list %s : %v", dirPath, err)
  257. }
  258. return lastFileName, nil
  259. }
  260. // ~ Directory APIs
  261. // Transaction Related APIs
  262. func (store *TikvStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  263. tx, err := store.client.Begin()
  264. if err != nil {
  265. return ctx, err
  266. }
  267. if store.onePC {
  268. tx.SetEnable1PC(store.onePC)
  269. }
  270. return context.WithValue(ctx, "tx", tx), nil
  271. }
  272. func (store *TikvStore) CommitTransaction(ctx context.Context) error {
  273. if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok {
  274. return tx.Commit(context.Background())
  275. }
  276. return nil
  277. }
  278. func (store *TikvStore) RollbackTransaction(ctx context.Context) error {
  279. if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok {
  280. return tx.Rollback()
  281. }
  282. return nil
  283. }
  284. // ~ Transaction Related APIs
  285. // Transaction Wrapper
  286. type TxnWrapper struct {
  287. *txnkv.KVTxn
  288. inContext bool
  289. }
  290. func (w *TxnWrapper) RunInTxn(f func(txn *txnkv.KVTxn) error) error {
  291. err := f(w.KVTxn)
  292. if !w.inContext {
  293. if err != nil {
  294. w.KVTxn.Rollback()
  295. return err
  296. }
  297. w.KVTxn.Commit(context.Background())
  298. return nil
  299. }
  300. return err
  301. }
  302. func (store *TikvStore) getTxn(ctx context.Context) (*TxnWrapper, error) {
  303. if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok {
  304. return &TxnWrapper{tx, true}, nil
  305. }
  306. txn, err := store.client.Begin()
  307. if err != nil {
  308. return nil, err
  309. }
  310. if store.onePC {
  311. txn.SetEnable1PC(store.onePC)
  312. }
  313. return &TxnWrapper{txn, false}, nil
  314. }
  315. // ~ Transaction Wrapper
  316. // Encoding Functions
  317. func hashToBytes(dir string) []byte {
  318. h := sha1.New()
  319. io.WriteString(h, dir)
  320. b := h.Sum(nil)
  321. return b
  322. }
  323. func generateKey(dirPath, fileName string) []byte {
  324. key := hashToBytes(dirPath)
  325. key = append(key, []byte(fileName)...)
  326. return key
  327. }
  328. func getNameFromKey(key []byte) string {
  329. return string(key[sha1.Size:])
  330. }
  331. func genDirectoryKeyPrefix(fullpath util.FullPath, startFileName string) (keyPrefix []byte) {
  332. keyPrefix = hashToBytes(string(fullpath))
  333. if len(startFileName) > 0 {
  334. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  335. }
  336. return keyPrefix
  337. }
  338. func isNotExists(err error) bool {
  339. if err == nil {
  340. return false
  341. }
  342. if err.Error() == "not exist" {
  343. return true
  344. }
  345. return false
  346. }
  347. // ~ Encoding Functions