-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
448 lines (375 loc) · 10.4 KB
/
main.go
File metadata and controls
448 lines (375 loc) · 10.4 KB
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
port = 9150
rsyncFilePath = "/logs/rsync.log"
debug = false
)
// unitDef defines a byte unit with its multiplier and recognized suffixes
type unitDef struct {
multiplier float64
suffixes []string
}
// byteUnits defines recognized byte unit suffixes (package-level to avoid allocation per call)
var byteUnits = []unitDef{
{multiplier: 1024, suffixes: []string{"KIB", "KI", "KB", "K"}},
{multiplier: 1024 * 1024, suffixes: []string{"MIB", "MI", "MB", "M"}},
{multiplier: 1024 * 1024 * 1024, suffixes: []string{"GIB", "GI", "GB", "G"}},
{multiplier: 1024 * 1024 * 1024 * 1024, suffixes: []string{"TIB", "TI", "TB", "T"}},
}
func init() {
if portEnv := os.Getenv("RSYNC_EXPORTER_PORT"); portEnv != "" {
parsedPort, err := strconv.Atoi(portEnv)
if err != nil || parsedPort <= 0 || parsedPort > 65535 {
fmt.Fprintf(os.Stderr, "invalid RSYNC_EXPORTER_PORT value %q, using default %d\n", portEnv, port)
} else {
port = parsedPort
}
}
if pathEnv := os.Getenv("RSYNC_LOG_PATH"); pathEnv != "" {
rsyncFilePath = pathEnv
}
if debugEnv := os.Getenv("RSYNC_DEBUG"); debugEnv != "" {
debugEnv = strings.ToLower(debugEnv)
debug = debugEnv == "true" || debugEnv == "1"
}
}
var (
bytesSentGauge = promauto.NewGauge(prometheus.GaugeOpts{
Name: "rsync_last_sent_bytes",
Help: "Bytes sent during the most recent rsync run",
})
bytesReceivedGauge = promauto.NewGauge(prometheus.GaugeOpts{
Name: "rsync_last_received_bytes",
Help: "Bytes received during the most recent rsync run",
})
totalSizeGauge = promauto.NewGauge(prometheus.GaugeOpts{
Name: "rsync_last_total_size_bytes",
Help: "Total size synced during the most recent rsync run",
})
lastRsyncExecutionTime = promauto.NewGauge(prometheus.GaugeOpts{
Name: "rsync_last_sync",
Help: "Last rsync sync time",
})
lastRsyncExecutionTimeValid = promauto.NewGauge(prometheus.GaugeOpts{
Name: "rsync_last_sync_valid",
Help: "Indicates if the last rsync sync time is valid",
})
)
// debugf prints a message only when debug mode is enabled
func debugf(format string, args ...interface{}) {
if debug {
fmt.Printf(format, args...)
}
}
func parseBytesToken(token string) (float64, error) {
cleaned := strings.TrimSpace(token)
cleaned = strings.Trim(cleaned, ",")
cleaned = strings.ReplaceAll(cleaned, ",", "")
if cleaned == "" {
return 0, fmt.Errorf("empty token")
}
multiplier := 1.0
upper := strings.ToUpper(cleaned)
for _, unit := range byteUnits {
for _, suffix := range unit.suffixes {
if strings.HasSuffix(upper, suffix) {
cut := len(cleaned) - len(suffix)
if cut < 0 {
cut = 0
}
cleaned = cleaned[:cut]
upper = upper[:cut]
multiplier = unit.multiplier
break
}
}
if multiplier != 1.0 {
break
}
}
if strings.HasSuffix(upper, "B") {
cut := len(cleaned) - 1
if cut < 0 {
cut = 0
}
cleaned = cleaned[:cut]
upper = upper[:cut]
}
cleaned = strings.TrimSpace(cleaned)
if cleaned == "" {
return 0, fmt.Errorf("no numeric value in token")
}
value, err := strconv.ParseFloat(cleaned, 64)
if err != nil {
return 0, err
}
result := value * multiplier
if result < 0 {
return 0, fmt.Errorf("negative byte value: %f", result)
}
return result, nil
}
func setupHTTPListener(ctx context.Context, errCh chan<- error) {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
server := &http.Server{
Addr: ":" + strconv.Itoa(port),
Handler: mux,
}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
fmt.Fprintf(os.Stderr, "HTTP server shutdown error: %v\n", err)
}
}()
fmt.Println("Starting HTTP listener for Prometheus metrics...")
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- fmt.Errorf("error starting HTTP server: %w", err)
}
}
func parseLogLine(logLine string) {
tokens := strings.Fields(logLine)
if len(tokens) == 0 {
return
}
for idx := 0; idx < len(tokens); idx++ {
switch tokens[idx] {
case "sent":
if idx+1 >= len(tokens) {
continue
}
value, err := parseBytesToken(tokens[idx+1])
if err != nil {
fmt.Fprintf(os.Stderr, "error parsing sent bytes: %v\n", err)
continue
}
debugf("Sent bytes: %f\n", value)
bytesSentGauge.Set(value)
case "received":
if idx+1 >= len(tokens) {
continue
}
value, err := parseBytesToken(tokens[idx+1])
if err != nil {
fmt.Fprintf(os.Stderr, "error parsing received bytes: %v\n", err)
continue
}
debugf("Received bytes: %f\n", value)
bytesReceivedGauge.Set(value)
case "total":
if idx+1 >= len(tokens) || tokens[idx+1] != "size" {
continue
}
valueIdx := idx + 2
if valueIdx < len(tokens) && tokens[valueIdx] == "is" {
valueIdx++
}
if valueIdx >= len(tokens) {
continue
}
value, err := parseBytesToken(tokens[valueIdx])
if err != nil {
fmt.Fprintf(os.Stderr, "error parsing total size bytes: %v\n", err)
lastRsyncExecutionTimeValid.Set(0)
continue
}
debugf("Total size bytes: %f\n", value)
totalSizeGauge.Set(value)
currentTimeSeconds := float64(time.Now().Unix())
debugf("Setting last sync time to %f\n", currentTimeSeconds)
lastRsyncExecutionTime.Set(currentTimeSeconds)
lastRsyncExecutionTimeValid.Set(1)
}
}
}
func tailLogFile(ctx context.Context, filePath string) error {
debugf("Attempting to tail log file: %s\n", filePath)
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("error opening log file: %w", err)
}
defer func() {
if file != nil {
if err := file.Close(); err != nil {
fmt.Fprintf(os.Stderr, "error closing log file handle: %v\n", err)
}
}
}()
fileInfo, err := file.Stat()
if err != nil {
return fmt.Errorf("error stating log file: %w", err)
}
if _, err := file.Seek(0, io.SeekEnd); err != nil {
return fmt.Errorf("error seeking log file: %w", err)
}
fmt.Println("Successfully started tailing log file.")
reader := bufio.NewReader(file)
var pending string
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
chunk, readErr := reader.ReadString('\n')
if len(chunk) > 0 {
pending += chunk
for {
newlineIdx := strings.IndexByte(pending, '\n')
if newlineIdx == -1 {
break
}
line := strings.TrimRight(pending[:newlineIdx], "\r")
if line != "" {
parseLogLine(line)
}
pending = pending[newlineIdx+1:]
}
}
if readErr != nil {
if errors.Is(readErr, io.EOF) {
time.Sleep(500 * time.Millisecond)
newInfo, statErr := os.Stat(filePath)
if statErr != nil {
if os.IsNotExist(statErr) {
// File was deleted - close old handle and wait for it to reappear
if file != nil {
if err := file.Close(); err != nil {
fmt.Fprintf(os.Stderr, "error closing deleted log file handle: %v\n", err)
}
file = nil
}
// Wait for file to reappear
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(1 * time.Second):
}
newInfo, statErr = os.Stat(filePath)
if statErr == nil {
break
}
if !os.IsNotExist(statErr) {
return fmt.Errorf("error stating log file while waiting: %w", statErr)
}
}
// Reopen the file
reopened, openErr := os.Open(filePath)
if openErr != nil {
return fmt.Errorf("error reopening log file after deletion: %w", openErr)
}
file = reopened
fileInfo, err = file.Stat()
if err != nil {
return fmt.Errorf("error stating reopened log file: %w", err)
}
reader.Reset(file)
pending = ""
continue
}
return fmt.Errorf("error stating log file: %w", statErr)
}
if !os.SameFile(fileInfo, newInfo) {
if err := file.Close(); err != nil {
fmt.Fprintf(os.Stderr, "error closing old log file handle: %v\n", err)
}
file = nil
reopened, openErr := os.Open(filePath)
if openErr != nil {
return fmt.Errorf("error reopening rotated log file: %w", openErr)
}
file = reopened
reader.Reset(file)
fileInfo = newInfo
pending = ""
} else {
currentOffset, seekErr := file.Seek(0, io.SeekCurrent)
if seekErr != nil {
return fmt.Errorf("error checking current offset: %w", seekErr)
}
if currentOffset > newInfo.Size() {
if _, err := file.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("error seeking after truncation: %w", err)
}
reader.Reset(file)
pending = ""
}
}
continue
}
return fmt.Errorf("log reader error: %w", readErr)
}
}
}
func main() {
fmt.Println("Rsync Exporter starting...")
fmt.Printf("Watching rsync log at %s\n", rsyncFilePath)
fmt.Printf("Serving metrics on port %d\n", port)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Handle shutdown signals
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
// Channel for HTTP server errors
httpErrCh := make(chan error, 1)
go setupHTTPListener(ctx, httpErrCh)
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
if err := tailLogFile(ctx, rsyncFilePath); err != nil {
if errors.Is(err, context.Canceled) {
return
}
fmt.Fprintf(os.Stderr, "Error tailing log: %v. Retrying in 10 seconds...\n", err)
}
lastRsyncExecutionTimeValid.Set(0)
select {
case <-ctx.Done():
return
case <-time.After(10 * time.Second):
}
}
}()
// Wait for shutdown signal or HTTP error
select {
case sig := <-sigCh:
fmt.Printf("Received signal %v, shutting down...\n", sig)
case err := <-httpErrCh:
fmt.Fprintf(os.Stderr, "HTTP listener error: %v\n", err)
}
cancel()
time.Sleep(100 * time.Millisecond) // Allow goroutines to clean up
fmt.Println("Shutdown complete.")
}