forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
neptune_apex.go
294 lines (267 loc) · 7.67 KB
/
neptune_apex.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
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
// Package neptuneapex implements an input plugin for the Neptune Apex
// aquarium controller.
package neptuneapex
import (
"encoding/xml"
"fmt"
"io/ioutil"
"math"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
// Measurement is constant across all metrics.
const Measurement = "neptune_apex"
type xmlReply struct {
SoftwareVersion string `xml:"software,attr"`
HardwareVersion string `xml:"hardware,attr"`
Hostname string `xml:"hostname"`
Serial string `xml:"serial"`
Timezone float64 `xml:"timezone"`
Date string `xml:"date"`
PowerFailed string `xml:"power>failed"`
PowerRestored string `xml:"power>restored"`
Probe []probe `xml:"probes>probe"`
Outlet []outlet `xml:"outlets>outlet"`
}
type probe struct {
Name string `xml:"name"`
Value string `xml:"value"`
Type *string `xml:"type"`
}
type outlet struct {
Name string `xml:"name"`
OutputID string `xml:"outputID"`
State string `xml:"state"`
DeviceID string `xml:"deviceID"`
Xstatus *string `xml:"xstatus"`
}
// NeptuneApex implements telegraf.Input.
type NeptuneApex struct {
Servers []string
ResponseTimeout internal.Duration
httpClient *http.Client
}
// Description implements telegraf.Input.Description
func (*NeptuneApex) Description() string {
return "Neptune Apex data collector"
}
// SampleConfig implements telegraf.Input.SampleConfig
func (*NeptuneApex) SampleConfig() string {
return `
## The Neptune Apex plugin reads the publicly available status.xml data from a local Apex.
## Measurements will be logged under "apex".
## The base URL of the local Apex(es). If you specify more than one server, they will
## be differentiated by the "source" tag.
servers = [
"http://apex.local",
]
## The response_timeout specifies how long to wait for a reply from the Apex.
#response_timeout = "5s"
`
}
// Gather implements telegraf.Input.Gather
func (n *NeptuneApex) Gather(acc telegraf.Accumulator) error {
var wg sync.WaitGroup
for _, server := range n.Servers {
wg.Add(1)
go func(server string) {
defer wg.Done()
acc.AddError(n.gatherServer(acc, server))
}(server)
}
wg.Wait()
return nil
}
func (n *NeptuneApex) gatherServer(
acc telegraf.Accumulator, server string) error {
resp, err := n.sendRequest(server)
if err != nil {
return err
}
return n.parseXML(acc, resp)
}
// parseXML is strict on the input and does not do best-effort parsing.
//This is because of the life-support nature of the Neptune Apex.
func (n *NeptuneApex) parseXML(acc telegraf.Accumulator, data []byte) error {
r := xmlReply{}
err := xml.Unmarshal(data, &r)
if err != nil {
return fmt.Errorf("unable to unmarshal XML: %v\nXML DATA: %q",
err, data)
}
mainFields := map[string]interface{}{
"serial": r.Serial,
}
var reportTime time.Time
if reportTime, err = parseTime(r.Date, r.Timezone); err != nil {
return err
}
if val, err := parseTime(r.PowerFailed, r.Timezone); err == nil {
mainFields["power_failed"] = val.UnixNano()
}
if val, err := parseTime(r.PowerRestored, r.Timezone); err == nil {
mainFields["power_restored"] = val.UnixNano()
}
acc.AddFields(Measurement, mainFields,
map[string]string{
"source": r.Hostname,
"type": "controller",
"software": r.SoftwareVersion,
"hardware": r.HardwareVersion,
},
reportTime)
// Outlets.
for _, o := range r.Outlet {
tags := map[string]string{
"source": r.Hostname,
"output_id": o.OutputID,
"device_id": o.DeviceID,
"name": o.Name,
"type": "output",
"software": r.SoftwareVersion,
"hardware": r.HardwareVersion,
}
fields := map[string]interface{}{
"state": o.State,
}
// Find Amp and Watt probes and add them as fields.
// Remove the redundant probe.
if pos := findProbe(fmt.Sprintf("%sW", o.Name), r.Probe); pos > -1 {
value, err := strconv.ParseFloat(
strings.TrimSpace(r.Probe[pos].Value), 64)
if err != nil {
acc.AddError(
fmt.Errorf(
"cannot convert string value %q to float64: %v",
r.Probe[pos].Value, err))
continue // Skip the whole outlet.
}
fields["watt"] = value
r.Probe[pos] = r.Probe[len(r.Probe)-1]
r.Probe = r.Probe[:len(r.Probe)-1]
}
if pos := findProbe(fmt.Sprintf("%sA", o.Name), r.Probe); pos > -1 {
value, err := strconv.ParseFloat(
strings.TrimSpace(r.Probe[pos].Value), 64)
if err != nil {
acc.AddError(
fmt.Errorf(
"cannot convert string value %q to float64: %v",
r.Probe[pos].Value, err))
break // // Skip the whole outlet.
}
fields["amp"] = value
r.Probe[pos] = r.Probe[len(r.Probe)-1]
r.Probe = r.Probe[:len(r.Probe)-1]
}
if o.Xstatus != nil {
fields["xstatus"] = *o.Xstatus
}
// Try to determine outlet type. Focus on accuracy, leaving the
//outlet_type "unknown" when ambiguous. 24v and vortech cannot be
// determined.
switch {
case strings.HasPrefix(o.DeviceID, "base_Var"):
tags["output_type"] = "variable"
case o.DeviceID == "base_Alarm":
fallthrough
case o.DeviceID == "base_Warn":
fallthrough
case strings.HasPrefix(o.DeviceID, "base_email"):
tags["output_type"] = "alert"
case fields["watt"] != nil || fields["amp"] != nil:
tags["output_type"] = "outlet"
case strings.HasPrefix(o.DeviceID, "Cntl_"):
tags["output_type"] = "virtual"
default:
tags["output_type"] = "unknown"
}
acc.AddFields(Measurement, fields, tags, reportTime)
}
// Probes.
for _, p := range r.Probe {
value, err := strconv.ParseFloat(strings.TrimSpace(p.Value), 64)
if err != nil {
acc.AddError(fmt.Errorf(
"cannot convert string value %q to float64: %v",
p.Value, err))
continue
}
fields := map[string]interface{}{
"value": value,
}
tags := map[string]string{
"source": r.Hostname,
"type": "probe",
"name": p.Name,
"software": r.SoftwareVersion,
"hardware": r.HardwareVersion,
}
if p.Type != nil {
tags["probe_type"] = *p.Type
}
acc.AddFields(Measurement, fields, tags, reportTime)
}
return nil
}
func findProbe(probe string, probes []probe) int {
for i, p := range probes {
if p.Name == probe {
return i
}
}
return -1
}
// parseTime takes a Neptune Apex date/time string with a timezone and
// returns a time.Time struct.
func parseTime(val string, tz float64) (time.Time, error) {
// Magic time constant from https://golang.org/pkg/time/#Parse
const TimeLayout = "01/02/2006 15:04:05 -0700"
// Timezone offset needs to be explicit
sign := '+'
if tz < 0 {
sign = '-'
}
// Build a time string with the timezone in a format Go can parse.
tzs := fmt.Sprintf("%c%04d", sign, int(math.Abs(tz))*100)
ts := fmt.Sprintf("%s %s", val, tzs)
t, err := time.Parse(TimeLayout, ts)
if err != nil {
return time.Now(), fmt.Errorf("unable to parse %q (%v)", ts, err)
}
return t, nil
}
func (n *NeptuneApex) sendRequest(server string) ([]byte, error) {
url := fmt.Sprintf("%s/cgi-bin/status.xml", server)
resp, err := n.httpClient.Get(url)
if err != nil {
return nil, fmt.Errorf("http GET failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
"response from server URL %q returned %d (%s), expected %d (%s)",
url, resp.StatusCode, http.StatusText(resp.StatusCode),
http.StatusOK, http.StatusText(http.StatusOK))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("unable to read output from %q: %v", url, err)
}
return body, nil
}
func init() {
inputs.Add("neptune_apex", func() telegraf.Input {
return &NeptuneApex{
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
}
})
}