-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
281 lines (264 loc) · 8.46 KB
/
server.go
File metadata and controls
281 lines (264 loc) · 8.46 KB
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
package main
/*
Package main is the entry point for the Defacto2 server application.
Use the Task runner / build tool (https://taskfile.dev) to build or run the source code.
$ task --list
Repository: https://github.com/Defacto2/server
Website: https://defacto2.net
License: GPL-3.0
© Defacto2, 2024-26
*/
import (
"context"
"database/sql"
"embed"
"errors"
"fmt"
"io"
"log"
"log/slog"
"os"
"runtime"
"slices"
"strings"
"github.com/Defacto2/helper"
"github.com/Defacto2/server/flags"
"github.com/Defacto2/server/handler"
"github.com/Defacto2/server/internal/config"
"github.com/Defacto2/server/internal/logs"
"github.com/Defacto2/server/internal/postgres"
"github.com/caarlos0/env/v11"
_ "github.com/jackc/pgx/v5"
)
var (
//go:embed public/text/defacto2.txt
brand []byte
//go:embed public/**/*
public embed.FS
//go:embed view/**/*
view embed.FS
version string // version is generated by the GoReleaser ldflags.
)
var ErrLog = errors.New("cannot save one or more log files")
// Main is the entry point for the application.
// By default, the web server can run without any
// flags or configuration. Otherwise, providing
// command arguments will be parsed and then the
// application exits.
func main() {
const msg = "defacto2 startup"
const exit = 0
// Initialize a temporary logger, and get then print
// the environment variable configurations.
tl := logs.Default()
slog.SetDefault(tl)
configs := environmentVars(tl)
// Parse any application commands and flags, and
// if appropriate run the request and exit to
// the terminal.
if code := flagParser(os.Stdout, tl, *configs); code >= exit {
os.Exit(int(code))
}
// Configure the sl application logger, the cl startup
// configuration logger and the logo writer.
// Two separate loggers are used to avoid the system and file logs
// being cluttered with server startup information.
const nothing = "" // replace the dname nothing argument with logs.NameDebug, to write debug log reports
lf, err := logs.OpenFiles(string(configs.AbsLog), logs.NameErr, logs.NameInfo, nothing)
if err != nil { //nolint:nestif
log.Println(fmt.Errorf("%w: %w", ErrLog, err))
} else {
if prod := configs.ProdMode.Bool(); prod {
defer func() {
err := lf.Close()
if err != nil {
log.Println(err)
}
}()
} else {
// We only use the log files in production mode. However
// it is good to create, open and close the files in development
// mode to confirm the functionality of the loggers.
_ = lf.Close()
lf = logs.NoFiles()
}
}
sl, cl, logo := setupWriters(*configs, lf)
configs.Print(cl)
// Connect to the database and perform some record repairs
// and sanity checks. Even if the database cannot connect
// the web server will continue to run with limited functionality.
db, err := postgres.Open()
if err != nil {
sl.Error(msg, slog.String("database", "could not initialize the database"),
slog.Any("error", err))
}
defer func() {
err := db.Close()
if err != nil {
sl.Warn("database",
slog.String("issue", "closing the database connection caused an error"),
slog.Any("error", err))
}
}()
var database postgres.Version
if err := database.Query(db); err != nil {
sl.Error(msg, slog.String("postgres", "could not run the version query"),
slog.Any("error", err))
}
// Cleanup any previous temporary directories created by this application.
config.TmpCleaner(sl)
config.TmpInfo(sl)
// Start the web server.
instance := newInstance(context.Background(), db, *configs)
newline(logo)
welcomeMsg(sl, instance.RecordCount)
routing := instance.Controller(db, sl)
instance.StartupBranding(sl, logo)
if err := instance.Start(routing, sl, *configs); err != nil {
logs.Fatal(sl, msg,
slog.String("environment vars", "could not startup the server, please check the configuration"))
}
go func() {
groupUsers(cl, msg)
locAddresses(cl, configs, msg)
}()
// Shutdown the web server after a signal is received.
instance.ShutdownHTTP(os.Stderr, routing, sl)
}
func setupWriters(configs config.Config, lf logs.Files) (*slog.Logger, *slog.Logger, io.Writer) {
// configure logo to stdout so it is ignored by systemd and the operating system
var logo io.Writer = os.Stdout
// configuration logger flags
cflag := logs.Configurations
clvl := logs.LevelInfo
// general slog and level configuration used by the website
sflag := logs.Defaults
slvl := logs.LevelInfo
if quiet := bool(configs.Quiet); quiet {
logo = io.Discard
clvl, slvl = logs.LevelError, logs.LevelError
sflag = logs.Quiets
}
// configure the server logger and make it the default
sl := lf.New(slvl, sflag)
slog.SetDefault(sl)
// print the server configuration and commandline flag output to stdout
cf := logs.NoFiles()
cl := cf.New(clvl, cflag)
return sl, cl, logo
}
func newline(w io.Writer) {
_, _ = fmt.Fprintln(w)
}
// groupUsers returns the owner and group of the current process and
// writes them to the w io.writer.
func groupUsers(sl *slog.Logger, msg string) {
groups, usr, err := helper.Owner()
if err != nil {
sl.Error(msg,
slog.String("own and group", "could not obtain the current user of this process"),
slog.Any("error", err))
}
clean := slices.DeleteFunc(groups, func(e string) bool {
return e == ""
})
sl.Info(msg, slog.String("permissions", "Server running as the following user and groups"),
slog.String("User", usr), slog.String("Groups", strings.Join(clean, ",")))
}
// locAddresses returns the local IP addresses in use by the application and
// writes them to the w io.writer.
func locAddresses(sl *slog.Logger, configs *config.Config, msg string) {
// get the local IP addresses and print them to the console.
err := configs.Addresses(sl)
if err != nil {
sl.Error(msg,
slog.String("local address", "could not obtain the usable addresses"),
slog.Any("error", err))
}
}
// environmentVars is used to parse the environment variables and set the Go runtime.
// Defaults are used if the environment variables are not set.
//
// The configuration uses reference types to make the values immutable.
func environmentVars(sl *slog.Logger) *config.Config {
const msg = "environment variables"
configs := config.Config{ //nolint:exhaustruct // complex config
Compression: true,
DatabaseURL: postgres.DefaultURL,
HTTPPort: config.StdCustom,
ProdMode: true,
ReadOnly: true,
SessionMaxAge: config.SessionHours,
}
if err := env.Parse(&configs); err != nil {
logs.Fatal(sl, msg,
slog.String("parsing error", "does the variable contain an invalid value?"),
slog.Any("error", err))
}
configs.Override()
if i := configs.MaxProcs; i > 0 {
runtime.GOMAXPROCS(int(i)) //nolint:gosec
}
return &configs
}
// newInstance is used to create the server controller instance.
//
// The configuration returns a reference type to make the values immutable.
func newInstance(ctx context.Context, db *sql.DB, configs config.Config) *handler.Configuration {
c := handler.Configuration{
Brand: brand,
Environment: configs,
Public: public,
Version: version,
View: view,
RecordCount: 0,
}
if c.Version == "" {
c.Version = flags.Commit("")
}
if ctx != nil && db != nil {
c.RecordCount = config.RecordCount(ctx, db)
}
return &c
}
// flagParser is used to parse the command line arguments.
// If an error is returned, the application will exit with the error code.
// Otherwise, a negative value is returned to indicate the application should continue.
func flagParser(w io.Writer, sl *slog.Logger, configs config.Config) flags.ExitCode {
const msg = "server flag parser"
if sl == nil {
return flags.GenericErr
}
exitc, err := flags.Run(w, version, &configs)
if err != nil {
sl.Error(msg,
slog.String("run", "there was a problem parsing the command arguments"),
slog.Int("exit code", int(exitc)),
slog.Any("error", err))
return exitc
}
usec := exitc >= flags.ExitOK
if usec {
return exitc
}
return flags.Continue
}
// welcomeMsg prints the welcome to message and returns the number
// of artifacts kept in the database. It customizes the log level based
// on the number of records vs the expected number.
func welcomeMsg(sl *slog.Logger, count int) {
const welcome = "Welcome to the Defacto2 web application"
switch {
case count == 0:
s := ", but with no access to the database records"
sl.Error(welcome + s)
case config.MinimumFiles > count:
s := " with too few records"
sl.Warn(welcome+s,
slog.Int("record count", count),
slog.Int("expecting at least", config.MinimumFiles))
default:
sl.Info(welcome, slog.Int("Artifacts", count))
}
}