summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/filecheck/collect_dirs.go
blob: 69a2e2f5cae7f27d156da584c30a823f2c2ace9d (plain)
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
// SPDX-License-Identifier: GPL-3.0-or-later

package filecheck

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/netdata/netdata/go/go.d.plugin/agent/module"
)

func (fc *Filecheck) collectDirs(ms map[string]int64) {
	curTime := time.Now()
	if time.Since(fc.lastDiscoveryDirs) >= fc.DiscoveryEvery.Duration() {
		fc.lastDiscoveryDirs = curTime
		fc.curDirs = fc.discoveryDirs()
		fc.updateDirsCharts(fc.curDirs)
	}

	for _, path := range fc.curDirs {
		fc.collectDir(ms, path, curTime)
	}
	ms["num_of_dirs"] = int64(len(fc.curDirs))
}

func (fc *Filecheck) collectDir(ms map[string]int64, path string, curTime time.Time) {
	info, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			ms[dirDimID(path, "exists")] = 0
		} else {
			ms[dirDimID(path, "exists")] = 1
		}
		fc.Debug(err)
		return
	}

	if !info.IsDir() {
		return
	}

	ms[dirDimID(path, "exists")] = 1
	ms[dirDimID(path, "mtime_ago")] = int64(curTime.Sub(info.ModTime()).Seconds())
	if num, err := calcDirNumOfFiles(path); err == nil {
		ms[dirDimID(path, "num_of_files")] = int64(num)
	}
	if fc.Dirs.CollectDirSize {
		if size, err := calcDirSize(path); err == nil {
			ms[dirDimID(path, "size_bytes")] = size
		}
	}
}

func (fc *Filecheck) discoveryDirs() (dirs []string) {
	for _, path := range fc.Dirs.Include {
		if hasMeta(path) {
			continue
		}
		dirs = append(dirs, path)
	}

	for _, path := range fc.Dirs.Include {
		if !hasMeta(path) {
			continue
		}
		matches, _ := filepath.Glob(path)
		for _, v := range matches {
			fi, err := os.Lstat(v)
			if err == nil && fi.IsDir() {
				dirs = append(dirs, v)
			}
		}
	}
	return removeDuplicates(dirs)
}

func (fc *Filecheck) updateDirsCharts(dirs []string) {
	set := make(map[string]bool, len(dirs))
	for _, path := range dirs {
		set[path] = true
		if !fc.collectedDirs[path] {
			fc.collectedDirs[path] = true
			fc.addDirToCharts(path)
		}
	}
	for path := range fc.collectedDirs {
		if !set[path] {
			delete(fc.collectedDirs, path)
			fc.removeDirFromCharts(path)
		}
	}
}

func (fc *Filecheck) addDirToCharts(path string) {
	for _, chart := range *fc.Charts() {
		if !strings.HasPrefix(chart.ID, "dir_") {
			continue
		}

		var id string
		switch chart.ID {
		case dirExistenceChart.ID:
			id = dirDimID(path, "exists")
		case dirModTimeChart.ID:
			id = dirDimID(path, "mtime_ago")
		case dirNumOfFilesChart.ID:
			id = dirDimID(path, "num_of_files")
		case dirSizeChart.ID:
			id = dirDimID(path, "size_bytes")
		default:
			fc.Warningf("add dimension: couldn't dim id for '%s' chart (dir '%s')", chart.ID, path)
			continue
		}

		dim := &module.Dim{ID: id, Name: reSpace.ReplaceAllString(path, "_")}

		if err := chart.AddDim(dim); err != nil {
			fc.Warning(err)
			continue
		}
		chart.MarkNotCreated()
	}
}

func (fc *Filecheck) removeDirFromCharts(path string) {
	for _, chart := range *fc.Charts() {
		if !strings.HasPrefix(chart.ID, "dir_") {
			continue
		}

		var id string
		switch chart.ID {
		case dirExistenceChart.ID:
			id = dirDimID(path, "exists")
		case dirModTimeChart.ID:
			id = dirDimID(path, "mtime_ago")
		case dirNumOfFilesChart.ID:
			id = dirDimID(path, "num_of_files")
		case dirSizeChart.ID:
			id = dirDimID(path, "size_bytes")
		default:
			fc.Warningf("remove dimension: couldn't dim id for '%s' chart (dir '%s')", chart.ID, path)
			continue
		}

		if err := chart.MarkDimRemove(id, true); err != nil {
			fc.Warning(err)
			continue
		}
		chart.MarkNotCreated()
	}
}

func dirDimID(path, metric string) string {
	return fmt.Sprintf("dir_%s_%s", reSpace.ReplaceAllString(path, "_"), metric)
}

func calcDirNumOfFiles(dirpath string) (int, error) {
	f, err := os.Open(dirpath)
	if err != nil {
		return 0, err
	}
	defer func() { _ = f.Close() }()
	// TODO: include dirs?
	names, err := f.Readdirnames(-1)
	return len(names), err
}

func calcDirSize(dirpath string) (int64, error) {
	var size int64
	err := filepath.Walk(dirpath, func(_ string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			size += info.Size()
		}
		return nil
	})
	return size, err
}