-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
234 lines (206 loc) · 7.29 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
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
package main
import (
"fmt"
"github.com/SourceForgery/duc2mqtt/hassio"
"github.com/go-ping/ping"
"github.com/jessevdk/go-flags"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"net/url"
"os"
"os/exec"
"runtime/debug"
"strings"
"time"
)
var opts struct {
Verbose []bool `long:"verbose" short:"v" description:"Verbosity. Repeat for increasing"`
Quiet []bool `long:"quiet" short:"q" description:"Make less verbose. Repeat for even less"`
Version bool `long:"version" short:"V" description:"Display version"`
LoggingFormat string `short:"l" long:"logging" choice:"coloured" choice:"plain" choice:"json" choice:"default" default:"default" description:"Log output format"`
Interval int `long:"interval" env:"INTERVAL" description:"Interval in milliseconds" default:"3000"`
MaxFailures int `long:"max-failures" env:"MAX_FAILURES" description:"Maximum number of consecutive failures before running the command" default:"5"`
IP string `long:"host" env:"IP" description:"Host name to ping (IP address recommended)" default:"1.1.1.1"`
Timeout int `long:"timeout" env:"TIMEOUT" description:"Timeout in milliseconds" default:"1000"`
Unprivileged bool `long:"unprivileged" env:"UNPRIVILEGED" description:"Run ping in unprivileged mode (see https://github.com/go-ping/ping) "`
Cooldown int `long:"cooldown" env:"COOLDOWN" description:"Cooldown in milliseconds after running the command before pinging again" default:"300000"`
MqttUri string `long:"mqtt-uri" env:"MQTT_URI" description:"The URI to the mqtt server. If using virtual-host extension (rabbitmq), it would be tcp://test.mosquitto.org:1883/vhost"`
MqttUniqueId string `long:"mqtt-unique-id" env:"MQTT_UNIQUE_ID" description:"The unique id of this device" default:"network-monitor"`
MqttName string `long:"mqtt-name" env:"MQTT_NAME" description:"The name of this device" default:"network-monitor"`
MqttTopicPrefix string `long:"mqtt-topic-prefix" env:"MQTT_TOPIC_PREFIX" description:"The mqtt prefix to use" default:"homeassistant"`
Command struct {
Args []string `required:"1"`
} `positional-args:"yes"`
}
var version = "unknown"
var hassioClient *hassio.Client
var problem *bool
var hassioSensor = hassio.NewAlarmSensorConfig("internet", "uptime")
func main() {
parser := flags.NewParser(&opts, flags.Default)
_, err := parser.Parse()
if err != nil {
if flags.WroteHelp(err) {
os.Exit(1)
}
log.Logger.Fatal().Err(err).Msg("Failed to parse command line arguments")
}
initializeLogging()
buildInfo, ok := debug.ReadBuildInfo()
if !ok {
log.Fatal().Msg("Failed to read build info")
}
var vcsVersion = "unknown"
for _, setting := range buildInfo.Settings {
if setting.Key == "vcs.revision" {
vcsVersion = setting.Value
}
}
if opts.Version {
log.Info().
Str("vcsVersion", vcsVersion).
Str("goVersion", buildInfo.GoVersion).
Str("version", version).
Msgf("network-monitor version %s compiled with %s, commitId: %s", version, buildInfo.GoVersion, vcsVersion)
os.Exit(1)
}
pinger, err := ping.NewPinger(opts.IP)
if err != nil {
log.Logger.Fatal().Err(err).Msgf("Failed to create pinger for %s", opts.IP)
}
pinger.SetPrivileged(!opts.Unprivileged)
if opts.MqttUri != "" {
setupMqtt()
}
acceptedDiff := 0
pinger.OnRecv = func(packet *ping.Packet) {
log.Debug().Msgf("Successfully pinged %s", opts.IP)
setStatus(true)
statistics := pinger.Statistics()
acceptedDiff = statistics.PacketsSent - statistics.PacketsRecv
}
go func() {
err := pinger.Run()
if err != nil {
log.Logger.Error().Err(err).Msgf("Failed to ping %s", pinger.Addr())
}
}()
defer pinger.Stop()
for {
time.Sleep(time.Duration(opts.Timeout) * time.Millisecond)
stats := pinger.Statistics()
if acceptedDiff+stats.PacketsRecv+opts.MaxFailures < stats.PacketsSent {
log.Error().Msgf("Ping to %s failed %d times consecutively. Running command: %s", opts.IP, opts.MaxFailures, strings.Join(opts.Command.Args, " "))
setStatus(false)
runCommand(opts.Command.Args)
time.Sleep(time.Duration(opts.Cooldown) * time.Millisecond)
}
log.Debug().Msgf("Sent %d packets and received %d packets and accepted diff: %d", stats.PacketsSent, stats.PacketsRecv, acceptedDiff)
}
}
func setupMqtt() {
mqttUrl, err := url.Parse(opts.MqttUri)
if err != nil {
log.Fatal().Err(err).Msgf("Failed to parse mqtt url")
}
amqpVhost := strings.TrimPrefix(mqttUrl.Path, "/")
hassioClient, err = hassio.ConnectMqtt(*mqttUrl, amqpVhost, opts.MqttUniqueId, opts.MqttTopicPrefix)
buildInfo, ok := debug.ReadBuildInfo()
if !ok {
log.Fatal().Msg("Failed to read build info")
}
hassioClient.Device = &hassio.Device{
Identifiers: []string{opts.MqttUniqueId},
Name: opts.MqttName,
SWVersion: buildInfo.Main.Version,
HWVersion: "N/A",
SerialNumber: "N/A",
Model: "NetworkMonitor",
ModelID: "NetworkMonitor",
Manufacturer: "SourceForgery",
ConfigurationURL: fmt.Sprintf("http://localhost/"),
}
hassioClient.SensorConfigurationData = map[string]hassio.SensorConfig{
"internet": hassioSensor,
}
err = hassioClient.SubscribeToHomeAssistantStatus()
if err != nil {
log.Fatal().Err(err).Msg("Failed to subscribe to Home Assistant status")
}
}
func pingIP(pinger *ping.Pinger) error {
oldPacketsRecv := pinger.PacketsRecv
err := pinger.Run()
if err != nil {
log.Logger.Error().Err(err).Msgf("Failed to ping %s", pinger.Addr())
}
time.Sleep(1 * time.Second)
if pinger.PacketsRecv <= oldPacketsRecv {
log.Warn().Msgf("Expected %d to be more than %d", pinger.PacketsRecv, oldPacketsRecv)
return fmt.Errorf("no packets received")
}
return nil
}
func runCommand(cmd []string) {
out, err := exec.Command(cmd[0], cmd[1:]...).Output()
if err != nil {
log.Error().Err(err).Msgf("Failed to run command: %s", cmd)
}
log.Info().Msgf("Command output: %s", out)
}
func terminalOutput() bool {
o, _ := os.Stdout.Stat()
return (o.Mode() & os.ModeCharDevice) == os.ModeCharDevice
}
func setStatus(newStatus bool) {
if problem != nil && newStatus == *problem {
return
}
problem = &newStatus
if hassioClient != nil {
value := 1.0
if newStatus {
value = 0
}
err := hassioClient.SendSensorData(hassioSensor.SensorType(), map[string]string{
hassioSensor.SensorId(): hassioSensor.ConvertValue(value),
})
if err != nil {
log.Error().Err(err).Msg("Failed to send data")
}
}
}
func initializeLogging() {
log.Logger = getLogger(opts.LoggingFormat).
With().Timestamp().
Logger()
setLogLevel(len(opts.Quiet) - len(opts.Verbose) + 1)
}
func getLogger(loggingFormat string) (lg zerolog.Logger) {
switch loggingFormat {
case "default":
if terminalOutput() {
return getLogger("coloured")
} else {
return getLogger("plain")
}
case "json":
return zerolog.New(os.Stdout)
case "coloured":
return zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339})
case "plain":
return zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339, NoColor: true})
default:
log.Panic().Msgf("What the f is %s", loggingFormat)
}
return lg
}
func setLogLevel(verbosity int) {
if verbosity < 0 {
zerolog.SetGlobalLevel(zerolog.TraceLevel)
} else if verbosity > 6 {
zerolog.SetGlobalLevel(zerolog.Disabled)
} else {
zerolog.SetGlobalLevel(zerolog.Level(verbosity))
}
}