blob: c97368069198f049411d4930c8afc0df650d975e [file] [log] [blame]
khenaidood948f772021-08-11 17:49:24 -04001// 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
15package fileutil
16
17import (
18 "os"
19 "path/filepath"
20 "sort"
21 "strings"
22 "time"
23)
24
25func PurgeFile(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}) <-chan error {
26 return purgeFile(dirname, suffix, max, interval, stop, nil, nil)
27}
28
29func PurgeFileWithDoneNotify(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}) (<-chan struct{}, <-chan error) {
30 doneC := make(chan struct{})
31 errC := purgeFile(dirname, suffix, max, interval, stop, nil, doneC)
32 return doneC, errC
33}
34
35// purgeFile is the internal implementation for PurgeFile which can post purged files to purgec if non-nil.
36// if donec is non-nil, the function closes it to notify its exit.
37func purgeFile(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}, purgec chan<- string, donec chan<- struct{}) <-chan error {
38 errC := make(chan error, 1)
39 go func() {
40 if donec != nil {
41 defer close(donec)
42 }
43 for {
44 fnames, err := ReadDir(dirname)
45 if err != nil {
46 errC <- err
47 return
48 }
49 newfnames := make([]string, 0)
50 for _, fname := range fnames {
51 if strings.HasSuffix(fname, suffix) {
52 newfnames = append(newfnames, fname)
53 }
54 }
55 sort.Strings(newfnames)
56 fnames = newfnames
57 for len(newfnames) > int(max) {
58 f := filepath.Join(dirname, newfnames[0])
59 l, err := TryLockFile(f, os.O_WRONLY, PrivateFileMode)
60 if err != nil {
61 break
62 }
63 if err = os.Remove(f); err != nil {
64 errC <- err
65 return
66 }
67 if err = l.Close(); err != nil {
68 plog.Errorf("error unlocking %s when purging file (%v)", l.Name(), err)
69 errC <- err
70 return
71 }
72 plog.Infof("purged file %s successfully", f)
73 newfnames = newfnames[1:]
74 }
75 if purgec != nil {
76 for i := 0; i < len(fnames)-len(newfnames); i++ {
77 purgec <- fnames[i]
78 }
79 }
80 select {
81 case <-time.After(interval):
82 case <-stop:
83 return
84 }
85 }
86 }()
87 return errC
88}