purge.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 := NewLock(f)
  41. if err != nil {
  42. errC <- err
  43. return
  44. }
  45. err = l.TryLock()
  46. if err != nil {
  47. break
  48. }
  49. err = os.Remove(f)
  50. if err != nil {
  51. errC <- err
  52. return
  53. }
  54. err = l.Unlock()
  55. if err != nil {
  56. plog.Errorf("error unlocking %s when purging file (%v)", l.Name(), err)
  57. errC <- err
  58. return
  59. }
  60. err = l.Destroy()
  61. if err != nil {
  62. plog.Errorf("error destroying lock %s when purging file (%v)", l.Name(), err)
  63. errC <- err
  64. return
  65. }
  66. plog.Infof("purged file %s successfully", f)
  67. newfnames = newfnames[1:]
  68. }
  69. select {
  70. case <-time.After(interval):
  71. case <-stop:
  72. return
  73. }
  74. }
  75. }()
  76. return errC
  77. }