summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/openvpn_status_log/collect.go
blob: f6a442fd53c30ce7926f709254f50bd7e5dc604c (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
// SPDX-License-Identifier: GPL-3.0-or-later

package openvpn_status_log

import (
	"time"
)

func (o *OpenVPNStatusLog) collect() (map[string]int64, error) {
	clients, err := parse(o.LogPath)
	if err != nil {
		return nil, err
	}

	mx := make(map[string]int64)

	collectTotalStats(mx, clients)

	if o.perUserMatcher != nil && numOfClients(clients) > 0 {
		o.collectUsers(mx, clients)
	}

	return mx, nil
}

func collectTotalStats(mx map[string]int64, clients []clientInfo) {
	var in, out int64
	for _, c := range clients {
		in += c.bytesReceived
		out += c.bytesSent
	}
	mx["clients"] = numOfClients(clients)
	mx["bytes_in"] = in
	mx["bytes_out"] = out
}

func (o *OpenVPNStatusLog) collectUsers(mx map[string]int64, clients []clientInfo) {
	now := time.Now().Unix()

	for _, user := range clients {
		name := user.commonName
		if !o.perUserMatcher.MatchString(name) {
			continue
		}
		if !o.collectedUsers[name] {
			o.collectedUsers[name] = true
			if err := o.addUserCharts(name); err != nil {
				o.Warning(err)
			}
		}
		mx[name+"_bytes_in"] = user.bytesReceived
		mx[name+"_bytes_out"] = user.bytesSent
		mx[name+"_connection_time"] = now - user.connectedSince
	}
}

func numOfClients(clients []clientInfo) int64 {
	var num int64
	for _, v := range clients {
		if v.commonName != "" && v.commonName != "UNDEF" {
			num++
		}
	}
	return num
}