Newer
Older
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
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"sort"
"time"
"owo.codes/whats-this/api/lib/db"
"owo.codes/whats-this/api/lib/middleware"
"owo.codes/whats-this/api/lib/routes"
"github.com/go-chi/chi"
"github.com/go-chi/valve"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// Build config
const (
configLocationUnix = "/etc/whats-this/api/config.toml"
shutdownTimeout = 10 * time.Second
version = "1.5.0"
)
// printConfiguration iterates through a configuration map[string]interface{}
// and prints out all of the values in alphabetical order. Configuration keys
// are printed with dot notation.
func printConfiguration(prefix string, config map[string]interface{}) {
keys := make([]string, len(config))
i := 0
for k := range config {
keys[i] = k
i++
}
sort.Strings(keys)
for _, k := range keys {
if v, ok := config[k].(map[string]interface{}); ok {
printConfiguration(fmt.Sprintf("%s%s.", prefix, k), v)
} else {
fmt.Printf("%s%s: %+v\n", prefix, k, config[k])
}
}
}
func init() {
// Flag configuration
flags := pflag.NewFlagSet("whats-this-api", pflag.ExitOnError)
flags.IntP("log-level", "l", 1, "Set zerolog logging level (5=panic, 4=fatal, 3=error, 2=warn, 1=info, 0=debug)")
configFile := flags.StringP("config-file", "c", configLocationUnix,
fmt.Sprintf("Path to configuration file, defaults to %s", configLocationUnix))
printConfig := flags.BoolP("print-config", "p", false, "Prints configuration and exits")
flags.Parse(os.Args)
// Configuration defaults
viper.SetDefault("database.objectBucket", "public")
viper.SetDefault("http.listenAddress", ":49544")
viper.BindPFlag("log.level", flags.Lookup("log-level")) // default is 1 (info)
// Load configuration file
viper.SetConfigType("toml")
file, err := os.Open(*configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open configuration file (%s) for reading: %s", *configFile, err.Error())
os.Exit(1)
return
}
err = viper.ReadConfig(file)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse configuration file (%s): %s", *configFile, err.Error())
os.Exit(1)
return
}
file.Close()
// Configure logger
zerolog.TimeFieldFormat = ""
if lvl := viper.GetInt("log.level"); 0 <= lvl && lvl <= 5 {
zerolog.SetGlobalLevel(zerolog.Level(lvl))
} else {
viper.Set("log.level", 1)
zerolog.SetGlobalLevel(zerolog.InfoLevel)
log.Warn().Int("log.level", lvl).Msg("Invalid log level, defaulting to 1 (info)")
}
log.Debug().Uint8("level", uint8(zerolog.GlobalLevel())).Msg("Set logger level")
// Print configuration variables in alphabetical order
if *printConfig {
log.Info().Msg("Printing configuration values to Stdout")
settings := viper.AllSettings()
printConfiguration("", settings)
os.Exit(0)
return
}
// Ensure required configuration variables are set
if viper.GetString("database.connectionURL") == "" {
log.Fatal().Msg("Configuration: database.connectionURL is required")
}
if viper.GetString("database.objectBucket") == "" {
log.Fatal().Msg("Configuration: database.objectBucket is required")
}
if viper.GetString("http.listenAddress") == "" {
log.Fatal().Msg("Configuration: http.listenAddress is required")
}
if viper.GetInt64("http.maximumRequestSize") == 0 {
log.Fatal().Msg("Configuration: http.maximumRequestSize is required")
}
if viper.GetString("polr.resultURL") == "" {
log.Fatal().Msg("Configuration: polr.resultURL is required")
}
if viper.GetString("pomf.storageLocation") == "" {
log.Fatal().Msg("Configuration: pomf.storageLocation is required")
}
}
func main() {
valv := valve.New()
baseCtx := valv.Context()
// Connect to database
err := db.Connect("postgres", viper.GetString("database.connectionURL"))
if err != nil {
log.Fatal().Err(err).Msg("failed to connect to and ping the database")
}
// Mount middleware
r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Use(middleware.RequestID)
r.Use(middleware.CORSHeaders([]string{"*"}))
r.Use(middleware.StatusEndpoint("/health"))
r.Use(middleware.Authenticator)
// Route handlers
r.Get("/shorten/polr", routes.ShortenPolr(false))
r.Get("/shorten/polr/associated", routes.ShortenPolr(true))
r.Post("/upload/pomf", routes.UploadPomf(false))
r.Post("/upload/pomf/associated", routes.UploadPomf(true))
r.Post("/users", routes.CreateUser)
r.Get("/users/me", routes.Me)
// MethodNotAllowed handler
r.MethodNotAllowed(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
io.WriteString(w, "405 method not allowed")
}))
// Create HTTP server on specified listening address
listenAddress := viper.GetString("http.listenAddress")
server := http.Server{
Addr: listenAddress,
Handler: chi.ServerBaseContext(baseCtx, r),
}
// Listen for interrupts (^C) and exit gracefully
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
log.Info().Str("cause", "interrupt").Dur("timeout", shutdownTimeout).Msg("Shutting down worker")
e := make(chan struct{}, 2)
errors := make(chan struct{}, 2)
// Shutdown HTTP server
go func() {
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
log.Info().Dur("timeout", shutdownTimeout).Msg("Shutting down HTTP server")
err := server.Shutdown(ctx)
if err != nil {
log.Warn().Err(err).Msg("Failed to shutdown HTTP server gracefully, closing forecefully")
server.Close()
errors <- struct{}{}
} else {
log.Info().Msg("Successfully shutdown HTTP server gracefully")
}
e <- struct{}{}
}()
// Shutdown the global valve
go func() {
log.Info().Dur("timeout", shutdownTimeout).Msg("Shutting down global valve")
err := valv.Shutdown(shutdownTimeout)
if err != nil {
log.Warn().Err(err).Msg("Failed to shutdown global valve")
errors <- struct{}{}
} else {
log.Info().Msg("Successfully shutdown global valve")
}
e <- struct{}{}
}()
// Wait for global valve and HTTP server to shutdown
<-e
<-e
select {
case <-errors:
log.Info().Msg("Finished shutting down with errors")
os.Exit(1)
default:
log.Info().Msg("Finished shutting down")
os.Exit(0)
}
}()
// Start HTTP server
log.Info().Str("listenAddress", listenAddress).Msg("Starting HTTP server")
err = server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal().Err(err).Msg("Failed to start HTTP server")
}
<-c
}