-
Notifications
You must be signed in to change notification settings - Fork 14
/
serve.go
378 lines (326 loc) · 11.9 KB
/
serve.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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package core
import (
"context"
"errors"
"fmt"
"io"
"os"
"reflect"
"sort"
"strings"
"github.com/anz-bank/sysl-go/common"
"github.com/anz-bank/sysl-go/config"
"github.com/spf13/afero"
"gopkg.in/yaml.v2"
"github.com/anz-bank/pkg/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
)
type serveContextKey int
const (
serveConfigFileSystemKey serveContextKey = iota
)
// ConfigFileSystemOnto adds a config filesystem to ctx.
func ConfigFileSystemOnto(ctx context.Context, fs afero.Fs) context.Context {
return context.WithValue(ctx, serveConfigFileSystemKey, fs)
}
// Serve serves an auto-generated service.
//nolint:funlen
func Serve(
ctx context.Context,
downstreamConfig, createService, serviceInterface interface{},
newManager func(ctx context.Context, cfg *config.DefaultConfig, serviceIntf interface{}, hooks *Hooks) (interface{}, error),
) error {
MustTypeCheckCreateService(createService, serviceInterface)
customConfig := NewZeroCustomConfig(reflect.TypeOf(downstreamConfig), GetAppConfigType(createService))
customConfig, err := LoadCustomConfig(ctx, customConfig)
if customConfig == nil {
return fmt.Errorf("configuration is empty")
}
if err != nil {
return err
}
customConfigValue := reflect.ValueOf(customConfig).Elem()
library := customConfigValue.FieldByName("Library").Interface().(config.LibraryConfig)
genCodeValue := customConfigValue.FieldByName("GenCode")
development := customConfigValue.FieldByName("Development").Interface().(*config.DevelopmentConfig)
appConfig := customConfigValue.FieldByName("App")
upstream := genCodeValue.FieldByName("Upstream").Interface().(config.UpstreamConfig)
downstream := genCodeValue.FieldByName("Downstream").Interface()
defaultConfig := &config.DefaultConfig{
Library: library,
Development: development,
GenCode: config.GenCodeConfig{
Upstream: upstream,
Downstream: downstream,
},
}
createServiceResult := reflect.ValueOf(createService).Call(
[]reflect.Value{reflect.ValueOf(ctx), appConfig},
)
if err := createServiceResult[2].Interface(); err != nil {
return err.(error)
}
serviceIntf := createServiceResult[0].Interface()
hooksIntf := createServiceResult[1].Interface()
server := &autogenServer{
name: "nameless-autogenerated-app", // TODO source the application name from somewhere
}
pkgLoggerConfigs := []log.Config{
log.SetVerboseMode(true),
} // TODO expose this so it is configurable.
var logrusLogger *logrus.Logger = nil // TODO do we need to expose this or can we delete it?
ctx = InitialiseLogging(ctx, pkgLoggerConfigs, logrusLogger)
// OK, we have a ctx that contains a logger now!
manager, err := newManager(ctx, defaultConfig, serviceIntf, hooksIntf.(*Hooks))
if err != nil {
return err
}
switch manager := manager.(type) {
case Manager: // aka RESTful service manager
server.restManager = manager
case GrpcServerManager:
server.grpcServerManager = &manager
default:
panic(fmt.Errorf("Wrong type returned from newManager()"))
}
return server.start(ctx)
}
// LoadCustomConfig populates the given zero customConfig value with configuration data.
func LoadCustomConfig(ctx context.Context, customConfig interface{}) (interface{}, error) {
// TODO make this more flexible. It should be possible to resolve a config value
// without needing to access os.Args or hit any kind of filesystem.
if len(os.Args) != 2 {
return nil, fmt.Errorf("Wrong number of arguments (usage: %s (config | -h | --help))", os.Args[0])
}
if os.Args[1] == "--help" || os.Args[1] == "-h" {
fmt.Printf("Usage: %s config\n\n", os.Args[0])
describeCustomConfig(os.Stdout, customConfig)
fmt.Print("\n\n")
return nil, nil
}
var fs afero.Fs
if v := ctx.Value(serveConfigFileSystemKey); v != nil {
fs = v.(afero.Fs)
} else {
fs = afero.NewOsFs()
}
configPath := os.Args[1]
configData, err := afero.Afero{Fs: fs}.ReadFile(configPath)
if err != nil {
return nil, err
}
err = yaml.UnmarshalStrict(configData, customConfig)
return customConfig, err
}
// NewZeroCustomConfig uses reflection to create a new type derived from DefaultConfig,
// but with new GenCode.Downstream and App fields holding the same types as
// downstreamConfig and appConfig. It returns a pointer to a zero value of that
// new type.
func NewZeroCustomConfig(downstreamConfigType, appConfigType reflect.Type) interface{} {
defaultConfigType := reflect.TypeOf(config.DefaultConfig{})
libraryField, has := defaultConfigType.FieldByName("Library")
if !has {
panic("config.DefaultType missing Library field")
}
developmentField, has := defaultConfigType.FieldByName("Development")
if !has {
panic("config.DefaultType missing Development field")
}
genCodeType := reflect.TypeOf(config.GenCodeConfig{})
upstreamField, has := genCodeType.FieldByName("Upstream")
if !has {
panic("config.DefaultType missing Upstream field")
}
return reflect.New(reflect.StructOf([]reflect.StructField{
libraryField,
{Name: "GenCode", Type: reflect.StructOf([]reflect.StructField{
upstreamField,
{Name: "Downstream", Type: downstreamConfigType, Tag: `yaml:"downstream"`},
}), Tag: `yaml:"genCode"`},
developmentField,
{Name: "App", Type: appConfigType, Tag: `yaml:"app"`},
})).Interface()
}
// MustTypeCheckCreateService checks that the given createService has an acceptable type, and panics otherwise.
func MustTypeCheckCreateService(createService, serviceInterface interface{}) {
cs := reflect.TypeOf(createService)
if cs.NumIn() != 2 {
panic("createService: wrong number of in params")
}
if cs.NumOut() != 3 {
panic("createService: wrong number of out params")
}
var ctx context.Context
if reflect.TypeOf(&ctx).Elem() != cs.In(0) {
panic(fmt.Errorf("createService: first in param must be of type context.Context, not %v", cs.In(0)))
}
serviceInterfaceType := reflect.TypeOf(serviceInterface)
if serviceInterfaceType != cs.Out(0) {
panic(fmt.Errorf("createService: second out param must be of type %v, not %v", serviceInterfaceType, cs.Out(0)))
}
var hooks Hooks
if reflect.TypeOf(&hooks) != cs.Out(1) {
panic(fmt.Errorf("createService: second out param must be of type *Hooks, not %v", cs.Out(1)))
}
var err error
if reflect.TypeOf(&err).Elem() != cs.Out(2) {
panic(fmt.Errorf("createService: third out param must be of type error, not %v", cs.Out(1)))
}
}
// GetAppConfigType extracts the app's config type from createService.
// Precondition: MustTypeCheckCreateService(createService, serviceInterface) succeeded.
func GetAppConfigType(createService interface{}) reflect.Type {
cs := reflect.TypeOf(createService)
return cs.In(1)
}
func yamlEgComment(example, format string, args ...interface{}) string {
return fmt.Sprintf("\033[1;31m%s \033[0;32m# "+format+"\033[0m", append([]interface{}{example}, args...)...)
}
func describeCustomConfig(w io.Writer, customConfig interface{}) {
commonTypes := map[reflect.Type]string{
reflect.TypeOf(config.CommonServerConfig{}): "",
reflect.TypeOf(config.CommonDownstreamData{}): "",
reflect.TypeOf(config.TLSConfig{}): "",
reflect.TypeOf(common.SensitiveString{}): yamlEgComment(`"*****"`, "sensitive string"),
}
fmt.Fprint(w, "\033[1mConfiguration file YAML schema\033[0m")
commonTypeNames := make([]string, 0, len(commonTypes))
commonTypesByName := make(map[string]reflect.Type, len(commonTypes))
for ct := range commonTypes {
name := fmt.Sprintf("%s.%s", ct.PkgPath(), ct.Name())
commonTypeNames = append(commonTypeNames, name)
commonTypesByName[name] = ct
}
sort.Strings(commonTypeNames)
for _, name := range commonTypeNames {
ct := commonTypesByName[name]
if commonTypes[ct] == "" {
delete(commonTypes, ct)
fmt.Fprintf(w, "\n\n\033[1;32m%q.%s:\033[0m", ct.PkgPath(), ct.Name())
describeYAMLForType(w, ct, commonTypes, 4)
commonTypes[ct] = ""
}
}
fmt.Fprintf(w, "\n\n\033[1mApplication Configuration\033[0m")
describeYAMLForType(w, reflect.TypeOf(customConfig), commonTypes, 0)
}
//nolint:funlen
func describeYAMLForType(w io.Writer, t reflect.Type, commonTypes map[reflect.Type]string, indent int) {
outf := func(format string, args ...interface{}) {
parts := strings.SplitAfterN(format, "\n", 2)
fmt.Fprintf(w, strings.Join(parts, strings.Repeat(" ", indent)), args...)
}
if alias, has := commonTypes[t]; has {
if alias == "" {
outf(" " + yamlEgComment(`{}`, "%q.%s", t.PkgPath(), t.Name()))
} else {
outf(" %s", alias)
}
return
}
switch reflect.New(t).Elem().Interface().(type) { //nolint:gocritic
case logrus.Level:
outf(" \033[1m%s\033[0m", logrus.StandardLogger().Level.String())
return
}
switch t.Kind() {
case reflect.Bool:
outf(" \033[1mfalse\033[0m")
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
outf(" \033[1m0\033[0m")
case reflect.Float32, reflect.Float64:
outf(" \033[1m0.0\033[0m")
case reflect.Array, reflect.Slice:
outf("\n-")
describeYAMLForType(w, t.Elem(), commonTypes, indent+4)
case reflect.Interface:
outf(" " + yamlEgComment("{}", "any value"))
case reflect.Map:
outf("\n key: ")
describeYAMLForType(w, t.Elem(), commonTypes, indent+4)
case reflect.Ptr:
describeYAMLForType(w, t.Elem(), commonTypes, indent)
case reflect.String:
outf(" \033[1m\"\"\033[0m")
case reflect.Struct:
n := t.NumField()
for i := 0; i < n; i++ {
f := t.Field(i)
yamlTag := f.Tag.Get("yaml")
yamlParts := strings.Split(yamlTag, ",")
var name string
if len(yamlParts) > 0 {
name = yamlParts[0]
} else {
name = f.Name
}
outf("\n%s:", name)
describeYAMLForType(w, f.Type, commonTypes, indent+4)
}
default:
panic(fmt.Errorf("describeYAMLForType: Unhandled type: %v", t))
}
}
// experimental fork of core.ServerParams
type autogenServer struct {
name string
restManager Manager
grpcServerManager *GrpcServerManager
prometheusRegistry *prometheus.Registry
}
func (s *autogenServer) start(ctx context.Context) error {
// precondition: ctx must have been threaded through InitialiseLogging and hence contain a logger
// prepare the middleware
mWare := prepareMiddleware(ctx, s.name, s.prometheusRegistry)
var restIsRunning, grpcIsRunning bool
listeners := make([]func() error, 0)
// Make the listener function for the REST Admin server
if s.restManager != nil && s.restManager.AdminServerConfig() != nil {
log.Info(ctx, "found AdminServerConfig for REST")
listenAdmin, err := configureAdminServerListener(ctx, s.restManager, s.prometheusRegistry, mWare.admin)
if err != nil {
return err
}
listeners = append(listeners, listenAdmin)
} else {
log.Info(ctx, "no AdminServerConfig for REST was found")
}
// Make the listener function for the REST Public server
if s.restManager != nil && s.restManager.PublicServerConfig() != nil {
log.Info(ctx, "found PublicServerConfig for REST")
listenPublic, err := configurePublicServerListener(ctx, s.restManager, mWare.public)
if err != nil {
return err
}
listeners = append(listeners, listenPublic)
restIsRunning = true
} else {
log.Info(ctx, "no PublicServerConfig for REST was found")
}
// Make the listener function for the gRPC Public server.
if s.grpcServerManager != nil && s.grpcServerManager.GrpcPublicServerConfig != nil {
log.Info(ctx, "found GrpcPublicServerConfig for gRPC")
listenPublicGrpc := configurePublicGrpcServerListener(ctx, *s.grpcServerManager)
listeners = append(listeners, listenPublicGrpc)
grpcIsRunning = true
} else {
log.Info(ctx, "no GrpcPublicServerConfig for gRPC was found")
}
// Refuse to start and panic if neither of the public servers are enabled.
if !restIsRunning && !grpcIsRunning {
err := errors.New("REST and gRPC servers cannot both be nil")
log.Error(ctx, err)
panic(err)
}
// Run all listeners for all configured servers and block until the first one terminates.
errChan := make(chan error, 1)
for i := range listeners {
listener := listeners[i]
go func() {
errChan <- listener()
}()
}
return <-errChan
}