/
service.go
320 lines (274 loc) · 10.2 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
// Copyright (c) 2017 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 service
import (
"math/rand"
"os"
"sync/atomic"
"time"
"github.com/uber-go/tally"
"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
"go.uber.org/yarpc"
"github.com/uber/cadence/client"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/archiver"
"github.com/uber/cadence/common/archiver/provider"
"github.com/uber/cadence/common/authorization"
"github.com/uber/cadence/common/blobstore"
"github.com/uber/cadence/common/clock"
"github.com/uber/cadence/common/cluster"
"github.com/uber/cadence/common/config"
"github.com/uber/cadence/common/dynamicconfig"
es "github.com/uber/cadence/common/elasticsearch"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/log/tag"
"github.com/uber/cadence/common/membership"
"github.com/uber/cadence/common/messaging"
"github.com/uber/cadence/common/metrics"
"github.com/uber/cadence/common/persistence"
)
type (
// BootstrapParams holds the set of parameters
// needed to bootstrap a service
BootstrapParams struct {
Name string
InstanceID string
Logger log.Logger
ThrottledLogger log.Logger
MetricScope tally.Scope
MembershipFactory MembershipMonitorFactory
RPCFactory common.RPCFactory
PProfInitializer common.PProfInitializer
PersistenceConfig config.Persistence
ClusterMetadata cluster.Metadata
ReplicatorConfig config.Replicator
MetricsClient metrics.Client
MessagingClient messaging.Client
BlobstoreClient blobstore.Client
ESClient es.GenericClient
ESConfig *config.ElasticSearchConfig
DynamicConfig dynamicconfig.Client
DispatcherProvider client.DispatcherProvider
DCRedirectionPolicy config.DCRedirectionPolicy
PublicClient workflowserviceclient.Interface
ArchivalMetadata archiver.ArchivalMetadata
ArchiverProvider provider.ArchiverProvider
Authorizer authorization.Authorizer
}
// MembershipMonitorFactory provides a bootstrapped membership monitor
MembershipMonitorFactory interface {
// GetMembershipMonitor return a membership monitor
GetMembershipMonitor() (membership.Monitor, error)
}
// Service contains the objects specific to this service
serviceImpl struct {
status int32
sName string
hostName string
hostInfo *membership.HostInfo
dispatcher *yarpc.Dispatcher
membershipFactory MembershipMonitorFactory
membershipMonitor membership.Monitor
rpcFactory common.RPCFactory
pprofInitializer common.PProfInitializer
clientBean client.Bean
timeSource clock.TimeSource
numberOfHistoryShards int
logger log.Logger
throttledLogger log.Logger
metricsScope tally.Scope
runtimeMetricsReporter *metrics.RuntimeMetricsReporter
metricsClient metrics.Client
clusterMetadata cluster.Metadata
messagingClient messaging.Client
blobstoreClient blobstore.Client
dynamicCollection *dynamicconfig.Collection
dispatcherProvider client.DispatcherProvider
archivalMetadata archiver.ArchivalMetadata
archiverProvider provider.ArchiverProvider
serializer persistence.PayloadSerializer
}
)
var _ Service = (*serviceImpl)(nil)
// New instantiates a Service Instance
// TODO: have a better name for Service.
func New(params *BootstrapParams) Service {
sVice := &serviceImpl{
status: common.DaemonStatusInitialized,
sName: params.Name,
logger: params.Logger,
throttledLogger: params.ThrottledLogger,
rpcFactory: params.RPCFactory,
membershipFactory: params.MembershipFactory,
pprofInitializer: params.PProfInitializer,
timeSource: clock.NewRealTimeSource(),
metricsScope: params.MetricScope,
numberOfHistoryShards: params.PersistenceConfig.NumHistoryShards,
clusterMetadata: params.ClusterMetadata,
metricsClient: params.MetricsClient,
messagingClient: params.MessagingClient,
blobstoreClient: params.BlobstoreClient,
dispatcherProvider: params.DispatcherProvider,
dynamicCollection: dynamicconfig.NewCollection(
params.DynamicConfig,
params.Logger,
dynamicconfig.ClusterNameFilter(params.ClusterMetadata.GetCurrentClusterName()),
),
archivalMetadata: params.ArchivalMetadata,
archiverProvider: params.ArchiverProvider,
serializer: persistence.NewPayloadSerializer(),
}
sVice.runtimeMetricsReporter = metrics.NewRuntimeMetricsReporter(params.MetricScope, time.Minute, sVice.GetLogger(), params.InstanceID)
sVice.dispatcher = sVice.rpcFactory.GetDispatcher()
if sVice.dispatcher == nil {
sVice.logger.Fatal("Unable to create yarpc dispatcher")
}
// Get the host name and set it on the service. This is used for emitting metric with a tag for hostname
if hostName, err := os.Hostname(); err != nil {
sVice.logger.WithTags(tag.Error(err)).Fatal("Error getting hostname")
} else {
sVice.hostName = hostName
}
return sVice
}
// UpdateLoggerWithServiceName tag logging with service name from the top level
func (params *BootstrapParams) UpdateLoggerWithServiceName(name string) {
if params.Logger != nil {
params.Logger = params.Logger.WithTags(tag.Service(name))
}
if params.ThrottledLogger != nil {
params.ThrottledLogger = params.ThrottledLogger.WithTags(tag.Service(name))
}
}
// GetHostName returns the name of host running the service
func (h *serviceImpl) GetHostName() string {
return h.hostName
}
// Start starts a yarpc service
func (h *serviceImpl) Start() {
if !atomic.CompareAndSwapInt32(&h.status, common.DaemonStatusInitialized, common.DaemonStatusStarted) {
return
}
var err error
h.metricsScope.Counter(metrics.RestartCount).Inc(1)
h.runtimeMetricsReporter.Start()
if err := h.pprofInitializer.Start(); err != nil {
h.logger.WithTags(tag.Error(err)).Fatal("Failed to start pprof")
}
if err := h.dispatcher.Start(); err != nil {
h.logger.WithTags(tag.Error(err)).Fatal("Failed to start yarpc dispatcher")
}
h.membershipMonitor, err = h.membershipFactory.GetMembershipMonitor()
if err != nil {
h.logger.WithTags(tag.Error(err)).Fatal("Membership monitor creation failed")
}
h.membershipMonitor.Start()
hostInfo, err := h.membershipMonitor.WhoAmI()
if err != nil {
h.logger.WithTags(tag.Error(err)).Fatal("failed to get host info from membership monitor")
}
h.hostInfo = hostInfo
h.clientBean, err = client.NewClientBean(
client.NewRPCClientFactory(h.rpcFactory, h.membershipMonitor, h.metricsClient, h.dynamicCollection, h.numberOfHistoryShards, h.logger),
h.dispatcherProvider,
h.clusterMetadata,
)
if err != nil {
h.logger.WithTags(tag.Error(err)).Fatal("fail to initialize client bean")
}
// The service is now started up
h.logger.Info("service started")
// seed the random generator once for this service
rand.Seed(time.Now().UTC().UnixNano())
}
// Stop closes the associated transport
func (h *serviceImpl) Stop() {
if !atomic.CompareAndSwapInt32(&h.status, common.DaemonStatusStarted, common.DaemonStatusStopped) {
return
}
if h.membershipMonitor != nil {
h.membershipMonitor.Stop()
}
if h.dispatcher != nil {
h.dispatcher.Stop() //nolint:errcheck
}
h.runtimeMetricsReporter.Stop()
}
func (h *serviceImpl) GetLogger() log.Logger {
return h.logger
}
func (h *serviceImpl) GetThrottledLogger() log.Logger {
return h.throttledLogger
}
func (h *serviceImpl) GetMetricsClient() metrics.Client {
return h.metricsClient
}
func (h *serviceImpl) GetClientBean() client.Bean {
return h.clientBean
}
func (h *serviceImpl) GetTimeSource() clock.TimeSource {
return h.timeSource
}
func (h *serviceImpl) GetMembershipMonitor() membership.Monitor {
return h.membershipMonitor
}
func (h *serviceImpl) GetHostInfo() *membership.HostInfo {
return h.hostInfo
}
func (h *serviceImpl) GetDispatcher() *yarpc.Dispatcher {
return h.dispatcher
}
// GetClusterMetadata returns the service cluster metadata
func (h *serviceImpl) GetClusterMetadata() cluster.Metadata {
return h.clusterMetadata
}
// GetMessagingClient returns the messaging client against Kafka
func (h *serviceImpl) GetMessagingClient() messaging.Client {
return h.messagingClient
}
func (h *serviceImpl) GetBlobstoreClient() blobstore.Client {
return h.blobstoreClient
}
func (h *serviceImpl) GetArchivalMetadata() archiver.ArchivalMetadata {
return h.archivalMetadata
}
func (h *serviceImpl) GetArchiverProvider() provider.ArchiverProvider {
return h.archiverProvider
}
func (h *serviceImpl) GetPayloadSerializer() persistence.PayloadSerializer {
return h.serializer
}
// GetMetricsServiceIdx returns the metrics name
func GetMetricsServiceIdx(serviceName string, logger log.Logger) metrics.ServiceIdx {
switch serviceName {
case common.FrontendServiceName:
return metrics.Frontend
case common.HistoryServiceName:
return metrics.History
case common.MatchingServiceName:
return metrics.Matching
case common.WorkerServiceName:
return metrics.Worker
default:
logger.Fatal("Unknown service name for metrics!")
}
// this should never happen!
return metrics.NumServices
}