forked from micro/micro
/
profile.go
396 lines (343 loc) · 12 KB
/
profile.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Package profile is for specific profiles
// @todo this package is the definition of cruft and
// should be rewritten in a more elegant way
package profile
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/crazybber/micro/v3/service/auth"
"github.com/crazybber/micro/v3/service/broker"
"github.com/crazybber/micro/v3/service/build"
"github.com/crazybber/micro/v3/service/build/golang"
"github.com/crazybber/micro/v3/service/client"
"github.com/crazybber/micro/v3/service/config"
"github.com/crazybber/micro/v3/service/events"
"github.com/crazybber/micro/v3/service/logger"
"github.com/crazybber/micro/v3/service/model"
"github.com/crazybber/micro/v3/service/registry"
"github.com/crazybber/micro/v3/service/router"
"github.com/crazybber/micro/v3/service/runtime"
"github.com/crazybber/micro/v3/service/server"
"github.com/crazybber/micro/v3/service/store"
"github.com/crazybber/micro/v3/util/opentelemetry"
"github.com/crazybber/micro/v3/util/opentelemetry/jaeger"
mAuthNJwt "github.com/crazybber/micro/v3/service/auth/jwt"
mAuthNoop "github.com/crazybber/micro/v3/service/auth/noop"
mBrokerMen "github.com/crazybber/micro/v3/service/broker/memory"
mClientGrpc "github.com/crazybber/micro/v3/service/client/grpc"
mConfigStore "github.com/crazybber/micro/v3/service/config/store"
mEventStore "github.com/crazybber/micro/v3/service/events/store"
memStream "github.com/crazybber/micro/v3/service/events/stream/memory"
mRegistryMem "github.com/crazybber/micro/v3/service/registry/memory"
mRouterK8s "github.com/crazybber/micro/v3/service/router/kubernetes"
mRouterReg "github.com/crazybber/micro/v3/service/router/registry"
mRuntimeK8s "github.com/crazybber/micro/v3/service/runtime/kubernetes"
mRuntimeLocal "github.com/crazybber/micro/v3/service/runtime/local"
mServerGrpc "github.com/crazybber/micro/v3/service/server/grpc"
mStoreFile "github.com/crazybber/micro/v3/service/store/file"
mStoreMem "github.com/crazybber/micro/v3/service/store/memory"
uAuth "github.com/crazybber/micro/v3/util/auth"
uUser "github.com/crazybber/micro/v3/util/user"
natsStream "github.com/crazybber/micro/v3/plugin/nats/stream"
redisstream "github.com/crazybber/micro/v3/plugin/redis/stream"
"github.com/go-redis/redis/v8"
"github.com/urfave/cli/v2"
)
// profiles which when called will configure micro to run in that environment
var profiles = map[string]*Profile{
// built in profiles
"client": Client,
"service": Service,
"server": Server,
"test": Test,
"local": Local,
"kubernetes": Kubernetes,
"develop": Develop,
"simple": Simple,
"dev": Dev,
}
// Profile configures an environment
type Profile struct {
// name of the profile
Name string
// function used for setup
Setup func(*cli.Context) error
// TODO: presetup dependencies
// e.g start resources
}
// Register a profile
func Register(name string, p *Profile) error {
if _, ok := profiles[name]; ok {
return fmt.Errorf("profile %s already exists", name)
}
profiles[name] = p
return nil
}
// Load a profile
func Load(name string) (*Profile, error) {
v, ok := profiles[name]
if !ok {
return nil, fmt.Errorf("profile %s does not exist", name)
}
return v, nil
}
// Client profile is for any entrypoint that behaves as a client
var Client = &Profile{
Name: "client",
Setup: func(ctx *cli.Context) error { return nil },
}
// Local profile to run as a single process
var Local = &Profile{
Name: "local",
Setup: func(ctx *cli.Context) error {
// set client/server
client.DefaultClient = mClientGrpc.NewClient()
server.DefaultServer = mServerGrpc.NewServer()
auth.DefaultAuth = mAuthNJwt.NewAuth()
store.DefaultStore = mStoreFile.NewStore(mStoreFile.WithDir(filepath.Join(uUser.Dir, "server", "store")))
SetupConfigSecretKey(ctx)
config.DefaultConfig, _ = mConfigStore.NewConfig(store.DefaultStore, "")
SetupJWT(ctx)
SetupRegistry(mRegistryMem.NewRegistry())
SetupBroker(mBrokerMen.NewBroker())
// set the store in the model
model.DefaultModel = model.NewModel(
model.WithStore(store.DefaultStore),
)
runtime.DefaultRuntime = mRuntimeLocal.NewRuntime()
var err error
events.DefaultStream, err = memStream.NewStream()
if err != nil {
logger.Fatalf("Error configuring stream: %v", err)
}
events.DefaultStore = mEventStore.NewStore(
mEventStore.WithStore(store.DefaultStore),
)
store.DefaultBlobStore, err = mStoreFile.NewBlobStore()
if err != nil {
logger.Fatalf("Error configuring file blob store: %v", err)
}
return nil
},
}
// Kubernetes profile to run on kubernetes with zero deps. Designed for use with the micro helm chart
var Kubernetes = &Profile{
Name: "kubernetes",
Setup: func(ctx *cli.Context) (err error) {
auth.DefaultAuth = mAuthNJwt.NewAuth()
SetupJWT(ctx)
runtime.DefaultRuntime = mRuntimeK8s.NewRuntime()
build.DefaultBuilder, err = golang.NewBuilder()
if err != nil {
logger.Fatalf("Error configuring golang builder: %v", err)
}
events.DefaultStream, err = memStream.NewStream()
if err != nil {
logger.Fatalf("Error configuring stream: %v", err)
}
store.DefaultStore = mStoreFile.NewStore(mStoreFile.WithDir("/store"))
store.DefaultBlobStore, err = mStoreFile.NewBlobStore(mStoreFile.WithDir("/store/blob"))
if err != nil {
logger.Fatalf("Error configuring file blob store: %v", err)
}
// set the store in the model
model.DefaultModel = model.NewModel(
model.WithStore(store.DefaultStore),
)
// the registry service uses the memory registry, the other core services will use the default
// rpc client and call the registry service
if ctx.Args().Get(1) == "registry" {
SetupRegistry(mRegistryMem.NewRegistry())
}
// the broker service uses the memory broker, the other core services will use the default
// rpc client and call the broker service
if ctx.Args().Get(1) == "broker" {
SetupBroker(mBrokerMen.NewBroker())
}
config.DefaultConfig, err = mConfigStore.NewConfig(store.DefaultStore, "")
if err != nil {
logger.Fatalf("Error configuring config: %v", err)
}
SetupConfigSecretKey(ctx)
// Use k8s routing which is DNS based
router.DefaultRouter = mRouterK8s.NewRouter()
client.DefaultClient.Init(client.Router(router.DefaultRouter))
// Configure tracing with Jaeger:
tracingServiceName := ctx.Args().Get(1)
if len(tracingServiceName) == 0 {
tracingServiceName = "Micro"
}
openTracer, _, err := jaeger.New(
opentelemetry.WithServiceName(tracingServiceName),
opentelemetry.WithTraceReporterAddress("localhost:6831"),
)
if err != nil {
logger.Fatalf("Error configuring opentracing: %v", err)
}
opentelemetry.DefaultOpenTracer = openTracer
return nil
},
}
var Server = &Profile{
Name: "server",
Setup: func(ctx *cli.Context) error {
auth.DefaultAuth = mAuthNJwt.NewAuth()
store.DefaultStore = mStoreFile.NewStore(mStoreFile.WithDir(filepath.Join(uUser.Dir, "server", "store")))
SetupConfigSecretKey(ctx)
config.DefaultConfig, _ = mConfigStore.NewConfig(store.DefaultStore, "")
SetupJWT(ctx)
// the registry service uses the memory registry, the other core services will use the default
// rpc client and call the registry service
if ctx.Args().Get(1) == "registry" {
SetupRegistry(mRegistryMem.NewRegistry())
} else {
// set the registry address
registry.DefaultRegistry.Init(
registry.Addrs("localhost:8000"),
)
SetupRegistry(registry.DefaultRegistry)
}
// the broker service uses the memory broker, the other core services will use the default
// rpc client and call the broker service
if ctx.Args().Get(1) == "broker" {
SetupBroker(mBrokerMen.NewBroker())
} else {
broker.DefaultBroker.Init(
broker.Addrs("localhost:8003"),
)
SetupBroker(broker.DefaultBroker)
}
// set the store in the model
model.DefaultModel = model.NewModel(
model.WithStore(store.DefaultStore),
)
// use the local runtime, note: the local runtime is designed to run source code directly so
// the runtime builder should NOT be set when using this implementation
runtime.DefaultRuntime = mRuntimeLocal.NewRuntime()
var err error
events.DefaultStream, err = memStream.NewStream()
if err != nil {
logger.Fatalf("Error configuring stream: %v", err)
}
events.DefaultStore = mEventStore.NewStore(
mEventStore.WithStore(store.DefaultStore),
)
store.DefaultBlobStore, err = mStoreFile.NewBlobStore()
if err != nil {
logger.Fatalf("Error configuring file blob store: %v", err)
}
// Configure tracing with Jaeger (forced tracing):
tracingServiceName := ctx.Args().Get(1)
if len(tracingServiceName) == 0 {
tracingServiceName = "Micro"
}
openTracer, _, err := jaeger.New(
opentelemetry.WithServiceName(tracingServiceName),
opentelemetry.WithSamplingRate(1),
)
if err != nil {
logger.Fatalf("Error configuring opentracing: %v", err)
}
opentelemetry.DefaultOpenTracer = openTracer
return nil
},
}
// Service is the default for any services run
var Service = &Profile{
Name: "service",
Setup: func(ctx *cli.Context) error { return nil },
}
// Test profile is used for the go test suite
var Test = &Profile{
Name: "test",
Setup: func(ctx *cli.Context) error {
auth.DefaultAuth = mAuthNoop.NewAuth()
store.DefaultStore = mStoreMem.NewStore()
store.DefaultBlobStore, _ = mStoreFile.NewBlobStore()
config.DefaultConfig, _ = mConfigStore.NewConfig(store.DefaultStore, "")
SetupRegistry(mRegistryMem.NewRegistry())
// set the store in the model
model.DefaultModel = model.NewModel(
model.WithStore(store.DefaultStore),
)
return nil
},
}
// SetupRegistry configures the registry
func SetupRegistry(reg registry.Registry) {
registry.DefaultRegistry = reg
router.DefaultRouter = mRouterReg.NewRouter(router.Registry(reg))
client.DefaultClient.Init(client.Registry(reg), client.Router(router.DefaultRouter))
server.DefaultServer.Init(server.Registry(reg))
}
// SetupBroker configures the broker
func SetupBroker(b broker.Broker) {
broker.DefaultBroker = b
client.DefaultClient.Init(client.Broker(b))
server.DefaultServer.Init(server.Broker(b))
}
// SetupJWT configures the default internal system rules
func SetupJWT(ctx *cli.Context) {
for _, rule := range uAuth.SystemRules {
if err := auth.DefaultAuth.Grant(rule); err != nil {
logger.Fatal("Error creating default rule: %v", err)
}
}
}
func SetupConfigSecretKey(ctx *cli.Context) {
key := ctx.String("config_secret_key")
if len(key) == 0 {
k, err := uUser.GetConfigSecretKey()
if err != nil {
logger.Fatal("Error getting config secret: %v", err)
}
os.Setenv("MICRO_CONFIG_SECRET_KEY", k)
}
}
// redisStreamOpts returns a slice of options which should be used to configure redis broker
func redisStreamOpts(ctx *cli.Context) []redisstream.Option {
fullAddr := ctx.String("broker_address")
o, err := redis.ParseURL(fullAddr)
if err != nil {
logger.Fatalf("Error configuring redis connection, failed to parse %s", fullAddr)
}
opts := []redisstream.Option{
redisstream.Address(o.Addr),
redisstream.User(o.Username),
redisstream.Password(o.Password),
}
if o.TLSConfig != nil {
opts = append(opts, redisstream.TLSConfig(o.TLSConfig))
}
return opts
}
// natsStreamOpts returns a slice of options which should be used to configure nats
func natsStreamOpts(ctx *cli.Context) []natsStream.Option {
opts := []natsStream.Option{
natsStream.Address("nats://nats-cluster:4222"),
natsStream.ClusterID("nats-streaming-cluster"),
}
// Parse event TLS certs
if len(ctx.String("events_tls_cert")) > 0 || len(ctx.String("events_tls_key")) > 0 {
cert, err := tls.LoadX509KeyPair(ctx.String("events_tls_cert"), ctx.String("events_tls_key"))
if err != nil {
logger.Fatalf("Error loading event TLS cert: %v", err)
}
// load custom certificate authority
caCertPool := x509.NewCertPool()
if len(ctx.String("events_tls_ca")) > 0 {
crt, err := ioutil.ReadFile(ctx.String("events_tls_ca"))
if err != nil {
logger.Fatalf("Error loading event TLS certificate authority: %v", err)
}
caCertPool.AppendCertsFromPEM(crt)
}
cfg := &tls.Config{Certificates: []tls.Certificate{cert}, RootCAs: caCertPool}
opts = append(opts, natsStream.TLSConfig(cfg))
}
return opts
}