-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
198 lines (161 loc) · 5.51 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
196
197
198
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"strconv"
"github.com/OpenSlides/openslides-autoupdate-service/pkg/auth"
"github.com/OpenSlides/openslides-autoupdate-service/pkg/environment"
messageBusRedis "github.com/OpenSlides/openslides-autoupdate-service/pkg/redis"
"github.com/OpenSlides/openslides-icc-service/internal/applause"
"github.com/OpenSlides/openslides-icc-service/internal/icchttp"
"github.com/OpenSlides/openslides-icc-service/internal/icclog"
"github.com/OpenSlides/openslides-icc-service/internal/notify"
"github.com/OpenSlides/openslides-icc-service/internal/redis"
"github.com/alecthomas/kong"
)
//go:generate sh -c "go run main.go build-doc > environment.md"
var (
envICCServicePort = environment.NewVariable("ICC_PORT", "9007", "Port on which the service listen on.")
envICCRedisHost = environment.NewVariable("CACHE_HOST", "localhost", "The host of the redis instance to save icc messages.")
envICCRedisPort = environment.NewVariable("CACHE_PORT", "6379", "The port of the redis instance to save icc messages.")
)
var cli struct {
Run struct{} `cmd:"" help:"Runs the service." default:"withargs"`
BuildDoc struct{} `cmd:"" help:"Build the environment documentation."`
Health struct {
Host string `help:"Host of the service" short:"h" default:"localhost"`
Port string `help:"Port of the service" short:"p" default:"9007" env:"ICC_PORT"`
UseHTTPS bool `help:"Use https to connect to the service" short:"s"`
Insecure bool `help:"Accept invalid cert" short:"k"`
} `cmd:"" help:"Runs a health check."`
}
func main() {
ctx, cancel := environment.InterruptContext()
defer cancel()
icclog.SetInfoLogger(log.Default())
kongCTX := kong.Parse(&cli, kong.UsageOnError())
switch kongCTX.Command() {
case "run":
if err := contextDone(run(ctx)); err != nil {
handleError(err)
os.Exit(1)
}
case "build-doc":
if err := contextDone(buildDocu()); err != nil {
handleError(err)
os.Exit(1)
}
case "health":
if err := contextDone(icchttp.HealthClient(ctx, cli.Health.UseHTTPS, cli.Health.Host, cli.Health.Port, cli.Health.Insecure)); err != nil {
handleError(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
}
// initService initializes all packages needed for the icc service.
//
// Returns a the service as callable.
func initService(lookup environment.Environmenter) (func(context.Context) error, error) {
if devMode, _ := strconv.ParseBool(environment.EnvDevelopment.Value(lookup)); devMode {
icclog.SetDebugLogger(log.Default())
}
var backgroundTasks []func(context.Context, func(error))
listenAddr := ":" + envICCServicePort.Value(lookup)
// Redis as message bus for datastore and logout events.
messageBus := messageBusRedis.New(lookup)
// Datastore Service.
database, err := applause.Flow(lookup, messageBus)
if err != nil {
return nil, fmt.Errorf("init database: %w", err)
}
// Auth Service.
authService, authBackground, err := auth.New(lookup, messageBus)
if err != nil {
return nil, fmt.Errorf("init auth system: %w", err)
}
backgroundTasks = append(backgroundTasks, authBackground)
backend := redis.New(envICCRedisHost.Value(lookup) + ":" + envICCRedisPort.Value(lookup))
notifyService, notifyBackground := notify.New(backend)
backgroundTasks = append(backgroundTasks, notifyBackground)
applauseService, applauseBackground := applause.New(backend, database)
backgroundTasks = append(backgroundTasks, applauseBackground)
service := func(ctx context.Context) error {
go database.Update(ctx, nil)
for _, bg := range backgroundTasks {
go bg(ctx, handleError)
}
// Start http server.
fmt.Printf("Listen on %s\n", listenAddr)
return Run(ctx, listenAddr, notifyService, applauseService, authService)
}
return service, nil
}
// Run starts a webserver
func Run(ctx context.Context, addr string, notifyService *notify.Notify, applauseService *applause.Applause, auth icchttp.Authenticater) error {
mux := http.NewServeMux()
icchttp.HandleHealth(mux)
notify.HandleReceive(mux, notifyService, auth)
notify.HandlePublish(mux, notifyService, auth)
applause.HandleReceive(mux, applauseService, auth)
applause.HandleSend(mux, applauseService, auth)
srv := &http.Server{
Addr: addr,
Handler: mux,
BaseContext: func(net.Listener) context.Context { return ctx },
}
// Shutdown logic in separate goroutine.
wait := make(chan error)
go func() {
<-ctx.Done()
if err := srv.Shutdown(context.Background()); err != nil {
wait <- fmt.Errorf("HTTP server shutdown: %w", err)
return
}
wait <- nil
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
return fmt.Errorf("HTTP Server failed: %v", err)
}
return <-wait
}
// contextDone returns an empty error if the context is done or exceeded
func contextDone(err error) error {
if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil
}
return err
}
// handleError handles an error.
//
// Ignores context closed errors.
func handleError(err error) {
if contextDone(err) == nil {
return
}
icclog.Info("Error: %v", err)
}