blob: da9fead078c1d31becc142eec29343e0e8058a52 [file] [log] [blame]
Stephane Barbariea75791c2019-01-24 10:58:06 -05001/*
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 */
npujar03b018e2019-11-13 15:29:36 +053016
Stephane Barbariea75791c2019-01-24 10:58:06 -050017package core
18
19import (
20 "context"
npujar03b018e2019-11-13 15:29:36 +053021
22 "time"
23
sbarbari17d7e222019-11-05 10:02:29 -050024 "github.com/opencord/voltha-go/db/model"
Stephane Barbariea75791c2019-01-24 10:58:06 -050025 "github.com/opencord/voltha-go/ro_core/config"
sbarbari17d7e222019-11-05 10:02:29 -050026 "github.com/opencord/voltha-lib-go/v2/pkg/db"
Scott Baker807addd2019-10-24 15:16:21 -070027 "github.com/opencord/voltha-lib-go/v2/pkg/db/kvstore"
Scott Baker807addd2019-10-24 15:16:21 -070028 grpcserver "github.com/opencord/voltha-lib-go/v2/pkg/grpc"
29 "github.com/opencord/voltha-lib-go/v2/pkg/log"
30 "github.com/opencord/voltha-lib-go/v2/pkg/probe"
Scott Baker555307d2019-11-04 08:58:01 -080031 "github.com/opencord/voltha-protos/v2/go/voltha"
Stephane Barbariea75791c2019-01-24 10:58:06 -050032 "google.golang.org/grpc"
Divya Desai660dbba2019-10-16 07:06:49 +000033 "google.golang.org/grpc/codes"
34 "google.golang.org/grpc/status"
Stephane Barbariea75791c2019-01-24 10:58:06 -050035)
36
npujar03b018e2019-11-13 15:29:36 +053037// Core holds all information of read only core service
Stephane Barbariea75791c2019-01-24 10:58:06 -050038type Core struct {
npujar03b018e2019-11-13 15:29:36 +053039 instanceID string
Stephane Barbariea75791c2019-01-24 10:58:06 -050040 genericMgr *ModelProxyManager
41 deviceMgr *DeviceManager
42 logicalDeviceMgr *LogicalDeviceManager
43 grpcServer *grpcserver.GrpcServer
44 grpcNBIAPIHandler *APIHandler
45 config *config.ROCoreFlags
46 clusterDataRoot model.Root
47 localDataRoot model.Root
48 clusterDataProxy *model.Proxy
49 localDataProxy *model.Proxy
50 exitChannel chan int
51 kvClient kvstore.Client
Girish Kumar91482642019-11-08 11:38:03 +000052 backend db.Backend
Stephane Barbariea75791c2019-01-24 10:58:06 -050053}
54
55func init() {
npujar03b018e2019-11-13 15:29:36 +053056 _, err := log.AddPackage(log.JSON, log.DebugLevel, nil)
57 if err != nil {
58 log.Errorw("unable-to-register-package-to-the-log-map", log.Fields{"error": err})
59 }
Stephane Barbariea75791c2019-01-24 10:58:06 -050060}
61
npujar03b018e2019-11-13 15:29:36 +053062// NewCore instantiates core service parameters
Stephane Barbariea75791c2019-01-24 10:58:06 -050063func NewCore(id string, cf *config.ROCoreFlags, kvClient kvstore.Client) *Core {
64 var core Core
npujar03b018e2019-11-13 15:29:36 +053065 core.instanceID = id
Stephane Barbariea75791c2019-01-24 10:58:06 -050066 core.exitChannel = make(chan int, 1)
67 core.config = cf
68 core.kvClient = kvClient
69
Girish Kumar91482642019-11-08 11:38:03 +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
Stephane Barbariea75791c2019-01-24 10:58:06 -050074 // Setup the KV store
75 // Do not call NewBackend constructor; it creates its own KV client
76 // Commented the backend for now until the issue between the model and the KV store
77 // is resolved.
Girish Kumar91482642019-11-08 11:38:03 +000078 core.backend = db.Backend{
79 Client: kvClient,
80 StoreType: cf.KVStoreType,
81 Host: cf.KVStoreHost,
82 Port: cf.KVStorePort,
83 Timeout: cf.KVStoreTimeout,
84 LivenessChannelInterval: livenessChannelInterval,
85 PathPrefix: "service/voltha"}
86 core.clusterDataRoot = model.NewRoot(&voltha.Voltha{}, &core.backend)
87 core.localDataRoot = model.NewRoot(&voltha.CoreInstance{}, &core.backend)
Stephane Barbarieef6650d2019-07-18 12:15:09 -040088 core.clusterDataProxy = core.clusterDataRoot.CreateProxy(context.Background(), "/", false)
89 core.localDataProxy = core.localDataRoot.CreateProxy(context.Background(), "/", false)
Stephane Barbariea75791c2019-01-24 10:58:06 -050090 return &core
91}
92
Divya Desai660dbba2019-10-16 07:06:49 +000093// waitUntilKVStoreReachableOrMaxTries will wait until it can connect to a KV store or until maxtries has been reached
94func (core *Core) waitUntilKVStoreReachableOrMaxTries(ctx context.Context, maxRetries int, retryInterval time.Duration) error {
95 log.Infow("verifying-KV-store-connectivity", log.Fields{"host": core.config.KVStoreHost,
96 "port": core.config.KVStorePort, "retries": maxRetries, "retryInterval": retryInterval})
97
98 // Get timeout in seconds with 1 second set as minimum
99 timeout := int(core.config.CoreTimeout.Seconds())
100 if timeout < 1 {
101 timeout = 1
102 }
103 count := 0
104 for {
105 if !core.kvClient.IsConnectionUp(timeout) {
106 log.Info("KV-store-unreachable")
107 if maxRetries != -1 {
108 if count >= maxRetries {
109 return status.Error(codes.Unavailable, "kv store unreachable")
110 }
111 }
npujar03b018e2019-11-13 15:29:36 +0530112 count++
Divya Desai660dbba2019-10-16 07:06:49 +0000113 // Take a nap before retrying
114 time.Sleep(retryInterval)
115 log.Infow("retry-KV-store-connectivity", log.Fields{"retryCount": count, "maxRetries": maxRetries, "retryInterval": retryInterval})
116
117 } else {
118 break
119 }
120 }
121 log.Info("KV-store-reachable")
122 return nil
123}
124
npujar03b018e2019-11-13 15:29:36 +0530125// Start will start core adapter services
Stephane Barbariea75791c2019-01-24 10:58:06 -0500126func (core *Core) Start(ctx context.Context) {
npujar03b018e2019-11-13 15:29:36 +0530127 log.Info("starting-adaptercore", log.Fields{"coreId": core.instanceID})
Divya Desai660dbba2019-10-16 07:06:49 +0000128
129 // Wait until connection to KV Store is up
130 if err := core.waitUntilKVStoreReachableOrMaxTries(ctx, core.config.MaxConnectionRetries, core.config.ConnectionRetryInterval); err != nil {
131 log.Fatal("Unable-to-connect-to-KV-store")
132 }
133
134 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusRunning)
135
Stephane Barbariea75791c2019-01-24 10:58:06 -0500136 core.genericMgr = newModelProxyManager(core.clusterDataProxy)
npujar03b018e2019-11-13 15:29:36 +0530137 core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
Stephane Barbariea75791c2019-01-24 10:58:06 -0500138 core.logicalDeviceMgr = newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
139 go core.startDeviceManager(ctx)
140 go core.startLogicalDeviceManager(ctx)
141 go core.startGRPCService(ctx)
Girish Kumar91482642019-11-08 11:38:03 +0000142 go core.monitorKvstoreLiveness(ctx)
Stephane Barbariea75791c2019-01-24 10:58:06 -0500143
144 log.Info("adaptercore-started")
145}
146
npujar03b018e2019-11-13 15:29:36 +0530147// Stop will stop core services
Stephane Barbariea75791c2019-01-24 10:58:06 -0500148func (core *Core) Stop(ctx context.Context) {
149 log.Info("stopping-adaptercore")
David Bainbridgef794fc52019-10-03 22:37:12 +0000150 if core.exitChannel != nil {
151 core.exitChannel <- 1
152 }
Stephane Barbariea75791c2019-01-24 10:58:06 -0500153 // Stop all the started services
David Bainbridgef794fc52019-10-03 22:37:12 +0000154 if core.grpcServer != nil {
155 core.grpcServer.Stop()
156 }
157 if core.logicalDeviceMgr != nil {
158 core.logicalDeviceMgr.stop(ctx)
159 }
160 if core.deviceMgr != nil {
161 core.deviceMgr.stop(ctx)
162 }
Stephane Barbariea75791c2019-01-24 10:58:06 -0500163 log.Info("adaptercore-stopped")
164}
165
166//startGRPCService creates the grpc service handlers, registers it to the grpc server
167// and starts the server
168func (core *Core) startGRPCService(ctx context.Context) {
169 // create an insecure gserver server
Girish Kumar91482642019-11-08 11:38:03 +0000170 core.grpcServer = grpcserver.NewGrpcServer(core.config.GrpcHost, core.config.GrpcPort, nil, false, probe.GetProbeFromContext(ctx))
Stephane Barbariea75791c2019-01-24 10:58:06 -0500171 log.Info("grpc-server-created")
172
173 core.grpcNBIAPIHandler = NewAPIHandler(core.genericMgr, core.deviceMgr, core.logicalDeviceMgr)
174 core.logicalDeviceMgr.setGrpcNbiHandler(core.grpcNBIAPIHandler)
175 // Create a function to register the core GRPC service with the GRPC server
176 f := func(gs *grpc.Server) {
177 voltha.RegisterVolthaServiceServer(
178 gs,
179 core.grpcNBIAPIHandler,
180 )
181 }
182
183 core.grpcServer.AddService(f)
184 log.Info("grpc-service-added")
185
Hardik Windlassdc63dde2019-09-30 07:15:13 +0000186 /*
187 * Start the GRPC server
188 *
189 * This is a bit sub-optimal here as the grpcServer.Start call does not return (blocks)
190 * until something fails, but we want to send a "start" status update. As written this
191 * means that we are actually sending the "start" status update before the server is
192 * started, which means it is possible that the status is "running" before it actually is.
193 *
194 * This means that there is a small window in which the core could return its status as
195 * ready, when it really isn't.
196 */
197 probe.UpdateStatusFromContext(ctx, "grpc-service", probe.ServiceStatusRunning)
198
Stephane Barbariea75791c2019-01-24 10:58:06 -0500199 // Start the server
Stephane Barbariea75791c2019-01-24 10:58:06 -0500200 log.Info("grpc-server-started")
Hardik Windlassdc63dde2019-09-30 07:15:13 +0000201 core.grpcServer.Start(context.Background())
202
203 probe.UpdateStatusFromContext(ctx, "grpc-service", probe.ServiceStatusStopped)
Stephane Barbariea75791c2019-01-24 10:58:06 -0500204}
205
206func (core *Core) startDeviceManager(ctx context.Context) {
207 // TODO: Interaction between the logicaldevicemanager and devicemanager should mostly occur via
208 // callbacks. For now, until the model is ready, devicemanager will keep a reference to the
209 // logicaldevicemanager to initiate the creation of logical devices
210 log.Info("starting-DeviceManager")
211 core.deviceMgr.start(ctx, core.logicalDeviceMgr)
212 log.Info("started-DeviceManager")
213}
214
215func (core *Core) startLogicalDeviceManager(ctx context.Context) {
216 log.Info("starting-Logical-DeviceManager")
217 core.logicalDeviceMgr.start(ctx)
218 log.Info("started-Logical-DeviceManager")
219}
Girish Kumar91482642019-11-08 11:38:03 +0000220
221/*
222* Thread to monitor kvstore Liveness (connection status)
223*
224* This function constantly monitors Liveness State of kvstore as reported
225* periodically by backend and updates the Status of kv-store service registered
226* with ro_core probe.
227*
228* If no liveness event has been seen within a timeout, then the thread will make
229* an trigger a "liveness" check, which will in turn trigger a liveness event on
230* the liveness channel, true or false depending on whether the attempt succeeded.
231*
232* The gRPC server in turn monitors the state of the readiness probe and will
233* start issuing UNAVAILABLE response while the probe is not ready.
234 */
235func (core *Core) monitorKvstoreLiveness(ctx context.Context) {
236 log.Info("start-monitoring-kvstore-liveness")
237
238 // Instruct backend to create Liveness channel for transporting state updates
239 livenessChannel := core.backend.EnableLivenessChannel()
240
241 log.Debug("enabled-kvstore-liveness-channel")
242
243 // Default state for kvstore is not alive
244 timeout := core.config.NotLiveProbeInterval
245 for {
246 timeoutTimer := time.NewTimer(timeout)
247 select {
248
249 case liveness := <-livenessChannel:
250 log.Debugw("received-liveness-change-notification", log.Fields{"liveness": liveness})
251
252 if !liveness {
253 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
254
255 if core.grpcServer != nil {
256 log.Info("kvstore-set-server-notready")
257 }
258
259 timeout = core.config.NotLiveProbeInterval
260 } else {
261 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusRunning)
262
263 if core.grpcServer != nil {
264 log.Info("kvstore-set-server-ready")
265 }
266
267 timeout = core.config.LiveProbeInterval
268 }
269
270 if !timeoutTimer.Stop() {
271 <-timeoutTimer.C
272 }
273
274 case <-timeoutTimer.C:
275 log.Info("kvstore-perform-liveness-check-on-timeout")
276
277 // Trigger Liveness check if no liveness update received within the timeout period.
278 // The Liveness check will push Live state to same channel which this routine is
279 // reading and processing. This, do it asynchronously to avoid blocking for
280 // backend response and avoid any possibility of deadlock
281 go core.backend.PerformLivenessCheck(core.config.KVStoreTimeout)
282 }
283 }
284}