-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsetup.go
140 lines (113 loc) · 2.48 KB
/
setup.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
package coredns_omada
import (
"context"
"errors"
"time"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
clog "github.com/coredns/coredns/plugin/pkg/log"
)
var log = clog.NewWithPlugin("omada")
func init() { plugin.Register("omada", setup) }
func setup(c *caddy.Controller) error {
config, err := parse(c)
if err != nil {
return plugin.Error("omada", err)
}
ctx, cancel := context.WithCancel(context.Background())
url := config.Controller_url
u := config.Username
p := config.Password
o, err := NewOmada(ctx, url, u, p)
if err != nil {
cancel()
return plugin.Error("omada", err)
}
o.config = config
if o.config.ignore_startup_errors {
go o.controllerInit(ctx)
} else {
err = o.controllerInit(ctx)
if err != nil {
cancel()
return plugin.Error("omada", err)
}
}
dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
o.Next = next
return o
})
c.OnShutdown(func() error { cancel(); return nil })
return nil
}
func (o *Omada) login() error {
log.Info("logging in...")
u := o.config.Username
p := o.config.Password
err := o.controller.Login(u, p)
if err != nil {
return err
}
return nil
}
func (o *Omada) controllerInit(ctx context.Context) error {
log.Info("starting initial omada setup...")
const retrySeconds = 15
duration := time.Duration(retrySeconds) * time.Second
for {
err := o.controller.GetControllerInfo()
if err != nil {
if o.config.ignore_startup_errors {
log.Warning(err)
time.Sleep(duration)
continue
} else {
return err
}
}
err = o.login()
if err != nil {
if o.config.ignore_startup_errors {
log.Warning(err)
time.Sleep(duration)
continue
} else {
return err
}
}
// setup site list
var sites []string
for s := range o.controller.Sites {
sites = append(sites, s)
}
sites = filterSites(o.config.Site, sites)
if len(sites) == 0 {
if o.config.ignore_startup_errors {
log.Warning(err)
time.Sleep(duration)
continue
} else {
return errors.New("no sites found")
}
}
log.Infof("found '%d' sites: %v", len(sites), sites)
o.sites = sites
// initial zone update
err = o.updateZones()
if err != nil {
if o.config.ignore_startup_errors {
log.Warning(err)
time.Sleep(duration)
continue
} else {
return err
}
}
log.Info("initial omada setup complete")
break
}
go updateSessionLoop(ctx, o)
go updateZoneLoop(ctx, o)
return nil
}