forked from oliwur/directory_stat_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirstat.go
205 lines (182 loc) · 5.37 KB
/
dirstat.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
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/codestoke/directory_stat_exporter/cfg"
"github.com/prometheus/common/promlog"
"github.com/prometheus/exporter-toolkit/web"
)
type metricValue struct {
labels map[string]string
name string
value int64
recursive bool
}
type metric struct {
metricName string
metricHelp string
metricType string
metricValues map[string]metricValue
}
const (
namespace = "dirstat"
metricFilesInDir = "files_in_dir"
metricOldestFileTime = "oldest_file_time"
metricCurrentTimestamp = "current_timestamp"
)
var (
config cfg.Config
metricRegister map[string]metric
currentTimestamp metric
cache []byte
lastRequest time.Time
cacheLock sync.Mutex
)
func main() {
var configFile string
flag.StringVar(&configFile, "config.file", "config.yml", "provide a custom config file")
var (
tlsConfigFile = flag.String("web.config", "", "Path to config yaml file that can enable TLS or authentication.")
)
flag.Parse()
config = cfg.GetConfig(configFile)
metricRegister = make(map[string]metric)
metricRegister[metricFilesInDir] = metric{
metricName: metricFilesInDir,
metricType: "gauge",
metricHelp: "this counts all the files in a directory",
metricValues: make(map[string]metricValue),
}
metricRegister[metricOldestFileTime] = metric{
metricName: metricOldestFileTime,
metricType: "gauge",
metricHelp: "displays the timestamp in unix time of the oldest file",
metricValues: make(map[string]metricValue),
}
lastRequest = time.Unix(0, 0)
cache = []byte("# dirstat")
promlogConfig := &promlog.Config{}
logger := promlog.New(promlogConfig)
http.HandleFunc("/metrics", handleMetrics)
server := &http.Server{Addr: ":" + config.ServicePort}
if err := web.ListenAndServe(server, *tlsConfigFile, logger); err != nil {
log.Fatalf("Failed to start the server: %v", err)
os.Exit(1)
}
}
func handleMetrics(w http.ResponseWriter, _ *http.Request) {
if lastRequest.Add(time.Minute*time.Duration(config.CacheTime)).Unix() < time.Now().Unix() {
// update the cache
{
writeMetricsResponse(w)
go updateMetrics()
}
} else {
// respond with the cache.
writeMetricsResponse(w)
}
}
func getMetricValues() []byte {
res := sprintDirMetric(currentTimestamp)
for _, value := range metricRegister {
res += sprintDirMetric(value)
}
return []byte(res)
}
func writeMetricsResponse(w http.ResponseWriter) {
_, _ = w.Write(cache)
}
func updateMetrics() {
cacheLock.Lock()
for _, dir := range config.Directories {
if dir.Recursive {
metricRegister[metricFilesInDir].metricValues[dir.Path] = metricValue{
value: int64(getFileCountInDirRecursively(dir.Path)),
recursive: dir.Recursive,
name: dir.Name,
labels: map[string]string{
"dir": dir.Name,
"recursive": strconv.FormatBool(dir.Recursive),
},
}
metricRegister[metricOldestFileTime].metricValues[dir.Path] = metricValue{
value: int64(getOldestAgeInDirRecursively(dir.Path)),
recursive: dir.Recursive,
name: dir.Name,
labels: map[string]string{
"dir": dir.Name,
"recursive": strconv.FormatBool(dir.Recursive),
},
}
} else {
metricRegister[metricFilesInDir].metricValues[dir.Path] = metricValue{
value: int64(getFileCountInDir(dir.Path)),
recursive: dir.Recursive,
name: dir.Name,
labels: map[string]string{
"dir": dir.Name,
"recursive": strconv.FormatBool(dir.Recursive),
},
}
metricRegister[metricOldestFileTime].metricValues[dir.Path] = metricValue{
value: int64(getOldestAgeInDir(dir.Path)),
recursive: dir.Recursive,
name: dir.Name,
labels: map[string]string{
"dir": dir.Name,
"recursive": strconv.FormatBool(dir.Recursive),
},
}
}
}
currentTimestamp = metric{
metricName: metricCurrentTimestamp,
metricHelp: "the current timestamp in unix time.",
metricType: "gauge",
metricValues: map[string]metricValue{"ts": {value: time.Now().Unix()}},
}
cache = getMetricValues()
lastRequest = time.Now()
cacheLock.Unlock()
}
// this should be replaced with one more generic generator.
//func sprintCurrentTimestamp(m metric) string {
// str := ""
// str += fmt.Sprintf("# HELP %s_%s %s\n", namespace, m.metricName, m.metricHelp)
// str += fmt.Sprintf("# TYPE %s_%s %s\n", namespace, m.metricName, m.metricType)
// for _, v := range m.metricValues {
// str += fmt.Sprintf("%s_%s %v\n", namespace, m.metricName, v.value)
// }
// return str
//}
func sprintDirMetric(m metric) string {
str := ""
str += fmt.Sprintf("# HELP %s_%s %s\n", namespace, m.metricName, m.metricHelp)
str += fmt.Sprintf("# TYPE %s_%s %s\n", namespace, m.metricName, m.metricType)
for _, v := range m.metricValues {
//str += fmt.Sprintf("%s_%s{dir=\"%s\",recursive=\"%t\"} %v\n", namespace, m.metricName, v.name, v.recursive, v.value)
str += sprintMetric(namespace, m.metricName, v.value, v.labels)
}
return str
}
func sprintMetric(ns string, name string, value int64, labels map[string]string) string {
strLbls := ""
if labels != nil {
var lblArr []string
strLbls += "{"
for k, v := range labels {
lblArr = append(lblArr, fmt.Sprintf("%s=\"%s\"", k, v))
}
strLbls += strings.Join(lblArr, ",")
strLbls += "}"
}
str := fmt.Sprintf("%s_%s%s %v\n", ns, name, strLbls, value)
return str
}