util.go 2.2 KB

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