forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filecount.go
311 lines (269 loc) · 7.04 KB
/
filecount.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package filecount
import (
"os"
"path/filepath"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/internal/globpath"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/karrick/godirwalk"
"github.com/pkg/errors"
)
const sampleConfig = `
## Directory to gather stats about.
## deprecated in 1.9; use the directories option
# directory = "/var/cache/apt/archives"
## Directories to gather stats about.
## This accept standard unit glob matching rules, but with the addition of
## ** as a "super asterisk". ie:
## /var/log/** -> recursively find all directories in /var/log and count files in each directories
## /var/log/*/* -> find all directories with a parent dir in /var/log and count files in each directories
## /var/log -> count all files in /var/log and all of its subdirectories
directories = ["/var/cache/apt/archives"]
## Only count files that match the name pattern. Defaults to "*".
name = "*.deb"
## Count files in subdirectories. Defaults to true.
recursive = false
## Only count regular files. Defaults to true.
regular_only = true
## Only count files that are at least this size. If size is
## a negative number, only count files that are smaller than the
## absolute value of size. Acceptable units are B, KiB, MiB, KB, ...
## Without quotes and units, interpreted as size in bytes.
size = "0B"
## Only count files that have not been touched for at least this
## duration. If mtime is negative, only count files that have been
## touched in this duration. Defaults to "0s".
mtime = "0s"
`
type FileCount struct {
Directory string // deprecated in 1.9
Directories []string
Name string
Recursive bool
RegularOnly bool
Size internal.Size
MTime internal.Duration `toml:"mtime"`
fileFilters []fileFilterFunc
globPaths []globpath.GlobPath
Fs fileSystem
Log telegraf.Logger
}
func (_ *FileCount) Description() string {
return "Count files in a directory"
}
func (_ *FileCount) SampleConfig() string { return sampleConfig }
type fileFilterFunc func(os.FileInfo) (bool, error)
func rejectNilFilters(filters []fileFilterFunc) []fileFilterFunc {
filtered := make([]fileFilterFunc, 0, len(filters))
for _, f := range filters {
if f != nil {
filtered = append(filtered, f)
}
}
return filtered
}
func (fc *FileCount) nameFilter() fileFilterFunc {
if fc.Name == "*" {
return nil
}
return func(f os.FileInfo) (bool, error) {
match, err := filepath.Match(fc.Name, f.Name())
if err != nil {
return false, err
}
return match, nil
}
}
func (fc *FileCount) regularOnlyFilter() fileFilterFunc {
if !fc.RegularOnly {
return nil
}
return func(f os.FileInfo) (bool, error) {
return f.Mode().IsRegular(), nil
}
}
func (fc *FileCount) sizeFilter() fileFilterFunc {
if fc.Size.Size == 0 {
return nil
}
return func(f os.FileInfo) (bool, error) {
if !f.Mode().IsRegular() {
return false, nil
}
if fc.Size.Size < 0 {
return f.Size() < -fc.Size.Size, nil
}
return f.Size() >= fc.Size.Size, nil
}
}
func (fc *FileCount) mtimeFilter() fileFilterFunc {
if fc.MTime.Duration == 0 {
return nil
}
return func(f os.FileInfo) (bool, error) {
age := absDuration(fc.MTime.Duration)
mtime := time.Now().Add(-age)
if fc.MTime.Duration < 0 {
return f.ModTime().After(mtime), nil
}
return f.ModTime().Before(mtime), nil
}
}
func absDuration(x time.Duration) time.Duration {
if x < 0 {
return -x
}
return x
}
func (fc *FileCount) initFileFilters() {
filters := []fileFilterFunc{
fc.nameFilter(),
fc.regularOnlyFilter(),
fc.sizeFilter(),
fc.mtimeFilter(),
}
fc.fileFilters = rejectNilFilters(filters)
}
func (fc *FileCount) count(acc telegraf.Accumulator, basedir string, glob globpath.GlobPath) {
childCount := make(map[string]int64)
childSize := make(map[string]int64)
walkFn := func(path string, de *godirwalk.Dirent) error {
rel, err := filepath.Rel(basedir, path)
if err == nil && rel == "." {
return nil
}
file, err := fc.Fs.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
match, err := fc.filter(file)
if err != nil {
acc.AddError(err)
return nil
}
if match {
parent := filepath.Dir(path)
childCount[parent]++
childSize[parent] += file.Size()
}
if file.IsDir() && !fc.Recursive && !glob.HasSuperMeta {
return filepath.SkipDir
}
return nil
}
postChildrenFn := func(path string, de *godirwalk.Dirent) error {
if glob.MatchString(path) {
gauge := map[string]interface{}{
"count": childCount[path],
"size_bytes": childSize[path],
}
acc.AddGauge("filecount", gauge,
map[string]string{
"directory": path,
})
}
parent := filepath.Dir(path)
if fc.Recursive {
childCount[parent] += childCount[path]
childSize[parent] += childSize[path]
}
delete(childCount, path)
delete(childSize, path)
return nil
}
err := godirwalk.Walk(basedir, &godirwalk.Options{
Callback: walkFn,
PostChildrenCallback: postChildrenFn,
Unsorted: true,
ErrorCallback: func(osPathname string, err error) godirwalk.ErrorAction {
if os.IsPermission(errors.Cause(err)) {
fc.Log.Debug(err)
return godirwalk.SkipNode
}
return godirwalk.Halt
},
})
if err != nil {
acc.AddError(err)
}
}
func (fc *FileCount) filter(file os.FileInfo) (bool, error) {
if fc.fileFilters == nil {
fc.initFileFilters()
}
for _, fileFilter := range fc.fileFilters {
match, err := fileFilter(file)
if err != nil {
return false, err
}
if !match {
return false, nil
}
}
return true, nil
}
func (fc *FileCount) Gather(acc telegraf.Accumulator) error {
if fc.globPaths == nil {
fc.initGlobPaths(acc)
}
for _, glob := range fc.globPaths {
for _, dir := range fc.onlyDirectories(glob.GetRoots()) {
fc.count(acc, dir, glob)
}
}
return nil
}
func (fc *FileCount) onlyDirectories(directories []string) []string {
out := make([]string, 0)
for _, path := range directories {
info, err := fc.Fs.Stat(path)
if err == nil && info.IsDir() {
out = append(out, path)
}
}
return out
}
func (fc *FileCount) getDirs() []string {
dirs := make([]string, len(fc.Directories))
for i, dir := range fc.Directories {
dirs[i] = filepath.Clean(dir)
}
if fc.Directory != "" {
dirs = append(dirs, filepath.Clean(fc.Directory))
}
return dirs
}
func (fc *FileCount) initGlobPaths(acc telegraf.Accumulator) {
fc.globPaths = []globpath.GlobPath{}
for _, directory := range fc.getDirs() {
glob, err := globpath.Compile(directory)
if err != nil {
acc.AddError(err)
} else {
fc.globPaths = append(fc.globPaths, *glob)
}
}
}
func NewFileCount() *FileCount {
return &FileCount{
Directory: "",
Directories: []string{},
Name: "*",
Recursive: true,
RegularOnly: true,
Size: internal.Size{Size: 0},
MTime: internal.Duration{Duration: 0},
fileFilters: nil,
Fs: osFS{},
}
}
func init() {
inputs.Add("filecount", func() telegraf.Input {
return NewFileCount()
})
}