-
Notifications
You must be signed in to change notification settings - Fork 935
/
Copy pathservice.go
445 lines (382 loc) · 19.6 KB
/
service.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package frontend
import (
"math"
"os"
"sync/atomic"
"time"
"go.temporal.io/api/workflowservice/v1"
"google.golang.org/grpc"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/reflection"
"go.temporal.io/server/common/membership"
"go.temporal.io/server/service/frontend/configs"
"go.temporal.io/server/common/quotas"
"go.temporal.io/server/common/config"
"go.temporal.io/server/api/adminservice/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/authorization"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/persistence"
persistenceClient "go.temporal.io/server/common/persistence/client"
espersistence "go.temporal.io/server/common/persistence/elasticsearch"
"go.temporal.io/server/common/resource"
"go.temporal.io/server/common/rpc"
"go.temporal.io/server/common/rpc/interceptor"
"go.temporal.io/server/common/searchattribute"
)
// Config represents configuration for frontend service
type Config struct {
NumHistoryShards int32
PersistenceMaxQPS dynamicconfig.IntPropertyFn
PersistenceGlobalMaxQPS dynamicconfig.IntPropertyFn
VisibilityMaxPageSize dynamicconfig.IntPropertyFnWithNamespaceFilter
EnableVisibilitySampling dynamicconfig.BoolPropertyFn
VisibilityListMaxQPS dynamicconfig.IntPropertyFnWithNamespaceFilter
EnableReadVisibilityFromES dynamicconfig.BoolPropertyFnWithNamespaceFilter
ESVisibilityListMaxQPS dynamicconfig.IntPropertyFnWithNamespaceFilter
ESIndexMaxResultWindow dynamicconfig.IntPropertyFn
HistoryMaxPageSize dynamicconfig.IntPropertyFnWithNamespaceFilter
RPS dynamicconfig.IntPropertyFn
MaxNamespaceRPSPerInstance dynamicconfig.IntPropertyFnWithNamespaceFilter
MaxNamespaceCountPerInstance dynamicconfig.IntPropertyFnWithNamespaceFilter
GlobalNamespaceRPS dynamicconfig.IntPropertyFnWithNamespaceFilter
MaxIDLengthLimit dynamicconfig.IntPropertyFn
EnableClientVersionCheck dynamicconfig.BoolPropertyFn
MinRetentionDays dynamicconfig.IntPropertyFn
DisallowQuery dynamicconfig.BoolPropertyFnWithNamespaceFilter
ShutdownDrainDuration dynamicconfig.DurationPropertyFn
MaxBadBinaries dynamicconfig.IntPropertyFnWithNamespaceFilter
// security protection settings
DisableListVisibilityByFilter dynamicconfig.BoolPropertyFnWithNamespaceFilter
// size limit system protection
BlobSizeLimitError dynamicconfig.IntPropertyFnWithNamespaceFilter
BlobSizeLimitWarn dynamicconfig.IntPropertyFnWithNamespaceFilter
ThrottledLogRPS dynamicconfig.IntPropertyFn
// Namespace specific config
EnableNamespaceNotActiveAutoForwarding dynamicconfig.BoolPropertyFnWithNamespaceFilter
// ValidSearchAttributes is legal indexed keys that can be used in list APIs
ValidSearchAttributes dynamicconfig.MapPropertyFn
SearchAttributesNumberOfKeysLimit dynamicconfig.IntPropertyFnWithNamespaceFilter
SearchAttributesSizeOfValueLimit dynamicconfig.IntPropertyFnWithNamespaceFilter
SearchAttributesTotalSizeLimit dynamicconfig.IntPropertyFnWithNamespaceFilter
// DefaultWorkflowRetryPolicy represents default values for unset fields on a Workflow's
// specified RetryPolicy
DefaultWorkflowRetryPolicy dynamicconfig.MapPropertyFnWithNamespaceFilter
// VisibilityArchival system protection
VisibilityArchivalQueryMaxPageSize dynamicconfig.IntPropertyFn
SendRawWorkflowHistory dynamicconfig.BoolPropertyFnWithNamespaceFilter
// DefaultWorkflowTaskTimeout the default workflow task timeout
DefaultWorkflowTaskTimeout dynamicconfig.DurationPropertyFnWithNamespaceFilter
// EnableServerVersionCheck disables periodic version checking performed by the frontend
EnableServerVersionCheck dynamicconfig.BoolPropertyFn
// EnableTokenNamespaceEnforcement enables enforcement that namespace in completion token matches namespace of the request
EnableTokenNamespaceEnforcement dynamicconfig.BoolPropertyFn
// gRPC keep alive options
// If a client pings too frequently, terminate the connection.
KeepAliveMinTime dynamicconfig.DurationPropertyFn
// Allow pings even when there are no active streams (RPCs)
KeepAlivePermitWithoutStream dynamicconfig.BoolPropertyFn
// Close the connection if a client is idle.
KeepAliveMaxConnectionIdle dynamicconfig.DurationPropertyFn
// Close the connection if it is too old.
KeepAliveMaxConnectionAge dynamicconfig.DurationPropertyFn
// Additive period after MaxConnectionAge after which the connection will be forcibly closed.
KeepAliveMaxConnectionAgeGrace dynamicconfig.DurationPropertyFn
// Ping the client if it is idle to ensure the connection is still active.
KeepAliveTime dynamicconfig.DurationPropertyFn
// Wait for the ping ack before assuming the connection is dead.
KeepAliveTimeout dynamicconfig.DurationPropertyFn
}
// NewConfig returns new service config with default values
func NewConfig(dc *dynamicconfig.Collection, numHistoryShards int32, enableReadFromES bool) *Config {
return &Config{
NumHistoryShards: numHistoryShards,
PersistenceMaxQPS: dc.GetIntProperty(dynamicconfig.FrontendPersistenceMaxQPS, 2000),
PersistenceGlobalMaxQPS: dc.GetIntProperty(dynamicconfig.FrontendPersistenceGlobalMaxQPS, 0),
VisibilityMaxPageSize: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendVisibilityMaxPageSize, 1000),
EnableVisibilitySampling: dc.GetBoolProperty(dynamicconfig.EnableVisibilitySampling, true),
VisibilityListMaxQPS: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendVisibilityListMaxQPS, 30),
EnableReadVisibilityFromES: dc.GetBoolPropertyFnWithNamespaceFilter(dynamicconfig.EnableReadVisibilityFromES, enableReadFromES),
ESVisibilityListMaxQPS: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendESVisibilityListMaxQPS, 10),
ESIndexMaxResultWindow: dc.GetIntProperty(dynamicconfig.FrontendESIndexMaxResultWindow, 10000),
HistoryMaxPageSize: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendHistoryMaxPageSize, common.GetHistoryMaxPageSize),
RPS: dc.GetIntProperty(dynamicconfig.FrontendRPS, 2400),
MaxNamespaceRPSPerInstance: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendMaxNamespaceRPSPerInstance, 2400),
MaxNamespaceCountPerInstance: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendMaxNamespaceCountPerInstance, 1200),
GlobalNamespaceRPS: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendGlobalNamespaceRPS, 0),
MaxIDLengthLimit: dc.GetIntProperty(dynamicconfig.MaxIDLengthLimit, 1000),
MaxBadBinaries: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.FrontendMaxBadBinaries, namespace.MaxBadBinaries),
DisableListVisibilityByFilter: dc.GetBoolPropertyFnWithNamespaceFilter(dynamicconfig.DisableListVisibilityByFilter, false),
BlobSizeLimitError: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.BlobSizeLimitError, 2*1024*1024),
BlobSizeLimitWarn: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.BlobSizeLimitWarn, 256*1024),
ThrottledLogRPS: dc.GetIntProperty(dynamicconfig.FrontendThrottledLogRPS, 20),
ShutdownDrainDuration: dc.GetDurationProperty(dynamicconfig.FrontendShutdownDrainDuration, 0),
EnableNamespaceNotActiveAutoForwarding: dc.GetBoolPropertyFnWithNamespaceFilter(dynamicconfig.EnableNamespaceNotActiveAutoForwarding, true),
EnableClientVersionCheck: dc.GetBoolProperty(dynamicconfig.EnableClientVersionCheck, true),
ValidSearchAttributes: dc.GetMapProperty(dynamicconfig.ValidSearchAttributes, searchattribute.GetDefaultTypeMap()),
SearchAttributesNumberOfKeysLimit: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.SearchAttributesNumberOfKeysLimit, 100),
SearchAttributesSizeOfValueLimit: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.SearchAttributesSizeOfValueLimit, 2*1024),
SearchAttributesTotalSizeLimit: dc.GetIntPropertyFilteredByNamespace(dynamicconfig.SearchAttributesTotalSizeLimit, 40*1024),
MinRetentionDays: dc.GetIntProperty(dynamicconfig.MinRetentionDays, namespace.MinRetentionDays),
VisibilityArchivalQueryMaxPageSize: dc.GetIntProperty(dynamicconfig.VisibilityArchivalQueryMaxPageSize, 10000),
DisallowQuery: dc.GetBoolPropertyFnWithNamespaceFilter(dynamicconfig.DisallowQuery, false),
SendRawWorkflowHistory: dc.GetBoolPropertyFnWithNamespaceFilter(dynamicconfig.SendRawWorkflowHistory, false),
DefaultWorkflowRetryPolicy: dc.GetMapPropertyFnWithNamespaceFilter(dynamicconfig.DefaultWorkflowRetryPolicy, common.GetDefaultRetryPolicyConfigOptions()),
DefaultWorkflowTaskTimeout: dc.GetDurationPropertyFilteredByNamespace(dynamicconfig.DefaultWorkflowTaskTimeout, common.DefaultWorkflowTaskTimeout),
EnableServerVersionCheck: dc.GetBoolProperty(dynamicconfig.EnableServerVersionCheck, os.Getenv("TEMPORAL_VERSION_CHECK_DISABLED") == ""),
EnableTokenNamespaceEnforcement: dc.GetBoolProperty(dynamicconfig.EnableTokenNamespaceEnforcement, false),
KeepAliveMinTime: dc.GetDurationProperty(dynamicconfig.KeepAliveMinTime, 10*time.Second),
KeepAlivePermitWithoutStream: dc.GetBoolProperty(dynamicconfig.KeepAlivePermitWithoutStream, true),
KeepAliveMaxConnectionIdle: dc.GetDurationProperty(dynamicconfig.KeepAliveMaxConnectionIdle, 2*time.Minute),
KeepAliveMaxConnectionAge: dc.GetDurationProperty(dynamicconfig.KeepAliveMaxConnectionAge, 5*time.Minute),
KeepAliveMaxConnectionAgeGrace: dc.GetDurationProperty(dynamicconfig.KeepAliveMaxConnectionAgeGrace, 70*time.Second),
KeepAliveTime: dc.GetDurationProperty(dynamicconfig.KeepAliveTime, 1*time.Minute),
KeepAliveTimeout: dc.GetDurationProperty(dynamicconfig.KeepAliveTimeout, 10*time.Second),
}
}
// Service represents the frontend service
type Service struct {
resource.Resource
status int32
config *Config
handler Handler
adminHandler *AdminHandler
versionChecker *VersionChecker
server *grpc.Server
serverMetricsReporter metrics.Reporter
sdkMetricsReporter metrics.Reporter
}
// NewService builds a new frontend service
func NewService(
params *resource.BootstrapParams,
) (*Service, error) {
isAdvancedVisExistInConfig := len(params.PersistenceConfig.AdvancedVisibilityStore) != 0
serviceConfig := NewConfig(dynamicconfig.NewCollection(params.DynamicConfigClient, params.Logger), params.PersistenceConfig.NumHistoryShards, isAdvancedVisExistInConfig)
params.PersistenceConfig.VisibilityConfig = &config.VisibilityConfig{
VisibilityListMaxQPS: serviceConfig.VisibilityListMaxQPS,
EnableSampling: serviceConfig.EnableVisibilitySampling,
ValidSearchAttributes: serviceConfig.ValidSearchAttributes,
}
visibilityManagerInitializer := func(
persistenceBean persistenceClient.Bean,
searchAttributesProvider searchattribute.Provider,
logger log.Logger,
) (persistence.VisibilityManager, error) {
visibilityFromDB := persistenceBean.GetVisibilityManager()
var visibilityFromES persistence.VisibilityManager
if params.ESConfig != nil {
visibilityIndexName := params.ESConfig.GetVisibilityIndex()
visibilityConfigForES := &config.VisibilityConfig{
MaxQPS: serviceConfig.PersistenceMaxQPS,
VisibilityListMaxQPS: serviceConfig.ESVisibilityListMaxQPS,
ESIndexMaxResultWindow: serviceConfig.ESIndexMaxResultWindow,
ValidSearchAttributes: serviceConfig.ValidSearchAttributes,
}
visibilityFromES = espersistence.NewVisibilityManager(visibilityIndexName, params.ESClient, visibilityConfigForES,
nil, params.MetricsClient, logger)
}
return persistence.NewVisibilityManagerWrapper(
visibilityFromDB,
visibilityFromES,
serviceConfig.EnableReadVisibilityFromES,
dynamicconfig.GetStringPropertyFn(common.AdvancedVisibilityWritingModeOff), // frontend visibility never write
), nil
}
serviceResource, err := resource.New(
params,
common.FrontendServiceName,
serviceConfig.PersistenceMaxQPS,
serviceConfig.PersistenceGlobalMaxQPS,
serviceConfig.ThrottledLogRPS,
visibilityManagerInitializer,
)
if err != nil {
return nil, err
}
var namespaceReplicationQueue persistence.NamespaceReplicationQueue
clusterMetadata := serviceResource.GetClusterMetadata()
if clusterMetadata.IsGlobalNamespaceEnabled() {
namespaceReplicationQueue = serviceResource.GetNamespaceReplicationQueue()
}
metricsInterceptor := interceptor.NewTelemetryInterceptor(
serviceResource.GetNamespaceCache(),
serviceResource.GetMetricsClient(),
metrics.FrontendAPIMetricsScopes(),
serviceResource.GetLogger(),
)
rateLimiterInterceptor := interceptor.NewRateLimitInterceptor(
configs.NewRequestToRateLimiter(func() float64 { return float64(serviceConfig.RPS()) }),
map[string]int{},
)
namespaceRateLimiterInterceptor := interceptor.NewNamespaceRateLimitInterceptor(
serviceResource.GetNamespaceCache(),
quotas.NewNamespaceRateLimiter(
func(req quotas.Request) quotas.RequestRateLimiter {
return configs.NewRequestToRateLimiter(func() float64 {
return namespaceRPS(
serviceConfig,
serviceResource.GetFrontendServiceResolver(),
req.Caller,
)
})
},
),
map[string]int{},
)
namespaceCountLimiterInterceptor := interceptor.NewNamespaceCountLimitInterceptor(
serviceResource.GetNamespaceCache(),
serviceConfig.MaxNamespaceCountPerInstance,
configs.ExecutionAPICountLimitOverride,
)
kep := keepalive.EnforcementPolicy{
MinTime: serviceConfig.KeepAliveMinTime(),
PermitWithoutStream: serviceConfig.KeepAlivePermitWithoutStream(),
}
var kp = keepalive.ServerParameters{
MaxConnectionIdle: serviceConfig.KeepAliveMaxConnectionIdle(),
MaxConnectionAge: serviceConfig.KeepAliveMaxConnectionAge(),
MaxConnectionAgeGrace: serviceConfig.KeepAliveMaxConnectionAgeGrace(),
Time: serviceConfig.KeepAliveTime(),
Timeout: serviceConfig.KeepAliveTimeout(),
}
grpcServerOptions, err := params.RPCFactory.GetFrontendGRPCServerOptions()
if err != nil {
params.Logger.Fatal("creating gRPC server options failed", tag.Error(err))
}
grpcServerOptions = append(
grpcServerOptions,
grpc.KeepaliveParams(kp),
grpc.KeepaliveEnforcementPolicy(kep),
grpc.ChainUnaryInterceptor(
rpc.ServiceErrorInterceptor,
metricsInterceptor.Intercept,
rateLimiterInterceptor.Intercept,
namespaceRateLimiterInterceptor.Intercept,
namespaceCountLimiterInterceptor.Intercept,
metrics.NewServerMetricsContextInjectorInterceptor(),
authorization.NewAuthorizationInterceptor(
params.ClaimMapper,
params.Authorizer,
serviceResource.GetMetricsClient(),
params.Logger,
),
),
)
wfHandler := NewWorkflowHandler(serviceResource, serviceConfig, namespaceReplicationQueue)
handler := NewDCRedirectionHandler(wfHandler, params.DCRedirectionPolicy)
return &Service{
Resource: serviceResource,
status: common.DaemonStatusInitialized,
config: serviceConfig,
server: grpc.NewServer(grpcServerOptions...),
handler: handler,
adminHandler: NewAdminHandler(serviceResource, params, serviceConfig),
versionChecker: NewVersionChecker(serviceConfig, params.MetricsClient, serviceResource.GetClusterMetadataManager()),
}, nil
}
// Start starts the service
func (s *Service) Start() {
if !atomic.CompareAndSwapInt32(&s.status, common.DaemonStatusInitialized, common.DaemonStatusStarted) {
return
}
logger := s.GetLogger()
logger.Info("frontend starting")
workflowservice.RegisterWorkflowServiceServer(s.server, s.handler)
healthpb.RegisterHealthServer(s.server, s.handler)
adminservice.RegisterAdminServiceServer(s.server, s.adminHandler)
reflection.Register(s.server)
// must start resource first
s.Resource.Start()
s.adminHandler.Start()
s.versionChecker.Start()
listener := s.GetGRPCListener()
logger.Info("Starting to serve on frontend listener")
if err := s.server.Serve(listener); err != nil {
logger.Fatal("Failed to serve on frontend listener", tag.Error(err))
}
}
// Stop stops the service
func (s *Service) Stop() {
logger := s.GetLogger()
if !atomic.CompareAndSwapInt32(&s.status, common.DaemonStatusStarted, common.DaemonStatusStopped) {
return
}
// initiate graceful shutdown:
// 1. Fail rpc health check, this will cause client side load balancer to stop forwarding requests to this node
// 2. wait for failure detection time
// 3. stop taking new requests by returning InternalServiceError
// 4. Wait for a second
// 5. Stop everything forcefully and return
requestDrainTime := common.MinDuration(time.Second, s.config.ShutdownDrainDuration())
failureDetectionTime := common.MaxDuration(0, s.config.ShutdownDrainDuration()-requestDrainTime)
logger.Info("ShutdownHandler: Updating rpc health status to ShuttingDown")
s.handler.UpdateHealthStatus(HealthStatusShuttingDown)
logger.Info("ShutdownHandler: Waiting for others to discover I am unhealthy")
time.Sleep(failureDetectionTime)
s.adminHandler.Stop()
s.versionChecker.Stop()
logger.Info("ShutdownHandler: Draining traffic")
time.Sleep(requestDrainTime)
// TODO: Change this to GracefulStop when integration tests are refactored.
s.server.Stop()
s.Resource.Stop()
if s.serverMetricsReporter != nil {
s.serverMetricsReporter.Stop(logger)
}
if s.sdkMetricsReporter != nil {
s.sdkMetricsReporter.Stop(logger)
}
logger.Info("frontend stopped")
}
func namespaceRPS(
config *Config,
frontendResolver membership.ServiceResolver,
namespace string,
) float64 {
hostRPS := float64(config.MaxNamespaceRPSPerInstance(namespace))
globalRPS := float64(config.GlobalNamespaceRPS(namespace))
hosts := float64(numFrontendHosts(frontendResolver))
rps := hostRPS + globalRPS*math.Exp((1.0-hosts)/8.0)
return rps
}
func numFrontendHosts(
frontendResolver membership.ServiceResolver,
) int {
defaultHosts := 1
if frontendResolver == nil {
return defaultHosts
}
ringSize := frontendResolver.MemberCount()
if ringSize < defaultHosts {
return defaultHosts
}
return ringSize
}