forked from OpenSlides/openslides-autoupdate-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
195 lines (159 loc) · 5.79 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
184
185
186
187
188
189
190
191
192
193
194
195
package main
import (
"context"
"fmt"
"io"
"log"
gohttp "net/http"
"os"
"strconv"
"strings"
"github.com/OpenSlides/openslides-autoupdate-service/internal/autoupdate"
"github.com/OpenSlides/openslides-autoupdate-service/internal/http"
"github.com/OpenSlides/openslides-autoupdate-service/internal/metric"
"github.com/OpenSlides/openslides-autoupdate-service/internal/oserror"
"github.com/OpenSlides/openslides-autoupdate-service/internal/restrict"
"github.com/OpenSlides/openslides-autoupdate-service/pkg/auth"
"github.com/OpenSlides/openslides-autoupdate-service/pkg/environment"
"github.com/OpenSlides/openslides-autoupdate-service/pkg/redis"
"github.com/alecthomas/kong"
)
//go:generate sh -c "go run main.go build-doc > environment.md"
var (
envAutoupdatePort = environment.NewVariable("AUTOUPDATE_PORT", "9012", "Port on which the service listen on.")
envMetricInterval = environment.NewVariable("METRIC_INTERVAL", "5m", "Time in how often the metrics are gathered. Zero disables the metrics.")
envMetricSaveInterval = environment.NewVariable("METRIC_SAVE_INTERVAL", "5m", "Interval, how often the metric should be saved to redis. Redis will ignore entries, that are twice at old then the save interval.")
envDisableConnectionCount = environment.NewVariable("DISABLE_CONNECTION_COUNT", "false", "Do not count connections.")
envPublicAccessOnly = environment.NewVariable("OPENSLIDES_PUBLIC_ACCESS_ONLY", "false", "Start for only public access. Does not write to redis or connect to the vote-service.")
)
var cli struct {
Run struct{} `cmd:"" help:"Runs the service." default:"withargs"`
BuildDoc struct{} `cmd:"" help:"Build the environment documentation."`
Health struct{} `cmd:"" help:"Runs a health check."`
}
func main() {
ctx, cancel := environment.InterruptContext()
defer cancel()
kongCTX := kong.Parse(&cli, kong.UsageOnError())
switch kongCTX.Command() {
case "run":
if err := run(ctx); err != nil {
oserror.Handle(err)
os.Exit(1)
}
case "build-doc":
if err := buildDocu(); err != nil {
oserror.Handle(err)
os.Exit(1)
}
case "health":
if err := health(ctx); err != nil {
oserror.Handle(err)
os.Exit(1)
}
}
}
func run(ctx context.Context) error {
lookup := new(environment.ForProduction)
service, err := initService(lookup)
if err != nil {
return fmt.Errorf("init services: %w", err)
}
return service(ctx)
}
func buildDocu() error {
lookup := new(environment.ForDocu)
if _, err := initService(lookup); err != nil {
return fmt.Errorf("init services: %w", err)
}
doc, err := lookup.BuildDoc()
if err != nil {
return fmt.Errorf("build doc: %w", err)
}
fmt.Println(doc)
return nil
}
func health(ctx context.Context) error {
port, found := os.LookupEnv("AUTOUPDATE_PORT")
if !found {
port = "9012"
}
req, err := gohttp.NewRequestWithContext(ctx, "GET", "http://localhost:"+port+"/system/autoupdate/health", nil)
if err != nil {
return fmt.Errorf("creating request: %w", err)
}
resp, err := gohttp.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("sending request: %w", err)
}
if resp.StatusCode != 200 {
return fmt.Errorf("health returned status %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response body: %w", err)
}
expect := `{"healthy": true}`
got := strings.TrimSpace(string(body))
if got != expect {
return fmt.Errorf("got `%s`, expected `%s`", body, expect)
}
return nil
}
// initService initializes all packages needed for the autoupdate service.
//
// Returns a the service as callable.
func initService(lookup environment.Environmenter) (func(context.Context) error, error) {
var backgroundTasks []func(context.Context, func(error))
listenAddr := ":" + envAutoupdatePort.Value(lookup)
// Redis as message bus for datastore and logout events.
messageBus := redis.New(lookup)
publicAccessOnly, _ := strconv.ParseBool(envPublicAccessOnly.Value(lookup))
// Autoupdate data flow.
flow, flowBackground, err := autoupdate.NewFlow(lookup, messageBus, publicAccessOnly)
if err != nil {
return nil, fmt.Errorf("init autoupdate data flow: %w", err)
}
backgroundTasks = append(backgroundTasks, flowBackground)
// Auth Service.
authService, authBackground, err := auth.New(lookup, messageBus)
if err != nil {
return nil, fmt.Errorf("init connection to auth: %w", err)
}
backgroundTasks = append(backgroundTasks, authBackground)
// Autoupdate Service.
auService, auBackground, err := autoupdate.New(lookup, flow, restrict.Middleware)
if err != nil {
return nil, fmt.Errorf("init autoupdate: %w", err)
}
backgroundTasks = append(backgroundTasks, auBackground)
// Start metrics.
metric.Register(metric.Runtime)
metricTime, err := environment.ParseDuration(envMetricInterval.Value(lookup))
if err != nil {
return nil, fmt.Errorf("invalid value for `METRIC_INTERVAL`, expected duration got %s: %w", envMetricInterval.Value(lookup), err)
}
metricSaveInterval, err := environment.ParseDuration(envMetricSaveInterval.Value(lookup))
if err != nil {
return nil, fmt.Errorf("invalid value for `METRIC_SAVE_INTERVAL`, expected duration got %s: %w", envMetricInterval.Value(lookup), err)
}
if metricTime > 0 {
runMetirc := func(ctx context.Context, errorHandler func(error)) {
metric.Loop(ctx, metricTime, log.Default())
}
backgroundTasks = append(backgroundTasks, runMetirc)
}
metricStorage := messageBus
if disable, _ := strconv.ParseBool(envDisableConnectionCount.Value(lookup)); disable || publicAccessOnly {
metricStorage = nil
}
service := func(ctx context.Context) error {
for _, bg := range backgroundTasks {
go bg(ctx, oserror.Handle)
}
// Start http server.
fmt.Printf("Listen on %s\n", listenAddr)
return http.Run(ctx, listenAddr, authService, auService, metricStorage, metricSaveInterval)
}
return service, nil
}