util.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. "strings"
  19. "github.com/coreos/etcd/pkg/fileutil"
  20. )
  21. var (
  22. badWalName = errors.New("bad wal name")
  23. )
  24. func Exist(dirpath string) bool {
  25. names, err := fileutil.ReadDir(dirpath)
  26. if err != nil {
  27. return false
  28. }
  29. return len(names) != 0
  30. }
  31. // searchIndex returns the last array index of names whose raft index section is
  32. // equal to or smaller than the given index.
  33. // The given names MUST be sorted.
  34. func searchIndex(names []string, index uint64) (int, bool) {
  35. for i := len(names) - 1; i >= 0; i-- {
  36. name := names[i]
  37. _, curIndex, err := parseWalName(name)
  38. if err != nil {
  39. plog.Panicf("parse correct name should never fail: %v", err)
  40. }
  41. if index >= curIndex {
  42. return i, true
  43. }
  44. }
  45. return -1, false
  46. }
  47. // names should have been sorted based on sequence number.
  48. // isValidSeq checks whether seq increases continuously.
  49. func isValidSeq(names []string) bool {
  50. var lastSeq uint64
  51. for _, name := range names {
  52. curSeq, _, err := parseWalName(name)
  53. if err != nil {
  54. plog.Panicf("parse correct name should never fail: %v", err)
  55. }
  56. if lastSeq != 0 && lastSeq != curSeq-1 {
  57. return false
  58. }
  59. lastSeq = curSeq
  60. }
  61. return true
  62. }
  63. func checkWalNames(names []string) []string {
  64. wnames := make([]string, 0)
  65. for _, name := range names {
  66. if _, _, err := parseWalName(name); err != nil {
  67. plog.Warningf("ignored file %v in wal", name)
  68. continue
  69. }
  70. wnames = append(wnames, name)
  71. }
  72. return wnames
  73. }
  74. func parseWalName(str string) (seq, index uint64, err error) {
  75. if !strings.HasSuffix(str, ".wal") {
  76. return 0, 0, badWalName
  77. }
  78. _, err = fmt.Sscanf(str, "%016x-%016x.wal", &seq, &index)
  79. return seq, index, err
  80. }
  81. func walName(seq, index uint64) string {
  82. return fmt.Sprintf("%016x-%016x.wal", seq, index)
  83. }