purge.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "log"
  17. "os"
  18. "path"
  19. "sort"
  20. "strings"
  21. "time"
  22. )
  23. func PurgeFile(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}) <-chan error {
  24. errC := make(chan error, 1)
  25. go func() {
  26. for {
  27. fnames, err := ReadDir(dirname)
  28. if err != nil {
  29. errC <- err
  30. return
  31. }
  32. newfnames := make([]string, 0)
  33. for _, fname := range fnames {
  34. if strings.HasSuffix(fname, suffix) {
  35. newfnames = append(newfnames, fname)
  36. }
  37. }
  38. sort.Strings(newfnames)
  39. for len(newfnames) > int(max) {
  40. f := path.Join(dirname, newfnames[0])
  41. l, err := NewLock(f)
  42. if err != nil {
  43. errC <- err
  44. return
  45. }
  46. err = l.TryLock()
  47. if err != nil {
  48. break
  49. }
  50. err = os.Remove(f)
  51. if err != nil {
  52. errC <- err
  53. return
  54. }
  55. err = l.Unlock()
  56. if err != nil {
  57. log.Printf("filePurge: unlock %s error %v", l.Name(), err)
  58. }
  59. err = l.Destroy()
  60. if err != nil {
  61. log.Printf("filePurge: destroy lock %s error %v", l.Name(), err)
  62. }
  63. log.Printf("filePurge: successfully removed file %s", f)
  64. newfnames = newfnames[1:]
  65. }
  66. select {
  67. case <-time.After(interval):
  68. case <-stop:
  69. return
  70. }
  71. }
  72. }()
  73. return errC
  74. }