blob: 57d00cf99a48d14663b49759da75c571be89373a [file] [log] [blame]
khenaidoob9203542018-09-17 22:56:37 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
npujar1d86a522019-11-14 17:11:16 +053016
khenaidoob9203542018-09-17 22:56:37 -040017package core
18
19import (
20 "context"
Thomas Lee Se5a44012019-11-07 20:32:24 +053021 "fmt"
Scott Baker2d87ee32020-03-03 13:04:01 -080022 "sync"
npujar1d86a522019-11-14 17:11:16 +053023 "time"
24
sbarbari17d7e222019-11-05 10:02:29 -050025 "github.com/opencord/voltha-go/db/model"
khenaidoob9203542018-09-17 22:56:37 -040026 "github.com/opencord/voltha-go/rw_core/config"
serkant.uluderya2ae470f2020-01-21 11:13:09 -080027 "github.com/opencord/voltha-lib-go/v3/pkg/db"
28 "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
29 grpcserver "github.com/opencord/voltha-lib-go/v3/pkg/grpc"
30 "github.com/opencord/voltha-lib-go/v3/pkg/kafka"
31 "github.com/opencord/voltha-lib-go/v3/pkg/log"
32 "github.com/opencord/voltha-lib-go/v3/pkg/probe"
33 "github.com/opencord/voltha-protos/v3/go/voltha"
khenaidoob9203542018-09-17 22:56:37 -040034 "google.golang.org/grpc"
khenaidoob3244212019-08-27 14:32:27 -040035 "google.golang.org/grpc/codes"
36 "google.golang.org/grpc/status"
khenaidoob9203542018-09-17 22:56:37 -040037)
38
npujar1d86a522019-11-14 17:11:16 +053039// Core represent read,write core attributes
khenaidoob9203542018-09-17 22:56:37 -040040type Core struct {
npujar1d86a522019-11-14 17:11:16 +053041 instanceID string
khenaidoob9203542018-09-17 22:56:37 -040042 deviceMgr *DeviceManager
43 logicalDeviceMgr *LogicalDeviceManager
44 grpcServer *grpcserver.GrpcServer
Richard Jankowskidbab94a2018-12-06 16:20:25 -050045 grpcNBIAPIHandler *APIHandler
khenaidoo2c6a0992019-04-29 13:46:56 -040046 adapterMgr *AdapterManager
khenaidoob9203542018-09-17 22:56:37 -040047 config *config.RWCoreFlags
npujar467fe752020-01-16 20:17:45 +053048 kmp kafka.InterContainerProxy
khenaidoo92e62c52018-10-03 14:02:54 -040049 clusterDataRoot model.Root
50 localDataRoot model.Root
khenaidoob9203542018-09-17 22:56:37 -040051 clusterDataProxy *model.Proxy
52 localDataProxy *model.Proxy
Scott Baker2d87ee32020-03-03 13:04:01 -080053 exitChannel chan struct{}
54 stopOnce sync.Once
Richard Jankowskie4d77662018-10-17 13:53:21 -040055 kvClient kvstore.Client
Girish Kumar4d3887d2019-11-22 14:22:05 +000056 backend db.Backend
khenaidoo43c82122018-11-22 18:38:28 -050057 kafkaClient kafka.Client
khenaidoo2c6a0992019-04-29 13:46:56 -040058 deviceOwnership *DeviceOwnership
khenaidoob9203542018-09-17 22:56:37 -040059}
60
npujar1d86a522019-11-14 17:11:16 +053061// NewCore creates instance of rw core
Thomas Lee Se5a44012019-11-07 20:32:24 +053062func NewCore(ctx context.Context, id string, cf *config.RWCoreFlags, kvClient kvstore.Client, kafkaClient kafka.Client) *Core {
khenaidoob9203542018-09-17 22:56:37 -040063 var core Core
npujar1d86a522019-11-14 17:11:16 +053064 core.instanceID = id
Scott Baker2d87ee32020-03-03 13:04:01 -080065 core.exitChannel = make(chan struct{})
khenaidoob9203542018-09-17 22:56:37 -040066 core.config = cf
Richard Jankowskie4d77662018-10-17 13:53:21 -040067 core.kvClient = kvClient
khenaidoo43c82122018-11-22 18:38:28 -050068 core.kafkaClient = kafkaClient
Richard Jankowskie4d77662018-10-17 13:53:21 -040069
Girish Kumar4d3887d2019-11-22 14:22:05 +000070 // Configure backend to push Liveness Status at least every (cf.LiveProbeInterval / 2) seconds
71 // so as to avoid trigger of Liveness check (due to Liveness timeout) when backend is alive
72 livenessChannelInterval := cf.LiveProbeInterval / 2
73
Richard Jankowskie4d77662018-10-17 13:53:21 -040074 // Setup the KV store
Girish Kumar4d3887d2019-11-22 14:22:05 +000075 core.backend = db.Backend{
76 Client: kvClient,
77 StoreType: cf.KVStoreType,
78 Host: cf.KVStoreHost,
79 Port: cf.KVStorePort,
80 Timeout: cf.KVStoreTimeout,
81 LivenessChannelInterval: livenessChannelInterval,
82 PathPrefix: cf.KVStoreDataPrefix}
83 core.clusterDataRoot = model.NewRoot(&voltha.Voltha{}, &core.backend)
84 core.localDataRoot = model.NewRoot(&voltha.CoreInstance{}, &core.backend)
khenaidoob9203542018-09-17 22:56:37 -040085 return &core
86}
87
npujar1d86a522019-11-14 17:11:16 +053088// Start brings up core services
Thomas Lee Se5a44012019-11-07 20:32:24 +053089func (core *Core) Start(ctx context.Context) error {
David K. Bainbridgeb4a9ab02019-09-20 15:12:16 -070090
91 // If the context has a probe then fetch it and register our services
92 var p *probe.Probe
93 if value := ctx.Value(probe.ProbeContextKey); value != nil {
94 if _, ok := value.(*probe.Probe); ok {
95 p = value.(*probe.Probe)
96 p.RegisterService(
97 "message-bus",
98 "kv-store",
99 "device-manager",
100 "logical-device-manager",
101 "adapter-manager",
102 "grpc-service",
103 )
104 }
105 }
106
Girish Kumarf56a4682020-03-20 20:07:46 +0000107 logger.Info("starting-core-services", log.Fields{"coreId": core.instanceID})
khenaidoob3244212019-08-27 14:32:27 -0400108
109 // Wait until connection to KV Store is up
110 if err := core.waitUntilKVStoreReachableOrMaxTries(ctx, core.config.MaxConnectionRetries, core.config.ConnectionRetryInterval); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000111 logger.Fatal("Unable-to-connect-to-KV-store")
khenaidoob3244212019-08-27 14:32:27 -0400112 }
David K. Bainbridgeb4a9ab02019-09-20 15:12:16 -0700113 if p != nil {
114 p.UpdateStatus("kv-store", probe.ServiceStatusRunning)
115 }
Thomas Lee Se5a44012019-11-07 20:32:24 +0530116 var err error
117
npujar467fe752020-01-16 20:17:45 +0530118 core.clusterDataProxy, err = core.clusterDataRoot.CreateProxy(ctx, "/", false)
Thomas Lee Se5a44012019-11-07 20:32:24 +0530119 if err != nil {
120 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
121 return fmt.Errorf("Failed to create cluster data proxy")
122 }
npujar467fe752020-01-16 20:17:45 +0530123 core.localDataProxy, err = core.localDataRoot.CreateProxy(ctx, "/", false)
Thomas Lee Se5a44012019-11-07 20:32:24 +0530124 if err != nil {
125 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
126 return fmt.Errorf("Failed to create local data proxy")
127 }
khenaidoob3244212019-08-27 14:32:27 -0400128
Scott Bakeree6a0872019-10-29 15:59:52 -0700129 // core.kmp must be created before deviceMgr and adapterMgr, as they will make
130 // private copies of the poiner to core.kmp.
npujar467fe752020-01-16 20:17:45 +0530131 core.initKafkaManager(ctx)
khenaidoob3244212019-08-27 14:32:27 -0400132
Girish Kumarf56a4682020-03-20 20:07:46 +0000133 logger.Debugw("values", log.Fields{"kmp": core.kmp})
Richard Jankowski199fd862019-03-18 14:49:51 -0400134 core.deviceMgr = newDeviceManager(core)
Kent Hagerman16ce36a2019-12-17 13:40:53 -0500135 core.adapterMgr = newAdapterManager(core.clusterDataProxy, core.instanceID, core.kafkaClient, core.deviceMgr)
khenaidooba6b6c42019-08-02 09:11:56 -0400136 core.deviceMgr.adapterMgr = core.adapterMgr
khenaidoo2c6a0992019-04-29 13:46:56 -0400137 core.logicalDeviceMgr = newLogicalDeviceManager(core, core.deviceMgr, core.kmp, core.clusterDataProxy, core.config.DefaultCoreTimeout)
khenaidoo54e0ddf2019-02-27 16:21:33 -0500138
Scott Bakeree6a0872019-10-29 15:59:52 -0700139 // Start the KafkaManager. This must be done after the deviceMgr, adapterMgr, and
140 // logicalDeviceMgr have been created, as once the kmp is started, it will register
141 // the above with the kmp.
142
143 go core.startKafkaManager(ctx,
144 core.config.ConnectionRetryInterval,
145 core.config.LiveProbeInterval,
146 core.config.NotLiveProbeInterval)
khenaidoob3244212019-08-27 14:32:27 -0400147
khenaidoob9203542018-09-17 22:56:37 -0400148 go core.startDeviceManager(ctx)
149 go core.startLogicalDeviceManager(ctx)
150 go core.startGRPCService(ctx)
khenaidoo21d51152019-02-01 13:48:37 -0500151 go core.startAdapterManager(ctx)
Girish Kumar4d3887d2019-11-22 14:22:05 +0000152 go core.monitorKvstoreLiveness(ctx)
khenaidoob9203542018-09-17 22:56:37 -0400153
khenaidoo1ce37ad2019-03-24 22:07:24 -0400154 // Setup device ownership context
npujar1d86a522019-11-14 17:11:16 +0530155 core.deviceOwnership = NewDeviceOwnership(core.instanceID, core.kvClient, core.deviceMgr, core.logicalDeviceMgr,
khenaidoo1ce37ad2019-03-24 22:07:24 -0400156 "service/voltha/owns_device", 10)
157
Girish Kumarf56a4682020-03-20 20:07:46 +0000158 logger.Info("core-services-started")
Thomas Lee Se5a44012019-11-07 20:32:24 +0530159 return nil
khenaidoob9203542018-09-17 22:56:37 -0400160}
161
npujar1d86a522019-11-14 17:11:16 +0530162// Stop brings down core services
khenaidoob9203542018-09-17 22:56:37 -0400163func (core *Core) Stop(ctx context.Context) {
Scott Baker2d87ee32020-03-03 13:04:01 -0800164 core.stopOnce.Do(func() {
Girish Kumarf56a4682020-03-20 20:07:46 +0000165 logger.Info("stopping-adaptercore")
Scott Baker2d87ee32020-03-03 13:04:01 -0800166 // Signal to the KVStoreMonitor that we are stopping.
167 close(core.exitChannel)
168 // Stop all the started services
169 if core.grpcServer != nil {
170 core.grpcServer.Stop()
171 }
172 if core.logicalDeviceMgr != nil {
173 core.logicalDeviceMgr.stop(ctx)
174 }
175 if core.deviceMgr != nil {
176 core.deviceMgr.stop(ctx)
177 }
178 if core.kmp != nil {
179 core.kmp.Stop()
180 }
Girish Kumarf56a4682020-03-20 20:07:46 +0000181 logger.Info("adaptercore-stopped")
Scott Baker2d87ee32020-03-03 13:04:01 -0800182 })
khenaidoob9203542018-09-17 22:56:37 -0400183}
184
khenaidoo631fe542019-05-31 15:44:43 -0400185//startGRPCService creates the grpc service handlers, registers it to the grpc server and starts the server
khenaidoob9203542018-09-17 22:56:37 -0400186func (core *Core) startGRPCService(ctx context.Context) {
187 // create an insecure gserver server
Scott Bakeree6a0872019-10-29 15:59:52 -0700188 core.grpcServer = grpcserver.NewGrpcServer(core.config.GrpcHost, core.config.GrpcPort, nil, false, probe.GetProbeFromContext(ctx))
Girish Kumarf56a4682020-03-20 20:07:46 +0000189 logger.Info("grpc-server-created")
khenaidoob9203542018-09-17 22:56:37 -0400190
khenaidoo54e0ddf2019-02-27 16:21:33 -0500191 core.grpcNBIAPIHandler = NewAPIHandler(core)
Girish Kumarf56a4682020-03-20 20:07:46 +0000192 logger.Infow("grpc-handler", log.Fields{"core_binding_key": core.config.CoreBindingKey})
Richard Jankowskidbab94a2018-12-06 16:20:25 -0500193 core.logicalDeviceMgr.setGrpcNbiHandler(core.grpcNBIAPIHandler)
khenaidoob9203542018-09-17 22:56:37 -0400194 // Create a function to register the core GRPC service with the GRPC server
195 f := func(gs *grpc.Server) {
196 voltha.RegisterVolthaServiceServer(
197 gs,
Richard Jankowskidbab94a2018-12-06 16:20:25 -0500198 core.grpcNBIAPIHandler,
khenaidoob9203542018-09-17 22:56:37 -0400199 )
200 }
201
202 core.grpcServer.AddService(f)
Girish Kumarf56a4682020-03-20 20:07:46 +0000203 logger.Info("grpc-service-added")
khenaidoob9203542018-09-17 22:56:37 -0400204
David K. Bainbridgeb4a9ab02019-09-20 15:12:16 -0700205 /*
206 * Start the GRPC server
207 *
208 * This is a bit sub-optimal here as the grpcServer.Start call does not return (blocks)
209 * until something fails, but we want to send a "start" status update. As written this
210 * means that we are actually sending the "start" status update before the server is
211 * started, which means it is possible that the status is "running" before it actually is.
212 *
213 * This means that there is a small window in which the core could return its status as
214 * ready, when it really isn't.
215 */
216 probe.UpdateStatusFromContext(ctx, "grpc-service", probe.ServiceStatusRunning)
Girish Kumarf56a4682020-03-20 20:07:46 +0000217 logger.Info("grpc-server-started")
npujar467fe752020-01-16 20:17:45 +0530218 core.grpcServer.Start(ctx)
David K. Bainbridgeb4a9ab02019-09-20 15:12:16 -0700219 probe.UpdateStatusFromContext(ctx, "grpc-service", probe.ServiceStatusStopped)
khenaidoob9203542018-09-17 22:56:37 -0400220}
221
Scott Bakeree6a0872019-10-29 15:59:52 -0700222// Initialize the kafka manager, but we will start it later
npujar467fe752020-01-16 20:17:45 +0530223func (core *Core) initKafkaManager(ctx context.Context) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000224 logger.Infow("initialize-kafka-manager", log.Fields{"host": core.config.KafkaAdapterHost,
khenaidoob9203542018-09-17 22:56:37 -0400225 "port": core.config.KafkaAdapterPort, "topic": core.config.CoreTopic})
Scott Bakeree6a0872019-10-29 15:59:52 -0700226
227 probe.UpdateStatusFromContext(ctx, "message-bus", probe.ServiceStatusPreparing)
228
229 // create the proxy
npujar467fe752020-01-16 20:17:45 +0530230 core.kmp = kafka.NewInterContainerProxy(
khenaidoo43c82122018-11-22 18:38:28 -0500231 kafka.InterContainerHost(core.config.KafkaAdapterHost),
232 kafka.InterContainerPort(core.config.KafkaAdapterPort),
233 kafka.MsgClient(core.kafkaClient),
khenaidoo79232702018-12-04 11:00:41 -0500234 kafka.DefaultTopic(&kafka.Topic{Name: core.config.CoreTopic}),
npujar467fe752020-01-16 20:17:45 +0530235 kafka.DeviceDiscoveryTopic(&kafka.Topic{Name: core.config.AffinityRouterTopic}))
Scott Bakeree6a0872019-10-29 15:59:52 -0700236
237 probe.UpdateStatusFromContext(ctx, "message-bus", probe.ServiceStatusPrepared)
Scott Bakeree6a0872019-10-29 15:59:52 -0700238}
239
240/*
241 * KafkaMonitorThread
242 *
npujar1d86a522019-11-14 17:11:16 +0530243 * Responsible for starting the Kafka Interadapter Proxy and monitoring its liveness
Scott Bakeree6a0872019-10-29 15:59:52 -0700244 * state.
245 *
246 * Any producer that fails to send will cause KafkaInterContainerProxy to
247 * post a false event on its liveness channel. Any producer that succeeds in sending
248 * will cause KafkaInterContainerProxy to post a true event on its liveness
npujar1d86a522019-11-14 17:11:16 +0530249 * channel. Group receivers also update liveness state, and a receiver will typically
Scott Bakeree6a0872019-10-29 15:59:52 -0700250 * indicate a loss of liveness within 3-5 seconds of Kafka going down. Receivers
251 * only indicate restoration of liveness if a message is received. During normal
252 * operation, messages will be routinely produced and received, automatically
253 * indicating liveness state. These routine liveness indications are rate-limited
254 * inside sarama_client.
255 *
256 * This thread monitors the status of KafkaInterContainerProxy's liveness and pushes
257 * that state to the core's readiness probes. If no liveness event has been seen
258 * within a timeout, then the thread will make an attempt to produce a "liveness"
259 * message, which will in turn trigger a liveness event on the liveness channel, true
260 * or false depending on whether the attempt succeeded.
261 *
262 * The gRPC server in turn monitors the state of the readiness probe and will
263 * start issuing UNAVAILABLE response while the probe is not ready.
264 *
265 * startupRetryInterval -- interval between attempts to start
266 * liveProbeInterval -- interval between liveness checks when in a live state
267 * notLiveProbeInterval -- interval between liveness checks when in a notLive state
268 *
269 * liveProbeInterval and notLiveProbeInterval can be configured separately,
270 * though the current default is that both are set to 60 seconds.
271 */
272
Girish Kumar4d3887d2019-11-22 14:22:05 +0000273func (core *Core) startKafkaManager(ctx context.Context, startupRetryInterval time.Duration, liveProbeInterval time.Duration, notLiveProbeInterval time.Duration) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000274 logger.Infow("starting-kafka-manager-thread", log.Fields{"host": core.config.KafkaAdapterHost,
Scott Bakeree6a0872019-10-29 15:59:52 -0700275 "port": core.config.KafkaAdapterPort, "topic": core.config.CoreTopic})
276
277 started := false
278 for !started {
279 // If we haven't started yet, then try to start
Girish Kumarf56a4682020-03-20 20:07:46 +0000280 logger.Infow("starting-kafka-proxy", log.Fields{})
Scott Bakeree6a0872019-10-29 15:59:52 -0700281 if err := core.kmp.Start(); err != nil {
282 // We failed to start. Delay and then try again later.
283 // Don't worry about liveness, as we can't be live until we've started.
284 probe.UpdateStatusFromContext(ctx, "message-bus", probe.ServiceStatusNotReady)
Girish Kumarf56a4682020-03-20 20:07:46 +0000285 logger.Infow("error-starting-kafka-messaging-proxy", log.Fields{"error": err})
Girish Kumar4d3887d2019-11-22 14:22:05 +0000286 time.Sleep(startupRetryInterval)
khenaidoob3244212019-08-27 14:32:27 -0400287 } else {
Scott Bakeree6a0872019-10-29 15:59:52 -0700288 // We started. We only need to do this once.
289 // Next we'll fall through and start checking liveness.
Girish Kumarf56a4682020-03-20 20:07:46 +0000290 logger.Infow("started-kafka-proxy", log.Fields{})
Scott Bakeree6a0872019-10-29 15:59:52 -0700291
292 // cannot do this until after the kmp is started
npujar1d86a522019-11-14 17:11:16 +0530293 if err := core.registerAdapterRequestHandlers(ctx, core.instanceID, core.deviceMgr, core.logicalDeviceMgr, core.adapterMgr, core.clusterDataProxy, core.localDataProxy); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000294 logger.Fatal("Failure-registering-adapterRequestHandler")
Scott Bakeree6a0872019-10-29 15:59:52 -0700295 }
296
297 started = true
khenaidoob3244212019-08-27 14:32:27 -0400298 }
khenaidoob9203542018-09-17 22:56:37 -0400299 }
Scott Bakeree6a0872019-10-29 15:59:52 -0700300
Girish Kumarf56a4682020-03-20 20:07:46 +0000301 logger.Info("started-kafka-message-proxy")
Scott Bakeree6a0872019-10-29 15:59:52 -0700302
303 livenessChannel := core.kmp.EnableLivenessChannel(true)
304
Girish Kumarf56a4682020-03-20 20:07:46 +0000305 logger.Info("enabled-kafka-liveness-channel")
Scott Bakeree6a0872019-10-29 15:59:52 -0700306
Girish Kumar4d3887d2019-11-22 14:22:05 +0000307 timeout := liveProbeInterval
Scott Bakeree6a0872019-10-29 15:59:52 -0700308 for {
309 timeoutTimer := time.NewTimer(timeout)
310 select {
311 case liveness := <-livenessChannel:
Girish Kumarf56a4682020-03-20 20:07:46 +0000312 logger.Infow("kafka-manager-thread-liveness-event", log.Fields{"liveness": liveness})
Scott Bakeree6a0872019-10-29 15:59:52 -0700313 // there was a state change in Kafka liveness
314 if !liveness {
315 probe.UpdateStatusFromContext(ctx, "message-bus", probe.ServiceStatusNotReady)
316
317 if core.grpcServer != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000318 logger.Info("kafka-manager-thread-set-server-notready")
Scott Bakeree6a0872019-10-29 15:59:52 -0700319 }
320
321 // retry frequently while life is bad
Girish Kumar4d3887d2019-11-22 14:22:05 +0000322 timeout = notLiveProbeInterval
Scott Bakeree6a0872019-10-29 15:59:52 -0700323 } else {
324 probe.UpdateStatusFromContext(ctx, "message-bus", probe.ServiceStatusRunning)
325
326 if core.grpcServer != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000327 logger.Info("kafka-manager-thread-set-server-ready")
Scott Bakeree6a0872019-10-29 15:59:52 -0700328 }
329
330 // retry infrequently while life is good
Girish Kumar4d3887d2019-11-22 14:22:05 +0000331 timeout = liveProbeInterval
Scott Bakeree6a0872019-10-29 15:59:52 -0700332 }
333 if !timeoutTimer.Stop() {
334 <-timeoutTimer.C
335 }
336 case <-timeoutTimer.C:
Girish Kumarf56a4682020-03-20 20:07:46 +0000337 logger.Info("kafka-proxy-liveness-recheck")
Scott Bakeree6a0872019-10-29 15:59:52 -0700338 // send the liveness probe in a goroutine; we don't want to deadlock ourselves as
339 // the liveness probe may wait (and block) writing to our channel.
340 go func() {
341 err := core.kmp.SendLiveness()
342 if err != nil {
343 // Catch possible error case if sending liveness after Sarama has been stopped.
Girish Kumarf56a4682020-03-20 20:07:46 +0000344 logger.Warnw("error-kafka-send-liveness", log.Fields{"error": err})
Scott Bakeree6a0872019-10-29 15:59:52 -0700345 }
346 }()
347 }
348 }
khenaidoob9203542018-09-17 22:56:37 -0400349}
350
khenaidoob3244212019-08-27 14:32:27 -0400351// waitUntilKVStoreReachableOrMaxTries will wait until it can connect to a KV store or until maxtries has been reached
Girish Kumar4d3887d2019-11-22 14:22:05 +0000352func (core *Core) waitUntilKVStoreReachableOrMaxTries(ctx context.Context, maxRetries int, retryInterval time.Duration) error {
Girish Kumarf56a4682020-03-20 20:07:46 +0000353 logger.Infow("verifying-KV-store-connectivity", log.Fields{"host": core.config.KVStoreHost,
khenaidoob3244212019-08-27 14:32:27 -0400354 "port": core.config.KVStorePort, "retries": maxRetries, "retryInterval": retryInterval})
khenaidoob3244212019-08-27 14:32:27 -0400355 count := 0
356 for {
npujar467fe752020-01-16 20:17:45 +0530357 if !core.kvClient.IsConnectionUp(ctx) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000358 logger.Info("KV-store-unreachable")
khenaidoob3244212019-08-27 14:32:27 -0400359 if maxRetries != -1 {
360 if count >= maxRetries {
361 return status.Error(codes.Unavailable, "kv store unreachable")
362 }
363 }
npujar1d86a522019-11-14 17:11:16 +0530364 count++
khenaidoob3244212019-08-27 14:32:27 -0400365 // Take a nap before retrying
Girish Kumar4d3887d2019-11-22 14:22:05 +0000366 time.Sleep(retryInterval)
Girish Kumarf56a4682020-03-20 20:07:46 +0000367 logger.Infow("retry-KV-store-connectivity", log.Fields{"retryCount": count, "maxRetries": maxRetries, "retryInterval": retryInterval})
khenaidoob3244212019-08-27 14:32:27 -0400368
369 } else {
370 break
371 }
372 }
Girish Kumarf56a4682020-03-20 20:07:46 +0000373 logger.Info("KV-store-reachable")
khenaidoob3244212019-08-27 14:32:27 -0400374 return nil
375}
376
npujar1d86a522019-11-14 17:11:16 +0530377func (core *Core) registerAdapterRequestHandlers(ctx context.Context, coreInstanceID string, dMgr *DeviceManager,
khenaidoo297cd252019-02-07 22:10:23 -0500378 ldMgr *LogicalDeviceManager, aMgr *AdapterManager, cdProxy *model.Proxy, ldProxy *model.Proxy,
khenaidoo54e0ddf2019-02-27 16:21:33 -0500379) error {
npujar1d86a522019-11-14 17:11:16 +0530380 requestProxy := NewAdapterRequestHandlerProxy(core, coreInstanceID, dMgr, ldMgr, aMgr, cdProxy, ldProxy,
khenaidoo297cd252019-02-07 22:10:23 -0500381 core.config.InCompetingMode, core.config.LongRunningRequestTimeout, core.config.DefaultRequestTimeout)
khenaidoob9203542018-09-17 22:56:37 -0400382
khenaidoo54e0ddf2019-02-27 16:21:33 -0500383 // Register the broadcast topic to handle any core-bound broadcast requests
384 if err := core.kmp.SubscribeWithRequestHandlerInterface(kafka.Topic{Name: core.config.CoreTopic}, requestProxy); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000385 logger.Fatalw("Failed-registering-broadcast-handler", log.Fields{"topic": core.config.CoreTopic})
khenaidoo54e0ddf2019-02-27 16:21:33 -0500386 return err
387 }
388
Kent Hagermana6d0c362019-07-30 12:50:21 -0400389 // Register the core-pair topic to handle core-bound requests destined to the core pair
390 if err := core.kmp.SubscribeWithDefaultRequestHandler(kafka.Topic{Name: core.config.CorePairTopic}, kafka.OffsetNewest); err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000391 logger.Fatalw("Failed-registering-pair-handler", log.Fields{"topic": core.config.CorePairTopic})
Kent Hagermana6d0c362019-07-30 12:50:21 -0400392 return err
393 }
394
Girish Kumarf56a4682020-03-20 20:07:46 +0000395 logger.Info("request-handler-registered")
khenaidoob9203542018-09-17 22:56:37 -0400396 return nil
397}
398
399func (core *Core) startDeviceManager(ctx context.Context) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000400 logger.Info("DeviceManager-Starting...")
khenaidoo4d4802d2018-10-04 21:59:49 -0400401 core.deviceMgr.start(ctx, core.logicalDeviceMgr)
Girish Kumarf56a4682020-03-20 20:07:46 +0000402 logger.Info("DeviceManager-Started")
khenaidoob9203542018-09-17 22:56:37 -0400403}
404
405func (core *Core) startLogicalDeviceManager(ctx context.Context) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000406 logger.Info("Logical-DeviceManager-Starting...")
khenaidoo4d4802d2018-10-04 21:59:49 -0400407 core.logicalDeviceMgr.start(ctx)
Girish Kumarf56a4682020-03-20 20:07:46 +0000408 logger.Info("Logical-DeviceManager-Started")
khenaidoob9203542018-09-17 22:56:37 -0400409}
khenaidoo21d51152019-02-01 13:48:37 -0500410
411func (core *Core) startAdapterManager(ctx context.Context) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000412 logger.Info("Adapter-Manager-Starting...")
Thomas Lee Se5a44012019-11-07 20:32:24 +0530413 err := core.adapterMgr.start(ctx)
414 if err != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000415 logger.Fatalf("failed-to-start-adapter-manager: error %v ", err)
Thomas Lee Se5a44012019-11-07 20:32:24 +0530416 }
Girish Kumarf56a4682020-03-20 20:07:46 +0000417 logger.Info("Adapter-Manager-Started")
William Kurkiandaa6bb22019-03-07 12:26:28 -0500418}
Girish Kumar4d3887d2019-11-22 14:22:05 +0000419
420/*
421* Thread to monitor kvstore Liveness (connection status)
422*
423* This function constantly monitors Liveness State of kvstore as reported
424* periodically by backend and updates the Status of kv-store service registered
425* with rw_core probe.
426*
427* If no liveness event has been seen within a timeout, then the thread will
428* perform a "liveness" check attempt, which will in turn trigger a liveness event on
429* the liveness channel, true or false depending on whether the attempt succeeded.
430*
431* The gRPC server in turn monitors the state of the readiness probe and will
432* start issuing UNAVAILABLE response while the probe is not ready.
433 */
434func (core *Core) monitorKvstoreLiveness(ctx context.Context) {
Girish Kumarf56a4682020-03-20 20:07:46 +0000435 logger.Info("start-monitoring-kvstore-liveness")
Girish Kumar4d3887d2019-11-22 14:22:05 +0000436
437 // Instruct backend to create Liveness channel for transporting state updates
438 livenessChannel := core.backend.EnableLivenessChannel()
439
Girish Kumarf56a4682020-03-20 20:07:46 +0000440 logger.Debug("enabled-kvstore-liveness-channel")
Girish Kumar4d3887d2019-11-22 14:22:05 +0000441
442 // Default state for kvstore is alive for rw_core
443 timeout := core.config.LiveProbeInterval
Scott Baker2d87ee32020-03-03 13:04:01 -0800444loop:
Girish Kumar4d3887d2019-11-22 14:22:05 +0000445 for {
446 timeoutTimer := time.NewTimer(timeout)
447 select {
448
449 case liveness := <-livenessChannel:
Girish Kumarf56a4682020-03-20 20:07:46 +0000450 logger.Debugw("received-liveness-change-notification", log.Fields{"liveness": liveness})
Girish Kumar4d3887d2019-11-22 14:22:05 +0000451
452 if !liveness {
453 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
454
455 if core.grpcServer != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000456 logger.Info("kvstore-set-server-notready")
Girish Kumar4d3887d2019-11-22 14:22:05 +0000457 }
458
459 timeout = core.config.NotLiveProbeInterval
460
461 } else {
462 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusRunning)
463
464 if core.grpcServer != nil {
Girish Kumarf56a4682020-03-20 20:07:46 +0000465 logger.Info("kvstore-set-server-ready")
Girish Kumar4d3887d2019-11-22 14:22:05 +0000466 }
467
468 timeout = core.config.LiveProbeInterval
469 }
470
471 if !timeoutTimer.Stop() {
472 <-timeoutTimer.C
473 }
474
Scott Baker2d87ee32020-03-03 13:04:01 -0800475 case <-core.exitChannel:
476 break loop
477
Girish Kumar4d3887d2019-11-22 14:22:05 +0000478 case <-timeoutTimer.C:
Girish Kumarf56a4682020-03-20 20:07:46 +0000479 logger.Info("kvstore-perform-liveness-check-on-timeout")
Girish Kumar4d3887d2019-11-22 14:22:05 +0000480
481 // Trigger Liveness check if no liveness update received within the timeout period.
482 // The Liveness check will push Live state to same channel which this routine is
483 // reading and processing. This, do it asynchronously to avoid blocking for
484 // backend response and avoid any possibility of deadlock
npujar467fe752020-01-16 20:17:45 +0530485 go core.backend.PerformLivenessCheck(ctx)
Girish Kumar4d3887d2019-11-22 14:22:05 +0000486 }
487 }
488}