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.

388 lines
8.7 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
  1. // +build tikv
  2. package tikv
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/sha1"
  7. "fmt"
  8. "io"
  9. "strings"
  10. "github.com/chrislusf/seaweedfs/weed/filer"
  11. "github.com/chrislusf/seaweedfs/weed/glog"
  12. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  13. "github.com/chrislusf/seaweedfs/weed/util"
  14. "github.com/tikv/client-go/v2/tikv"
  15. "github.com/tikv/client-go/v2/txnkv"
  16. )
  17. var (
  18. _ filer.FilerStore = ((*TikvStore)(nil))
  19. )
  20. func init() {
  21. filer.Stores = append(filer.Stores, &TikvStore{})
  22. }
  23. type TikvStore struct {
  24. client *tikv.KVStore
  25. deleteRangeConcurrency int
  26. }
  27. // Basic APIs
  28. func (store *TikvStore) GetName() string {
  29. return "tikv"
  30. }
  31. func (store *TikvStore) Initialize(config util.Configuration, prefix string) error {
  32. pdAddrs := []string{}
  33. pdAddrsStr := config.GetString(prefix + "pdaddrs")
  34. for _, item := range strings.Split(pdAddrsStr, ",") {
  35. pdAddrs = append(pdAddrs, strings.TrimSpace(item))
  36. }
  37. drc := config.GetInt(prefix + "deleterange_concurrency")
  38. if drc <= 0 {
  39. drc = 1
  40. }
  41. store.deleteRangeConcurrency = drc
  42. return store.initialize(pdAddrs)
  43. }
  44. func (store *TikvStore) initialize(pdAddrs []string) error {
  45. client, err := tikv.NewTxnClient(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. return context.WithValue(ctx, "tx", tx), nil
  268. }
  269. func (store *TikvStore) CommitTransaction(ctx context.Context) error {
  270. if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok {
  271. return tx.Commit(context.Background())
  272. }
  273. return nil
  274. }
  275. func (store *TikvStore) RollbackTransaction(ctx context.Context) error {
  276. if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok {
  277. return tx.Rollback()
  278. }
  279. return nil
  280. }
  281. // ~ Transaction Related APIs
  282. // Transaction Wrapper
  283. type TxnWrapper struct {
  284. *txnkv.KVTxn
  285. inContext bool
  286. }
  287. func (w *TxnWrapper) RunInTxn(f func(txn *txnkv.KVTxn) error) error {
  288. err := f(w.KVTxn)
  289. if !w.inContext {
  290. if err != nil {
  291. w.KVTxn.Rollback()
  292. return err
  293. }
  294. w.KVTxn.Commit(context.Background())
  295. return nil
  296. }
  297. return err
  298. }
  299. func (store *TikvStore) getTxn(ctx context.Context) (*TxnWrapper, error) {
  300. if tx, ok := ctx.Value("tx").(*txnkv.KVTxn); ok {
  301. return &TxnWrapper{tx, true}, nil
  302. }
  303. txn, err := store.client.Begin()
  304. if err != nil {
  305. return nil, err
  306. }
  307. return &TxnWrapper{txn, false}, nil
  308. }
  309. // ~ Transaction Wrapper
  310. // Encoding Functions
  311. func hashToBytes(dir string) []byte {
  312. h := sha1.New()
  313. io.WriteString(h, dir)
  314. b := h.Sum(nil)
  315. return b
  316. }
  317. func generateKey(dirPath, fileName string) []byte {
  318. key := hashToBytes(dirPath)
  319. key = append(key, []byte(fileName)...)
  320. return key
  321. }
  322. func getNameFromKey(key []byte) string {
  323. return string(key[sha1.Size:])
  324. }
  325. func genDirectoryKeyPrefix(fullpath util.FullPath, startFileName string) (keyPrefix []byte) {
  326. keyPrefix = hashToBytes(string(fullpath))
  327. if len(startFileName) > 0 {
  328. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  329. }
  330. return keyPrefix
  331. }
  332. func isNotExists(err error) bool {
  333. if err == nil {
  334. return false
  335. }
  336. if err.Error() == "not exist" {
  337. return true
  338. }
  339. return false
  340. }
  341. // ~ Encoding Functions