generated from qdm12/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (157 loc) · 4.65 KB
/
main.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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
_ "time/tzdata"
"github.com/qdm12/golibs/logging"
"github.com/qdm12/srv/internal/config"
"github.com/qdm12/srv/internal/filesystem"
"github.com/qdm12/srv/internal/health"
"github.com/qdm12/srv/internal/metrics"
"github.com/qdm12/srv/internal/models"
"github.com/qdm12/srv/internal/server"
"github.com/qdm12/srv/internal/shutdown"
"github.com/qdm12/srv/internal/splash"
)
var (
version = "unknown"
commit = "unknown"
buildDate = "an unknown date"
)
func main() {
buildInfo := models.BuildInformation{
Version: version,
Commit: commit,
BuildDate: buildDate,
}
ctx := context.Background()
ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
configReader := config.NewReader()
logger := logging.NewParent(logging.Settings{})
args := os.Args
errorCh := make(chan error)
go func() {
errorCh <- _main(ctx, buildInfo, args, logger, configReader)
}()
select {
case <-ctx.Done():
fmt.Println()
logger.Warn("Caught OS signal, shutting down\n")
stop()
case err := <-errorCh:
close(errorCh)
if err == nil { // expected exit such as healthcheck
os.Exit(0)
}
logger.Error(err)
}
const shutdownGracePeriod = 5 * time.Second
timer := time.NewTimer(shutdownGracePeriod)
select {
case <-errorCh:
if !timer.Stop() {
<-timer.C
}
logger.Info("Shutdown successful")
case <-timer.C:
logger.Warn("Shutdown timed out")
}
os.Exit(1)
}
func _main(ctx context.Context, buildInfo models.BuildInformation,
args []string, logger logging.ParentLogger, configReader config.Reader) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if health.IsClientMode(args) {
// Running the program in a separate instance through the Docker
// built-in healthcheck, in an ephemeral fashion to query the
// long running instance of the program about its status
client := health.NewClient()
config, _, err := configReader.ReadConfig()
if err != nil {
return err
}
return client.Query(ctx, config.Health.Address)
}
fmt.Println(splash.Splash(buildInfo))
config, warnings, err := configReader.ReadConfig()
logger = logger.NewChild(logging.Settings{Level: config.Log.Level})
for _, warning := range warnings {
logger.Warn(warning)
}
if err != nil {
return err
}
srvExists, srvIsEmpty, err := filesystem.DirChecks(config.Filepaths.Srv)
if err != nil {
return err
}
if !srvExists || srvIsEmpty {
logger.Warn(config.Filepaths.Srv + " is empty, initiating it with dummy files")
if err := filesystem.InitDummySrv(config.Filepaths.Srv); err != nil {
return err
}
}
files, directories, err := filesystem.WalkSrv(config.Filepaths.Srv)
if err != nil {
return err
}
for _, file := range files {
logger.Debug("Found file: " + file)
}
logger.Info("Found " + strconv.Itoa(len(files)) + " files and " +
strconv.Itoa(len(directories)) + " directories in " + config.Filepaths.Srv)
err = filesystem.CopyDir(config.Filepaths.Srv, config.Filepaths.Work)
if err != nil {
return err
}
shutdownServersGroup := shutdown.NewGroup("servers: ")
metricsLogger := logger.NewChild(logging.Settings{Prefix: "metrics server: "})
metricsServer := metrics.NewServer(config.Metrics.Address, metricsLogger)
const registerMetrics = true
metrics, err := metrics.New(registerMetrics)
if err != nil {
return err
}
metricsServerCtx, metricsServerDone := shutdownServersGroup.Add("metrics", time.Second)
go func() {
defer close(metricsServerDone)
if err := metricsServer.Run(metricsServerCtx); err != nil {
logger.Error(err.Error())
}
}()
serverLogger := logger.NewChild(logging.Settings{Prefix: "http server: "})
srvFS := http.Dir(config.Filepaths.Work)
mainServer := server.New(config.HTTP, serverLogger, metrics, srvFS)
serverCtx, serverDone := shutdownServersGroup.Add("server", time.Second)
go func() {
defer close(serverDone)
if err := mainServer.Run(serverCtx); err != nil {
logger.Error(err.Error())
if errors.Is(err, server.ErrCrashed) {
cancel() // stop other routines
}
}
}()
healthcheck := func() error { return nil }
heathcheckLogger := logger.NewChild(logging.Settings{Prefix: "healthcheck: "})
healthServer := health.NewServer(config.Health.Address, heathcheckLogger, healthcheck)
healthServerCtx, healthServerDone := shutdownServersGroup.Add("health", time.Second)
go func() {
defer close(healthServerDone)
if err := healthServer.Run(healthServerCtx); err != nil {
logger.Error(err.Error())
}
}()
shutdownOrder := shutdown.NewOrder()
shutdownOrder.Append(shutdownServersGroup)
<-ctx.Done()
return shutdownOrder.Shutdown(time.Second, logger)
}