-
Notifications
You must be signed in to change notification settings - Fork 0
/
internet-monitor.groovy
306 lines (273 loc) · 9.46 KB
/
internet-monitor.groovy
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
/*
* Internet connection monitor
*/
/* groovylint-disable CompileStatic, DuplicateStringLiteral, DuplicateNumberLiteral */
import groovy.transform.Field
import com.hubitat.app.DeviceWrapper
@Field static final String ICMP = 'ICMP'
@Field static final String HTTP = 'HTTP'
@Field static final String BOOL = 'bool'
@Field static final String NUMBER = 'number'
@Field static final String STRING = 'string'
@Field static final String HUBITAT_NAMESPACE = 'hubitat'
@Field static final String PRESENCE_DEVICE = 'Virtual Presence'
@Field static final String PRESENCE = 'presence'
@Field static final String PRESENT_TRUE = 'present'
@Field static final int ERROR_THRESHOLD_DEFAULT = 10000
@Field static final int HTTP_TIMEOUT_DEFAULT = 20
@Field static final float WARN_THRESHOLD = (float) 2 / 3 // groovylint-disable-line NoFloat
@Field static final int HTTP_CHECK_INTERVAL = 500
@Field static final int MAX_TRIES = 3
static final String version() { return '1.0.0' }
definition(
name: 'Internet Connection Monitor',
namespace: 'hugoh',
author: 'Hugo Haas',
description: 'Application monitoring the internet connection via HTTP & ICMP checks',
iconUrl: '',
iconX2Url: '',
category: 'Utility',
importUrl: 'https://github.com/hugoh/hubitat-internet-monitor/blob/master/internet-monitor.groovy',
singleThreaded: true
)
@Field static final List DefaultCheckedUrls = [
'http://www.gstatic.com/generate_204',
'http://www.msftncsi.com/ncsi.txt',
'http://detectportal.firefox.com/'
]
@Field static final List DefaultPingHosts = [
'1.1.1.1',
'8.8.8.8',
'9.9.9.9'
]
preferences {
section('Polling Intervals') {
input('checkInterval', NUMBER, title: 'Polling interval in seconds when Internet is up',
defaultValue: 300, required: true)
input('checkIntervalWhenDown', NUMBER, title: 'Polling interval in seconds when Internet is down',
defaultValue: 60, required: true)
}
section('Checked Endpoints') {
input('checkedUrls', STRING, title: 'URLs to check via HTTP',
description: 'Comma-separated list of URLs',
defaultValue: DefaultCheckedUrls.join(','), required: true)
input('pingHosts', STRING, title: 'Hosts to check via ping',
description: 'Comma-separated list of IP addresses or hostnames',
defaultValue: DefaultPingHosts.join(','), required: true)
}
section('Error Thresholds') {
input('httpThreshold', NUMBER, title: 'Error latency threshold for HTTP checks (in ms)',
defaultValue: ERROR_THRESHOLD_DEFAULT, required: true)
input('pingThreshold', NUMBER, title: 'Error latency threshold for ping checks (in ms)',
defaultValue: ERROR_THRESHOLD_DEFAULT)
}
section('Debugging') {
input('logEnable', BOOL, title: 'Enable debug logging', defaultValue: false)
}
}
/* ------------------------------------------------------------------------------------------------------- */
void installed() {
unsubscribe()
subscribe(location, 'systemStart', systemStart)
initialize()
}
void updated() {
installed()
}
void systemStart(evt) { // groovylint-disable-line NoDef, MethodParameterTypeRequired, UnusedMethodParameter
initialize()
}
void uninstalled() {
for (device in getChildDevices()) { // groovylint-disable-line UnnecessaryGetter
deleteChildDevice(device.deviceNetworkId)
}
}
void initialize() {
log.info("${app.label} version ${version()} initializing")
unschedule()
initializeState()
runIn(1, 'poll')
}
/* ------------------------------------------------------------------------------------------------------- */
void poll() {
try {
checkInternetIsUp()
} finally {
scheduleNextPoll()
}
}
private void scheduleNextPoll() {
nextRun = nextCheckIn()
logDebug("Scheduling next check in ${nextRun} seconds")
runIn(nextRun, 'poll')
}
private int nextCheckIn() {
if (presenceDevice().currentValue(PRESENCE) == PRESENT_TRUE) {
return settings.checkInterval
} else { //groovylint-disable-line UnnecessaryElseStatement
return settings.checkIntervalWhenDown
}
}
private DeviceWrapper presenceDevice() {
presenceSensorId = "internet-monitor:up_presence:${app.id}"
presenceSensorName = "${app.label} Sensor"
return getChildDevice(presenceSensorId) ?:
addChildDevice(HUBITAT_NAMESPACE, PRESENCE_DEVICE, presenceSensorId,
[name: presenceSensorName, isComponent: true])
}
private void initializeState() {
log.info("Initializing state for ${app.name} version ${version()}")
state.clear()
state.targets = [
(HTTP): splitString(settings.checkedUrls, DefaultCheckedUrls),
(ICMP): splitString(settings.pingHosts, DefaultPingHosts)
]
final int initialIndex = -1
state.targetIndex = [
(HTTP): initialIndex,
(ICMP): initialIndex
]
state.errorThresholds = [
(HTTP): positiveValue(settings.httpThreshold),
(ICMP): positiveValue(settings.pingThreshold)
]
state.httpTimeout = state.errorThresholds[HTTP] ? // This is in seconds for httpGet
(int) Math.ceil(state.errorThresholds[HTTP] / 1000) :
HTTP_TIMEOUT_DEFAULT
state.warnThresholds = [:]
for (t in [HTTP, ICMP]) {
state.warnThresholds[t] = (int) Math.floor(state.errorThresholds[t] * WARN_THRESHOLD)
}
assert presenceDevice() != null
}
private void ensureValidState() {
if (state.targets &&
state.targetIndex &&
state.errorThresholds &&
state.httpTimeout) {
return
}
// Something's missing
initializeState()
}
private boolean httpTest(String uri) {
boolean ret
req = [
'uri': uri,
'timeout': state.httpTimeout,
'textParser': true
]
logDebug("Sending HTTP request ${req}")
httpGet(req) { resp ->
ret = resp.isSuccess() //groovylint-disable-line UnnecessaryGetter
}
logDebug("HTTP request ${uri} success: ${ret}")
return ret
}
private boolean pingTest(String host) {
logDebug("Sending ICMP ping to ${host}")
hubitat.helper.NetworkUtils.PingData pingData = hubitat.helper.NetworkUtils.ping(host, 1)
ret = pingData?.packetsReceived
logDebug("Received ICMP ping response from ${host}: ${ret}")
return ret
}
private boolean isTargetReachable(String target, String type) {
logDebug("[${type}] Testing ${target} at most ${MAX_TRIES} times")
boolean reachable = false
for (i = 1; i <= MAX_TRIES; i++) {
boolean reached
start = now()
try {
if (type == HTTP) {
reached = httpTest(target)
} else if (type == ICMP) {
reached = pingTest(target)
} else {
throw new IllegalArgumentException("Unsupported test type ${type}")
}
reachedIn = now() - start
} catch (java.io.IOException ex) {
log.error("Could not reach ${target}: ${ex.message}")
reached = false
}
if (reached) {
if (state.errorThresholds?."$type" > 0) {
final String thresholdMsg = 'Target %s reached but latency exceeded threshold; took %dms'
if (reachedIn > state.errorThresholds."$type") {
log.error(sprintf(thresholdMsg, target, reachedIn))
reached = false
} else if (reachedIn > state.warnThresholds?."$type") {
log.warn(sprintf(thresholdMsg, target, reachedIn))
}
}
}
if (reached) {
reachable = true
break
}
if (type == HTTP) {
logDebug("Retrying in ${HTTP_CHECK_INTERVAL}ms")
pauseExecution(HTTP_CHECK_INTERVAL)
}
}
if (reachable) {
logDebug("[${type}] Reached ${target} in ${reachedIn}ms after ${i} tries")
} else {
log.error("[${type}] Could not reach ${target} after ${MAX_TRIES} tries")
}
logDebug("[${type}] Reached ${target}: ${reachable}")
return reachable
}
private boolean runChecks(String type) {
logDebug("Running ${type} checks")
boolean isUp = false
List targets = state.targets[type]
int s = targets.size()
for (j = 0; j < s; j++) {
String target = targets.get(incTargetIndex(type))
if (isTargetReachable(target, type)) {
isUp = true
break
}
}
logDebug("${type} checks successful: ${isUp}")
return isUp
}
private int incTargetIndex(String type) {
int i = state.targetIndex[type] + 1
i %= state.targets[type].size()
state.targetIndex[type] = i
return i
}
private boolean checkInternetIsUp() {
logDebug('Checking for Internet connectivity')
ensureValidState()
boolean isUp
isUp = runChecks(HTTP) ?: runChecks(ICMP)
reportResults(isUp)
return isUp
}
private void reportResults(boolean isUp) {
if (isUp) {
presenceDevice().arrived()
log.info('Internet is up')
} else {
presenceDevice().departed()
log.error('Internet is down: all tests failed')
}
}
private int positiveValue(Long v) {
return v == null ? 0 : Math.max(v, 0)
}
private List splitString(String commaSeparatedString, List defaultValue) {
if (commaSeparatedString == null) {
log.info("No settings value, using default ${defaultValue}")
return defaultValue
}
return commaSeparatedString.split('[, ]+')
}
private void logDebug(String msg) {
if (logEnable) {
log.debug(msg)
}
}