-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcaddyconsul.go
218 lines (174 loc) · 6.08 KB
/
caddyconsul.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
package caddyconsul
import (
"encoding/json"
"sync"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/hashicorp/consul/api"
"github.com/pkg/errors"
_ "github.com/greenpau/caddy-auth-jwt"
_ "github.com/greenpau/caddy-auth-portal"
_ "github.com/lolPants/caddy-requestid"
)
func init() {
caddy.RegisterModule(App{})
httpcaddyfile.RegisterGlobalOption("consul", getAppFromParseCaddyfile)
}
// This variables are global to allow informations passing between two instances
// of the plugin new configuration reloads (which triggers a Stop()/Cleanup()
// of the previous instance of the plugin and Start()/Provision() a new one).
var (
// lastIndexes is a sync.Map of the last requested Consul indexes
lastIndexes sync.Map
// globalConfig stores the config recovered from the Consul K/V store
globalConfig *caddy.Config
// globalServices stores the services to reverse-proxy
globalServices map[string][]*api.ServiceEntry
// globalInitDone states if it is safe to generate the config because
// both the config and the services have been fetch once
globalInitDone bool
)
// App is the main Consul plugin struct
type App struct {
// ConsulGlobalConfigKey is the Consul config K/V store key
ConsulGlobalConfigKey string `json:"consul_global_config_key"`
// Server describes the information to reach the Consul server
Server *ConsulServer `json:"consul_server"`
// AutoReverseProxy describes the auto reverse-proxying configuration from Consul services
AutoReverseProxy *AutoReverseProxyOptions `json:"auto_reverse_proxy"`
client *api.Client
globalConfig *caddy.Config
services map[string][]*api.ServiceEntry
fullConfigJSON []byte
shutdownChan chan bool
}
// NewApp instantiates a new App{} struct
func NewApp() (app *App) {
app = &App{
Server: &ConsulServer{},
AutoReverseProxy: &AutoReverseProxyOptions{
DefaultHTTPServerOptions: &DefaultHTTPServerOptions{},
TLSIssuers: []json.RawMessage{},
AuthenticationConfiguration: &AuthenticationConfiguration{},
},
}
return
}
// CaddyModule returns the Caddy module information.
func (App) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "consul",
New: func() caddy.Module { return NewApp() },
}
}
// Provision sets up the module.
func (cc *App) Provision(ctx caddy.Context) (err error) {
caddy.Log().Named("consul").Info("Provisioning app")
// Initialize Consul client
cc.client, err = api.NewClient(&api.Config{
Address: cc.Server.Address,
Scheme: cc.Server.Scheme,
Datacenter: cc.Server.Datacenter,
Namespace: cc.Server.Namespace,
Token: cc.Server.Token,
TokenFile: cc.Server.TokenFile,
HttpAuth: &api.HttpBasicAuth{
Username: cc.Server.Username,
Password: cc.Server.Password,
},
})
if err != nil {
err = errors.Wrap(err, "unable to initiate Consul client")
return
}
// Init the global services map.
// This map is shared accross all plugin's instances
if globalServices == nil {
globalServices = make(map[string][]*api.ServiceEntry)
}
caddy.Log().Named("consul").Info("App is provisioned")
return nil
}
// Start starts the module.
func (cc *App) Start() error {
caddy.Log().Named("consul").Info("Starting app")
// We start listening for shutdown events
cc.shutdownChan = make(chan bool)
// We init our Consul watcher
go cc.watchConsul()
return nil
}
// Stop stops the module.
func (cc *App) Stop() error {
return nil
}
// Cleanup cleanups the module.
func (cc *App) Cleanup() error {
caddy.Log().Named("consul").Info("Cleaning up app")
if cc.shutdownChan != nil {
cc.shutdownChan <- true
}
caddy.Log().Named("consul").Info("App was cleaned!")
return nil
}
// Validate validates that the module has a usable config.
func (cc *App) Validate() error {
caddy.Log().Named("consul").Info("Validating app")
if cc.ConsulGlobalConfigKey == "" {
return logAndReturn(ErrMissingConsulKVKey)
}
if cc.Server.Address == "" {
return logAndReturn(ErrConsulServerAddressMissing)
}
if cc.Server.Scheme == "" {
return logAndReturn(ErrConsulServerSchemeMissing)
}
// If ServicesTag is not empty, we will generate the http configuration,
// so we need to have some information
if cc.AutoReverseProxy.ServicesTag != "" {
if cc.AutoReverseProxy.DefaultHTTPServerOptions.HTTPPort == 0 {
return logAndReturn(ErrMissingDefaultHTTPServerOptionsHTTPPort)
}
if cc.AutoReverseProxy.DefaultHTTPServerOptions.HTTPSPort == 0 {
return logAndReturn(ErrMissingDefaultHTTPServerOptionsHTTPSPort)
}
if cc.AutoReverseProxy.DefaultHTTPServerOptions.Zone == "" {
return logAndReturn(ErrMissingDefaultHTTPServerOptionsZone)
}
}
// If module caddy-auth-portal is enabled, some options are required
if cc.AutoReverseProxy.AuthenticationConfiguration.Enabled {
// If we handle authentication, we need to have an authentication domain
if cc.AutoReverseProxy.AuthenticationConfiguration.AuthenticationDomain == "" {
return logAndReturn(ErrMissingAuthenticationConfigurationAuthenticationDomain)
}
// If we handle authentication, we need to have some backend configs
if len(cc.AutoReverseProxy.AuthenticationConfiguration.AuthPortalConfiguration.BackendConfigs) == 0 {
return logAndReturn(ErrMissingAuthenticationConfigurationAuthPortalConfigurationBackendConfigs)
}
// If we handle authentication, we need to have a domain for the cookie
if cc.AutoReverseProxy.AuthenticationConfiguration.AuthPortalConfiguration.CookieConfig.Domain == "" {
return logAndReturn(ErrMissingAuthenticationConfigurationAuthPortalConfigurationCookieConfigDomain)
}
}
caddy.Log().Named("consul").Info("App validated")
return nil
}
// UnmarshalCaddyfile unmarshal plugin's caddyfile.
func (cc *App) UnmarshalCaddyfile(d *caddyfile.Dispenser) (err error) {
app, err := parseCaddyfile(d, nil)
if err != nil {
return
}
cc = app
return
}
// Interface guards
var (
_ caddy.App = (*App)(nil)
_ caddy.Provisioner = (*App)(nil)
_ caddy.Validator = (*App)(nil)
_ caddy.CleanerUpper = (*App)(nil)
_ caddyfile.Unmarshaler = (*App)(nil)
)