/
main.go
128 lines (98 loc) · 2.39 KB
/
main.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
package main
import (
"fmt"
"log"
"net/url"
"os"
"time"
"github.com/coreos/go-systemd/dbus"
client "github.com/influxdata/influxdb1-client"
)
func main() {
conn, err := dbus.New()
var influxClient *client.Client = initInflux()
// Ensuring that the connection is closed at some point.
defer conn.Close()
if err != nil {
fmt.Println("Could not create a new connection object.")
return
}
// Subscribing to systemd dbus events.
err = conn.Subscribe()
if err != nil {
fmt.Println("Could not subscribe to the bus.")
return
}
updateCh := make(chan *dbus.PropertiesUpdate, 256)
errCh := make(chan error, 256)
// Properties (signals here) changes will be saved to those objects.
conn.SetPropertiesSubscriber(updateCh, errCh)
for {
select {
case update := <-updateCh:
var points []client.Point = getPoint(update)
influxClient.Write(client.BatchPoints{
Points: points,
Database: "systemd",
RetentionPolicy: "autogen",
Precision: "ms",
WriteConsistency: "any",
})
case err := <-errCh:
fmt.Println(err)
}
}
}
func getPoint(properties *dbus.PropertiesUpdate) []client.Point {
activeState := properties.Changed["ActiveState"].String()
var point client.Point = client.Point{
Measurement: "services",
Tags: map[string]string{
"service": properties.UnitName,
},
Fields: map[string]interface{}{
"state": activeState,
"value": getStateValue(activeState),
},
// Need to use the timestamp provided by dbus..
Time: time.Now(),
Precision: "ms",
}
points := [1]client.Point{point}
return points[0:1]
}
func initInflux() *client.Client {
host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
if err != nil {
log.Fatal(err)
}
conf := client.Config{
URL: *host,
Username: os.Getenv("admin"),
Password: os.Getenv("admin"),
}
influxConnection, err := client.NewClient(conf)
if err != nil {
fmt.Println("Error building a new client for InfluxDB.")
}
return influxConnection
}
// active (1), reloading, inactive (0), failed (-1), activating, deactivating
func getStateValue(state string) int {
switch state {
case "\"failed\"":
return -1
case "\"inactive\"":
return 0
case "\"active\"":
return 1
case "\"reloading\"":
return 2
case "\"activating\"":
return 4
case "\"deactivating\"":
return 5
default:
panic("Unhandled dbus active state value")
}
}