purge.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 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. errC := make(chan error, 1)
  24. go func() {
  25. for {
  26. fnames, err := ReadDir(dirname)
  27. if err != nil {
  28. errC <- err
  29. return
  30. }
  31. newfnames := make([]string, 0)
  32. for _, fname := range fnames {
  33. if strings.HasSuffix(fname, suffix) {
  34. newfnames = append(newfnames, fname)
  35. }
  36. }
  37. sort.Strings(newfnames)
  38. for len(newfnames) > int(max) {
  39. f := path.Join(dirname, newfnames[0])
  40. l, err := TryLockFile(f, os.O_WRONLY, 0600)
  41. if err != nil {
  42. break
  43. }
  44. if err = os.Remove(f); err != nil {
  45. errC <- err
  46. return
  47. }
  48. if err = l.Close(); err != nil {
  49. plog.Errorf("error unlocking %s when purging file (%v)", l.Name(), err)
  50. errC <- err
  51. return
  52. }
  53. plog.Infof("purged file %s successfully", f)
  54. newfnames = newfnames[1:]
  55. }
  56. select {
  57. case <-time.After(interval):
  58. case <-stop:
  59. return
  60. }
  61. }
  62. }()
  63. return errC
  64. }