-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.go
170 lines (140 loc) · 4.43 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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"golang.org/x/oauth2"
"github.com/exzz/netatmo-api-go"
"github.com/xperimental/netatmo-exporter/v2/internal/collector"
"github.com/xperimental/netatmo-exporter/v2/internal/config"
"github.com/xperimental/netatmo-exporter/v2/internal/logger"
"github.com/xperimental/netatmo-exporter/v2/internal/token"
"github.com/xperimental/netatmo-exporter/v2/internal/web"
)
var (
signals = []os.Signal{
syscall.SIGINT,
syscall.SIGTERM,
}
log = logger.NewLogger()
)
func main() {
cfg, err := config.Parse(os.Args, os.Getenv)
switch {
case err == pflag.ErrHelp:
return
case err != nil:
log.Fatalf("Error in configuration: %s", err)
default:
}
log.SetLevel(logrus.Level(cfg.LogLevel))
log.Infof("netatmo-exporter %s (commit: %s)", Version, GitCommit)
client := netatmo.NewClient(cfg.Netatmo, tokenUpdated(cfg.TokenFile))
if cfg.TokenFile != "" {
token, err := loadToken(cfg.TokenFile)
switch {
case os.IsNotExist(err):
case err != nil:
log.Fatalf("Error loading token: %s", err)
case !token.Expiry.IsZero() && token.Expiry.Before(time.Now()):
log.Warn("Restored token has expired! Token has been ignored.")
default:
if token.RefreshToken == "" {
log.Warn("Restored token has no refresh-token! Exporter will need to be re-authenticated manually.")
} else if token.Expiry.IsZero() {
log.Warn("Restored token has no expiry time! Token will be renewed immediately.")
token.Expiry = time.Now().Add(time.Second)
}
log.Infof("Loaded token from %s.", cfg.TokenFile)
client.InitWithToken(context.Background(), token)
}
registerSignalHandler(client, cfg.TokenFile)
} else {
log.Warn("No token-file set! Authentication will be lost on restart.")
}
metrics := collector.New(log, client.Read, cfg.RefreshInterval, cfg.StaleDuration)
prometheus.MustRegister(metrics)
tokenMetric := token.Metric(client.CurrentToken)
prometheus.MustRegister(tokenMetric)
if cfg.DebugHandlers {
http.Handle("/debug/data", web.DebugDataHandler(log, client.Read))
http.Handle("/debug/token", web.DebugTokenHandler(log, client.CurrentToken))
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
http.Handle("/auth/authorize", web.AuthorizeHandler(cfg.ExternalURL, client))
http.Handle("/auth/callback", web.CallbackHandler(ctx, client))
http.Handle("/auth/settoken", web.SetTokenHandler(ctx, client))
http.Handle("/metrics", promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}))
http.Handle("/version", versionHandler(log))
http.Handle("/", web.HomeHandler(client.CurrentToken))
log.Infof("Listen on %s...", cfg.Addr)
log.Fatal(http.ListenAndServe(cfg.Addr, nil))
}
func loadToken(fileName string) (*oauth2.Token, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer file.Close()
var token oauth2.Token
if err := json.NewDecoder(file).Decode(&token); err != nil {
return nil, err
}
return &token, nil
}
func registerSignalHandler(client *netatmo.Client, fileName string) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, signals...)
go func() {
sig := <-ch
signal.Reset(signals...)
log.Debugf("Got signal: %s", sig)
if err := saveToken(client, fileName); err != nil {
log.Errorf("Error persisting token: %s", err)
}
os.Exit(0)
}()
}
func tokenUpdated(fileName string) netatmo.TokenUpdateFunc {
if fileName == "" {
return nil
}
return func(token *oauth2.Token) {
log.Debugf("Token updated. Expires: %s", token.Expiry)
if err := saveTokenFile(fileName, token); err != nil {
log.Errorf("Error saving token: %s", err)
}
}
}
func saveToken(client *netatmo.Client, fileName string) error {
token, err := client.CurrentToken()
switch {
case err == netatmo.ErrNotAuthenticated:
return nil
case err != nil:
return fmt.Errorf("error retrieving token: %w", err)
default:
}
log.Infof("Saving token to %s ...", fileName)
return saveTokenFile(fileName, token)
}
func saveTokenFile(fileName string, token *oauth2.Token) error {
data, err := json.Marshal(token)
if err != nil {
return fmt.Errorf("error marshalling token: %w", err)
}
if err := os.WriteFile(fileName, data, 0o600); err != nil {
return fmt.Errorf("error writing token file: %w", err)
}
return nil
}