-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
root.go
324 lines (251 loc) · 8.36 KB
/
root.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package commands
import (
"context"
"fmt"
"net"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/valyala/fasthttp"
"golang.org/x/sync/errgroup"
"github.com/authelia/authelia/v4/internal/authentication"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/logging"
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/model"
"github.com/authelia/authelia/v4/internal/server"
"github.com/authelia/authelia/v4/internal/utils"
)
// NewRootCmd returns a new Root Cmd.
func NewRootCmd() (cmd *cobra.Command) {
version := utils.Version()
cmd = &cobra.Command{
Use: "authelia",
Short: fmt.Sprintf(fmtCmdAutheliaShort, version),
Long: fmt.Sprintf(fmtCmdAutheliaLong, version),
Example: cmdAutheliaExample,
Version: version,
Args: cobra.NoArgs,
PreRun: newCmdWithConfigPreRun(true, true, true),
Run: cmdRootRun,
DisableAutoGenTag: true,
}
cmdWithConfigFlags(cmd, false, []string{})
cmd.AddCommand(
newAccessControlCommand(),
newBuildInfoCmd(),
newCryptoCmd(),
newHashPasswordCmd(),
newStorageCmd(),
newValidateConfigCmd(),
)
return cmd
}
func cmdRootRun(_ *cobra.Command, _ []string) {
logger := logging.Logger()
logger.Infof("Authelia %s is starting", utils.Version())
if os.Getenv("ENVIRONMENT") == "dev" {
logger.Info("===> Authelia is running in development mode. <===")
}
if err := logging.InitializeLogger(config.Log, true); err != nil {
logger.Fatalf("Cannot initialize logger: %v", err)
}
providers, warnings, errors := getProviders()
if len(warnings) != 0 {
for _, err := range warnings {
logger.Warn(err)
}
}
if len(errors) != 0 {
for _, err := range errors {
logger.Error(err)
}
logger.Fatalf("Errors occurred provisioning providers.")
}
doStartupChecks(config, &providers, logger)
runServices(config, providers, logger)
}
//nolint:gocyclo // Complexity is required in this function.
func runServices(config *schema.Configuration, providers middlewares.Providers, log *logrus.Logger) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(quit)
g, ctx := errgroup.WithContext(ctx)
var (
mainServer, metricsServer *fasthttp.Server
mainListener, metricsListener net.Listener
)
g.Go(func() (err error) {
defer func() {
if r := recover(); r != nil {
log.WithError(recoverErr(r)).Errorf("Critical error in server caught (recovered)")
}
}()
if mainServer, mainListener, err = server.CreateDefaultServer(*config, providers); err != nil {
return err
}
if err = mainServer.Serve(mainListener); err != nil {
log.WithError(err).Error("Server (main) returned error")
return err
}
return nil
})
g.Go(func() (err error) {
if providers.Metrics == nil {
return nil
}
defer func() {
if r := recover(); r != nil {
log.WithError(recoverErr(r)).Errorf("Critical error in metrics server caught (recovered)")
}
}()
if metricsServer, metricsListener, err = server.CreateMetricsServer(config.Telemetry.Metrics); err != nil {
return err
}
if err = metricsServer.Serve(metricsListener); err != nil {
log.WithError(err).Error("Server (metrics) returned error")
return err
}
return nil
})
if config.AuthenticationBackend.File != nil && config.AuthenticationBackend.File.Watch {
provider := providers.UserProvider.(*authentication.FileUserProvider)
if watcher, err := runServiceFileWatcher(g, log, config.AuthenticationBackend.File.Path, provider); err != nil {
log.WithError(err).Errorf("Error opening file watcher")
} else {
defer watcher.Close()
}
}
select {
case s := <-quit:
switch s {
case syscall.SIGINT:
log.Debugf("Shutdown started due to SIGINT")
case syscall.SIGQUIT:
log.Debugf("Shutdown started due to SIGQUIT")
}
case <-ctx.Done():
log.Debugf("Shutdown started due to context completion")
}
cancel()
log.Infof("Shutting down")
var err error
if mainServer != nil {
if err = mainServer.Shutdown(); err != nil {
log.WithError(err).Errorf("Error occurred shutting down the server")
}
}
if metricsServer != nil {
if err = metricsServer.Shutdown(); err != nil {
log.WithError(err).Errorf("Error occurred shutting down the metrics server")
}
}
if err = providers.StorageProvider.Close(); err != nil {
log.WithError(err).Errorf("Error occurred closing the database connection")
}
if err = g.Wait(); err != nil {
log.WithError(err).Errorf("Error occurred waiting for shutdown")
}
}
type ReloadFilter func(path string) (skipped bool)
type ProviderReload interface {
Reload() (reloaded bool, err error)
}
func runServiceFileWatcher(g *errgroup.Group, log *logrus.Logger, path string, reload ProviderReload) (watcher *fsnotify.Watcher, err error) {
if watcher, err = fsnotify.NewWatcher(); err != nil {
return nil, err
}
failed := make(chan struct{})
var directory, filename string
if path != "" {
directory, filename = filepath.Dir(path), filepath.Base(path)
}
g.Go(func() error {
for {
select {
case <-failed:
return nil
case event, ok := <-watcher.Events:
if !ok {
return nil
}
if filename != filepath.Base(event.Name) {
log.WithField("file", event.Name).WithField("op", event.Op).Tracef("File modification detected to irrelevant file")
break
}
switch {
case event.Op&fsnotify.Write == fsnotify.Write, event.Op&fsnotify.Create == fsnotify.Create:
log.WithField("file", event.Name).WithField("op", event.Op).Debug("File modification detected")
switch reloaded, err := reload.Reload(); {
case err != nil:
log.WithField("file", event.Name).WithField("op", event.Op).WithError(err).Error("Error occurred reloading file")
case reloaded:
log.WithField("file", event.Name).Info("Reloaded file successfully")
default:
log.WithField("file", event.Name).Debug("Reload of file was triggered but it was skipped")
}
case event.Op&fsnotify.Remove == fsnotify.Remove:
log.WithField("file", event.Name).WithField("op", event.Op).Debug("Remove of file was detected")
}
case err, ok := <-watcher.Errors:
if !ok {
return nil
}
log.WithError(err).Errorf("Error while watching files")
}
}
})
if err := watcher.Add(directory); err != nil {
failed <- struct{}{}
return nil, err
}
log.WithField("directory", directory).WithField("file", filename).Debug("Directory is being watched for changes to the file")
return watcher, nil
}
func doStartupChecks(config *schema.Configuration, providers *middlewares.Providers, log *logrus.Logger) {
var (
failures []string
err error
)
if err = doStartupCheck(log, "storage", providers.StorageProvider, false); err != nil {
log.Errorf("Failure running the storage provider startup check: %+v", err)
failures = append(failures, "storage")
}
if err = doStartupCheck(log, "user", providers.UserProvider, false); err != nil {
log.Errorf("Failure running the user provider startup check: %+v", err)
failures = append(failures, "user")
}
if err = doStartupCheck(log, "notification", providers.Notifier, config.Notifier.DisableStartupCheck); err != nil {
log.Errorf("Failure running the notification provider startup check: %+v", err)
failures = append(failures, "notification")
}
if !config.NTP.DisableStartupCheck && !providers.Authorizer.IsSecondFactorEnabled() {
log.Debug("The NTP startup check was skipped due to there being no configured 2FA access control rules")
} else if err = doStartupCheck(log, "ntp", providers.NTP, config.NTP.DisableStartupCheck); err != nil {
log.Errorf("Failure running the ntp provider startup check: %+v", err)
if !config.NTP.DisableFailure {
failures = append(failures, "ntp")
}
}
if len(failures) != 0 {
log.Fatalf("The following providers had fatal failures during startup: %s", strings.Join(failures, ", "))
}
}
func doStartupCheck(logger *logrus.Logger, name string, provider model.StartupCheck, disabled bool) error {
if disabled {
logger.Debugf("%s provider: startup check skipped as it is disabled", name)
return nil
}
if provider == nil {
return fmt.Errorf("unrecognized provider or it is not configured properly")
}
return provider.StartupCheck()
}