util.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package wal
  15. import (
  16. "errors"
  17. "fmt"
  18. "log"
  19. "strings"
  20. "github.com/coreos/etcd/pkg/fileutil"
  21. )
  22. var (
  23. badWalName = errors.New("bad wal name")
  24. )
  25. func Exist(dirpath string) bool {
  26. names, err := fileutil.ReadDir(dirpath)
  27. if err != nil {
  28. return false
  29. }
  30. return len(names) != 0
  31. }
  32. // searchIndex returns the last array index of names whose raft index section is
  33. // equal to or smaller than the given index.
  34. // The given names MUST be sorted.
  35. func searchIndex(names []string, index uint64) (int, bool) {
  36. for i := len(names) - 1; i >= 0; i-- {
  37. name := names[i]
  38. _, curIndex, err := parseWalName(name)
  39. if err != nil {
  40. log.Panicf("parse correct name should never fail: %v", err)
  41. }
  42. if index >= curIndex {
  43. return i, true
  44. }
  45. }
  46. return -1, false
  47. }
  48. // names should have been sorted based on sequence number.
  49. // isValidSeq checks whether seq increases continuously.
  50. func isValidSeq(names []string) bool {
  51. var lastSeq uint64
  52. for _, name := range names {
  53. curSeq, _, err := parseWalName(name)
  54. if err != nil {
  55. log.Panicf("parse correct name should never fail: %v", err)
  56. }
  57. if lastSeq != 0 && lastSeq != curSeq-1 {
  58. return false
  59. }
  60. lastSeq = curSeq
  61. }
  62. return true
  63. }
  64. func checkWalNames(names []string) []string {
  65. wnames := make([]string, 0)
  66. for _, name := range names {
  67. if _, _, err := parseWalName(name); err != nil {
  68. log.Printf("wal: ignored file %v in wal", name)
  69. continue
  70. }
  71. wnames = append(wnames, name)
  72. }
  73. return wnames
  74. }
  75. func parseWalName(str string) (seq, index uint64, err error) {
  76. if !strings.HasSuffix(str, ".wal") {
  77. return 0, 0, badWalName
  78. }
  79. _, err = fmt.Sscanf(str, "%016x-%016x.wal", &seq, &index)
  80. return seq, index, err
  81. }
  82. func walName(seq, index uint64) string {
  83. return fmt.Sprintf("%016x-%016x.wal", seq, index)
  84. }