-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
250 lines (217 loc) · 6.91 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package main
import (
"html/template"
"net/http"
"os"
"path/filepath"
"io/ioutil"
"time"
"encoding/pem"
"crypto/x509"
log "github.com/sirupsen/logrus"
"github.com/jessevdk/go-flags"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/yaml.v2"
"github.com/foogod/go-powerwall"
)
const (
exporterName = "powerwall"
exporterVersion = "0.2.0"
projectURL = "https://github.com/foogod/powerwall_exporter"
defaultListenAddress = ":9871"
defaultMetricsPath = "/metrics"
defaultLoginEmail = "[email protected]"
defaultRetryInterval = "1s"
defaultRetryTimeout = "0s" // Retries disabled by default
)
var options struct {
Debug bool `long:"debug" description:"Enable debug messages"`
LogStyle string `long:"log.style" description:"Style of log output to produce" choice:"text" choice:"logfmt" choice:"json" default:"text"`
ConfigFile string `long:"config.file" description:"Path to config file"`
FetchCert bool `long:"fetchcert" description:"Retrieve TLS cert and store it in cert file"`
}
func setOptionDefaults() {
options.ConfigFile = os.Args[0] + ".yaml"
}
func main() {
setOptionDefaults()
_, err := flags.Parse(&options)
if err != nil {
os.Exit(1)
}
switch options.LogStyle {
case "text":
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
DisableLevelTruncation: true,
PadLevelText: true,
})
case "logfmt":
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
case "json":
log.SetFormatter(&log.JSONFormatter{})
}
if options.Debug {
log.SetLevel(log.DebugLevel)
}
powerwall.SetLogFunc(pwclientLog)
log.WithFields(log.Fields{"version": exporterVersion}).Infof("Starting %s exporter", exporterName)
loadConfig(options.ConfigFile)
if options.FetchCert {
fetchTLSCert()
} else {
if config.Device.TLSCertFile != "" {
loadTLSCert(config.Device.TLSCertFile)
}
startServer()
}
}
func pwclientLog(v ...interface{}) {
log.Debug(v...)
}
type Config struct {
Web WebConfig
Device DeviceConfig
}
type WebConfig struct {
ListenAddress string `yaml:"listen_address"`
MetricsPath string `yaml:"metrics_path"`
}
type DeviceConfig struct {
GatewayAddress string `yaml:"gateway_address"`
LoginEmail string `yaml:"login_email"`
LoginPassword string `yaml:"login_password"`
RetryInterval time.Duration `yaml:"retry_interval"`
RetryTimeout time.Duration `yaml:"retry_timeout"`
TLSCertFile string `yaml:"tls_cert_file"`
cert *x509.Certificate
}
var config Config
func loadConfig(filename string) {
absPath, err := filepath.Abs(filename)
if err != nil {
absPath = filename
}
log.WithFields(log.Fields{"file": absPath}).Info("Loading config")
yamlFile, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("Unable to read config file: %s", err)
}
// Set defaults
retryInterval, _ := time.ParseDuration(defaultRetryInterval)
retryTimeout, _ := time.ParseDuration(defaultRetryTimeout)
config.Web = WebConfig{
ListenAddress: defaultListenAddress,
MetricsPath: defaultMetricsPath,
}
config.Device = DeviceConfig{
LoginEmail: defaultLoginEmail,
RetryInterval: retryInterval,
RetryTimeout: retryTimeout,
}
err = yaml.UnmarshalStrict(yamlFile, &config)
if err != nil {
log.Fatalf("Unable to parse config file: %s", err)
}
// Check required fields
if config.Device.GatewayAddress == "" {
log.Fatal("Required parameter device.gateway_address not specified in config file")
}
if config.Device.LoginPassword == "" {
log.Fatal("Required parameter device.login_password not specified in config file")
}
}
func loadTLSCert(filename string) {
pemCert, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("Unable to read TLS cert file: %s", err)
}
block, _ := pem.Decode(pemCert)
if block == nil || block.Type != "CERTIFICATE" {
log.Fatalf("Contents of TLS cert file do not appear to be a PEM-encoded certificate")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
log.Fatalf("Error parsing cert file: %s", err)
}
config.Device.cert = cert
absPath, err := filepath.Abs(filename)
if err != nil {
absPath = filename
}
log.WithFields(log.Fields{"file": absPath, "subject": cert.Subject}).Debug("Loaded TLS certificate")
}
func fetchTLSCert() {
if config.Device.TLSCertFile == "" {
log.Fatalf("device.tls_cert_file not specified in config file")
}
pwclient := powerwall.NewClient(config.Device.GatewayAddress, config.Device.LoginEmail, config.Device.LoginPassword)
cert, err := pwclient.FetchTLSCert()
if err != nil {
log.Fatalf("Unable to fetch TLS certificate: %s", err)
}
pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
err = ioutil.WriteFile(config.Device.TLSCertFile, pemCert, 0644)
if err != nil {
log.Fatalf("Unable to write to cert file: %s", err)
}
log.Infof("TLS certificate retrieved and written to %s", config.Device.TLSCertFile)
}
func startServer() {
http.HandleFunc("/", indexPageHandler)
pwclient := powerwall.NewClient(config.Device.GatewayAddress, config.Device.LoginEmail, config.Device.LoginPassword)
pwclient.SetRetry(config.Device.RetryInterval, config.Device.RetryTimeout)
if config.Device.cert != nil {
pwclient.SetTLSCert(config.Device.cert)
}
reg := prometheus.NewRegistry()
reg.MustRegister(NewPowerwallCollector(pwclient))
regLogger := log.New()
regLogger.Level = log.ErrorLevel
regHandler := promhttp.HandlerFor(reg, promhttp.HandlerOpts{
ErrorLog: regLogger,
ErrorHandling: promhttp.ContinueOnError,
})
http.Handle(config.Web.MetricsPath, regHandler)
log.WithFields(log.Fields{"listen_address": config.Web.ListenAddress, "metrics_path": config.Web.MetricsPath}).Info("Listening for HTTP connections")
log.Fatal(http.ListenAndServe(config.Web.ListenAddress, nil))
}
func indexPageHandler(w http.ResponseWriter, r *http.Request) {
templateValues := struct{
Exporter string
Version string
MetricsPath string
ProjectURL string
}{exporterName, exporterVersion, config.Web.MetricsPath, projectURL}
// Ordinarily we should probably parse the template once ahead of time and
// reuse it, but people aren't likely to be calling this page over and over
// again normally, so this is fine for this case.
t, err := template.New("indexHTML").Parse(indexHTML)
if err != nil {
log.Errorf("Error parsing template for index HTML (/): %s", err)
http.Error(w, "Internal server error", 500)
return
}
err = t.Execute(w, templateValues)
if err != nil {
log.Errorf("Error executing template for index HTML (/): %s", err)
}
}
const indexHTML = `<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ .Exporter }} exporter</title>
</head>
<body>
<h1>{{ .Exporter }} exporter for Prometheus (Version {{ .Version }})</h1>
<p>Exported metrics are available at <a href="{{ .MetricsPath }}">{{ .MetricsPath }}</a></p>
<h2>More information:</h2>
<p><a href="{{ .ProjectURL }}">{{ .ProjectURL }}</a></p>
</body>
</html>
`