purge.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2015 The etcd Authors
  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 fileutil
  15. import (
  16. "os"
  17. "path"
  18. "sort"
  19. "strings"
  20. "time"
  21. )
  22. func PurgeFile(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}) <-chan error {
  23. return purgeFile(dirname, suffix, max, interval, stop, nil)
  24. }
  25. // purgeFile is the internal implementation for PurgeFile which can post purged files to purgec if non-nil.
  26. func purgeFile(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}, purgec chan<- string) <-chan error {
  27. errC := make(chan error, 1)
  28. go func() {
  29. for {
  30. fnames, err := ReadDir(dirname)
  31. if err != nil {
  32. errC <- err
  33. return
  34. }
  35. newfnames := make([]string, 0)
  36. for _, fname := range fnames {
  37. if strings.HasSuffix(fname, suffix) {
  38. newfnames = append(newfnames, fname)
  39. }
  40. }
  41. sort.Strings(newfnames)
  42. fnames = newfnames
  43. for len(newfnames) > int(max) {
  44. f := path.Join(dirname, newfnames[0])
  45. l, err := TryLockFile(f, os.O_WRONLY, PrivateFileMode)
  46. if err != nil {
  47. break
  48. }
  49. if err = os.Remove(f); err != nil {
  50. errC <- err
  51. return
  52. }
  53. if err = l.Close(); err != nil {
  54. plog.Errorf("error unlocking %s when purging file (%v)", l.Name(), err)
  55. errC <- err
  56. return
  57. }
  58. plog.Infof("purged file %s successfully", f)
  59. newfnames = newfnames[1:]
  60. }
  61. if purgec != nil {
  62. for i := 0; i < len(fnames)-len(newfnames); i++ {
  63. purgec <- fnames[i]
  64. }
  65. }
  66. select {
  67. case <-time.After(interval):
  68. case <-stop:
  69. return
  70. }
  71. }
  72. }()
  73. return errC
  74. }