consistentread.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package io
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io/ioutil"
  18. )
  19. // ConsistentRead repeatedly reads a file until it gets the same content twice.
  20. // This is useful when reading files in /proc that are larger than page size
  21. // and kernel may modify them between individual read() syscalls.
  22. func ConsistentRead(filename string, attempts int) ([]byte, error) {
  23. return consistentReadSync(filename, attempts, nil)
  24. }
  25. // consistentReadSync is the main functionality of ConsistentRead but
  26. // introduces a sync callback that can be used by the tests to mutate the file
  27. // from which the test data is being read
  28. func consistentReadSync(filename string, attempts int, sync func(int)) ([]byte, error) {
  29. oldContent, err := ioutil.ReadFile(filename)
  30. if err != nil {
  31. return nil, err
  32. }
  33. for i := 0; i < attempts; i++ {
  34. if sync != nil {
  35. sync(i)
  36. }
  37. newContent, err := ioutil.ReadFile(filename)
  38. if err != nil {
  39. return nil, err
  40. }
  41. if bytes.Compare(oldContent, newContent) == 0 {
  42. return newContent, nil
  43. }
  44. // Files are different, continue reading
  45. oldContent = newContent
  46. }
  47. return nil, fmt.Errorf("could not get consistent content of %s after %d attempts", filename, attempts)
  48. }