util.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package wal
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. )
  7. func Exist(dirpath string) bool {
  8. names, err := readDir(dirpath)
  9. if err != nil {
  10. return false
  11. }
  12. return len(names) != 0
  13. }
  14. // searchIndex returns the last array index of names whose raft index section is
  15. // equal to or smaller than the given index.
  16. // The given names MUST be sorted.
  17. func searchIndex(names []string, index uint64) (int, bool) {
  18. for i := len(names) - 1; i >= 0; i-- {
  19. name := names[i]
  20. _, curIndex, err := parseWalName(name)
  21. if err != nil {
  22. panic("parse correct name error")
  23. }
  24. if index >= curIndex {
  25. return i, true
  26. }
  27. }
  28. return -1, false
  29. }
  30. // names should have been sorted based on sequence number.
  31. // isValidSeq checks whether seq increases continuously.
  32. func isValidSeq(names []string) bool {
  33. var lastSeq uint64
  34. for _, name := range names {
  35. curSeq, _, err := parseWalName(name)
  36. if err != nil {
  37. panic("parse correct name error")
  38. }
  39. if lastSeq != 0 && lastSeq != curSeq-1 {
  40. return false
  41. }
  42. lastSeq = curSeq
  43. }
  44. return true
  45. }
  46. // readDir returns the filenames in wal directory.
  47. func readDir(dirpath string) ([]string, error) {
  48. dir, err := os.Open(dirpath)
  49. if err != nil {
  50. return nil, err
  51. }
  52. defer dir.Close()
  53. names, err := dir.Readdirnames(-1)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return names, nil
  58. }
  59. func checkWalNames(names []string) []string {
  60. wnames := make([]string, 0)
  61. for _, name := range names {
  62. if _, _, err := parseWalName(name); err != nil {
  63. log.Printf("parse %s: %v", name, err)
  64. continue
  65. }
  66. wnames = append(wnames, name)
  67. }
  68. return wnames
  69. }
  70. func parseWalName(str string) (seq, index uint64, err error) {
  71. var num int
  72. num, err = fmt.Sscanf(str, "%016x-%016x.wal", &seq, &index)
  73. if num != 2 && err == nil {
  74. err = fmt.Errorf("bad wal name: %s", str)
  75. }
  76. return
  77. }
  78. func walName(seq, index uint64) string {
  79. return fmt.Sprintf("%016x-%016x.wal", seq, index)
  80. }
  81. func max(a, b int64) int64 {
  82. if a > b {
  83. return a
  84. }
  85. return b
  86. }