-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
104 lines (86 loc) · 2.55 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
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
nethttp "net/http"
"os"
"os/signal"
"path/filepath"
"sync"
"time"
"github.com/alexruf/fritzmond/collector"
"github.com/alexruf/fritzmond/config"
"github.com/alexruf/fritzmond/fritzbox"
"github.com/alexruf/fritzmond/http"
"github.com/alexruf/fritzmond/ui"
bolt "go.etcd.io/bbolt"
)
var usage bool
var cfg config.Config
func main() {
flag.BoolVar(&usage, "help", false, "Print this help message.")
flag.StringVar(&cfg.Url, "url", "https://fritz.box", "URL of the FRITZ!Box.")
flag.StringVar(&cfg.Username, "username", "", "Username to authenticate with the FRITZ!Box.")
flag.StringVar(&cfg.Password, "password", "", "Password to authenticate with the FRITZ!Box.")
flag.BoolVar(&cfg.SkipTlsVerify, "skipTlsVerify", true, "Skip TLS certificate validation.")
flag.UintVar(&cfg.Interval, "interval", 10, "Interval in seconds at which data should be fetched from the FRITZ!Box.")
flag.StringVar(&cfg.DbPath, "dbpath", "", "Path to the directory where database is stored.")
flag.UintVar(&cfg.Port, "port", 8090, "Listen port for the web UI.")
flag.BoolVar(&cfg.DisableWebUi, "disableWebUi", false, "Disable the web UI.")
flag.Parse()
if usage {
flag.Usage()
return
}
if err := cfg.Validate(); err != nil {
log.Printf("Error in configuration: %s\n", err)
return
}
ctx, cancel := context.WithCancel(context.Background())
wg := &sync.WaitGroup{}
db, err := bolt.Open(filepath.Join(cfg.DbPath, "fritzmond.db"), 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
log.Printf("Error opening database: %s\n", err)
return
}
defer db.Close()
httpClient := http.NewHttpClient(cfg.SkipTlsVerify)
digestAuthClient := http.NewDigestAuthClient(httpClient, cfg.Username, cfg.Password)
fb := fritzbox.New(ctx, digestAuthClient, cfg.Url)
col := collector.New(ctx, cfg, fb, db)
wg.Add(1)
go col.Start(wg)
var srv *nethttp.Server
if !cfg.DisableWebUi {
app := ui.New(db)
app.RegisterRoutes()
wg.Add(1)
srv = startHttpServer(wg)
} else {
log.Println("Web UI disabled")
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
if srv != nil {
_ = srv.Shutdown(ctx)
}
cancel()
wg.Wait()
}
func startHttpServer(wg *sync.WaitGroup) *nethttp.Server {
srv := &nethttp.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
}
go func() {
defer wg.Done()
log.Printf("HTTP Server listening on http://127.0.0.1:%d/\n", cfg.Port)
if err := srv.ListenAndServe(); !errors.Is(err, nethttp.ErrServerClosed) {
log.Fatalf("HTTP server error: %s", err)
}
}()
return srv
}