blob: f54c4b60b60612fadf248783d5e351a35c7f6fd6 [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001/*
2 * Copyright 2020-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 */
16
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +000017//Package main -> this is the entry point of the OpenOnuAdapter
Holger Hildebrandtfa074992020-03-27 15:42:06 +000018package main
19
20import (
21 "context"
22 "errors"
23 "fmt"
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +000024 "io/ioutil"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000025 "os"
26 "os/signal"
Andrea Campanella3d7c9312021-01-19 09:20:49 +010027 "strings"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000028 "syscall"
29 "time"
30
khenaidoo7d3c5582021-08-11 18:09:44 -040031 "github.com/golang/protobuf/ptypes/empty"
32 conf "github.com/opencord/voltha-lib-go/v7/pkg/config"
33 "github.com/opencord/voltha-lib-go/v7/pkg/db/kvstore"
34 "github.com/opencord/voltha-lib-go/v7/pkg/events"
35 "github.com/opencord/voltha-lib-go/v7/pkg/events/eventif"
36 vgrpc "github.com/opencord/voltha-lib-go/v7/pkg/grpc"
37 "github.com/opencord/voltha-lib-go/v7/pkg/kafka"
38 "github.com/opencord/voltha-lib-go/v7/pkg/log"
39 "github.com/opencord/voltha-lib-go/v7/pkg/probe"
40 "github.com/opencord/voltha-lib-go/v7/pkg/version"
41 "github.com/opencord/voltha-protos/v5/go/adapter_services"
42 "github.com/opencord/voltha-protos/v5/go/core"
43 "github.com/opencord/voltha-protos/v5/go/voltha"
44 "google.golang.org/grpc"
45
46 ic "github.com/opencord/voltha-protos/v5/go/inter_container"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000047
Matteo Scandolo761f7512020-11-23 15:52:40 -080048 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/config"
Holger Hildebrandt4b5e73f2021-08-19 06:51:21 +000049 ac "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/core"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000050)
51
khenaidoo7d3c5582021-08-11 18:09:44 -040052const (
53 clusterMessagingService = "cluster-message-service"
54 onuAdapterService = "onu-adapter-service"
55 kvService = "kv-service"
56 coreService = "core-service"
57)
58
Holger Hildebrandtfa074992020-03-27 15:42:06 +000059type adapter struct {
Himani Chawla4d908332020-08-31 12:30:20 +053060 //defaultAppName string
khenaidoo7d3c5582021-08-11 18:09:44 -040061 instanceID string
62 config *config.AdapterFlags
63 kafkaClient kafka.Client
64 kvClient kvstore.Client
65 eventProxy eventif.EventProxy
66 grpcServer *vgrpc.GrpcServer
67 onuAdapter *ac.OpenONUAC
68 coreClient *vgrpc.Client
Holger Hildebrandtfa074992020-03-27 15:42:06 +000069}
70
Holger Hildebrandtfa074992020-03-27 15:42:06 +000071func newAdapter(cf *config.AdapterFlags) *adapter {
72 var a adapter
73 a.instanceID = cf.InstanceID
74 a.config = cf
Holger Hildebrandtfa074992020-03-27 15:42:06 +000075 return &a
76}
77
78func (a *adapter) start(ctx context.Context) error {
dbainbri4d3a0dc2020-12-02 00:33:42 +000079 logger.Info(ctx, "Starting Core Adapter components")
Holger Hildebrandtfa074992020-03-27 15:42:06 +000080 var err error
81
82 var p *probe.Probe
83 if value := ctx.Value(probe.ProbeContextKey); value != nil {
84 if _, ok := value.(*probe.Probe); ok {
85 p = value.(*probe.Probe)
86 p.RegisterService(
dbainbri4d3a0dc2020-12-02 00:33:42 +000087 ctx,
khenaidoo7d3c5582021-08-11 18:09:44 -040088 clusterMessagingService,
89 kvService,
90 onuAdapterService,
91 coreService,
Holger Hildebrandtfa074992020-03-27 15:42:06 +000092 )
93 }
94 }
95
96 // Setup KV Client
dbainbri4d3a0dc2020-12-02 00:33:42 +000097 logger.Debugw(ctx, "create-kv-client", log.Fields{"kvstore": a.config.KVStoreType})
98 if err = a.setKVClient(ctx); err != nil {
99 logger.Fatalw(ctx, "error-setting-kv-client", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000100 }
101
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000102 // Setup Log Config
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800103 cm := conf.NewConfigManager(ctx, a.kvClient, a.config.KVStoreType, a.config.KVStoreAddress, a.config.KVStoreTimeout)
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000104 go conf.StartLogLevelConfigProcessing(cm, ctx)
105
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000106 // Setup Kafka Client
khenaidoo7d3c5582021-08-11 18:09:44 -0400107 if a.kafkaClient, err = newKafkaClient(ctx, "sarama", a.config.KafkaClusterAddress); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000108 logger.Fatalw(ctx, "Unsupported-common-client", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000109 }
110
khenaidoo7d3c5582021-08-11 18:09:44 -0400111 // Start kafka communication with the broker
112 if err := kafka.StartAndWaitUntilKafkaConnectionIsUp(ctx, a.kafkaClient, a.config.HeartbeatCheckInterval, clusterMessagingService); err != nil {
113 logger.Fatal(ctx, "unable-to-connect-to-kafka")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000114 }
115
khenaidoo7d3c5582021-08-11 18:09:44 -0400116 // Wait until connection to KV store is established
117 if err := WaitUntilKvStoreConnectionIsUp(ctx, a.kvClient, a.config.KVStoreTimeout, kvService); err != nil {
118 logger.Fatal(ctx, "unable-to-connect-to-kv-store")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000119 }
120
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000121 // Create the event proxy to post events to KAFKA
Himani Chawlac07fda02020-12-09 16:21:21 +0530122 a.eventProxy = events.NewEventProxy(events.MsgClient(a.kafkaClient), events.MsgTopic(kafka.Topic{Name: a.config.EventTopic}))
khenaidoo7d3c5582021-08-11 18:09:44 -0400123 go func() {
124 if err := a.eventProxy.Start(); err != nil {
125 logger.Fatalw(ctx, "event-proxy-cannot-start", log.Fields{"error": err})
126 }
127 }()
128
129 // Create the Core client to handle requests to the Core. Note that the coreClient is an interface and needs to be
130 // cast to the appropriate grpc client by invoking GetCoreGrpcClient on the a.coreClient
131 if a.coreClient, err = vgrpc.NewClient(a.config.CoreEndpoint,
132 a.coreRestarted,
133 vgrpc.ActivityCheck(true)); err != nil {
134 logger.Fatal(ctx, "grpc-client-not-created")
135 }
136 // Start the core grpc client
137 go a.coreClient.Start(ctx, setAndTestCoreServiceHandler)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000138
139 // Create the open ONU interface adapter
khenaidoo7d3c5582021-08-11 18:09:44 -0400140 if a.onuAdapter, err = a.startVolthaInterfaceAdapter(ctx, a.coreClient, a.eventProxy, a.config, cm); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000141 logger.Fatalw(ctx, "error-starting-volthaInterfaceAdapter for OpenOnt", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000142 }
143
khenaidoo7d3c5582021-08-11 18:09:44 -0400144 // Create and start the grpc server
145 a.grpcServer = vgrpc.NewGrpcServer(a.config.GrpcAddress, nil, false, p)
146
147 //Register the adapter service
148 a.addAdapterService(ctx, a.grpcServer, a.onuAdapter)
149
150 //Register the onu inter adapter service
151 a.addOnuInterAdapterService(ctx, a.grpcServer, a.onuAdapter)
152
153 go a.startGRPCService(ctx, a.grpcServer, onuAdapterService)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000154
155 // Register this adapter to the Core - retries indefinitely
khenaidoo7d3c5582021-08-11 18:09:44 -0400156 if err = a.registerWithCore(ctx, coreService, -1); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000157 logger.Fatalw(ctx, "error-registering-with-core", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000158 }
159
khenaidoo7d3c5582021-08-11 18:09:44 -0400160 // Start the readiness and liveliness check and update the probe status
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000161 a.checkServicesReadiness(ctx)
162 return err
163}
164
khenaidoo7d3c5582021-08-11 18:09:44 -0400165// TODO: Any action the adapter needs to do following a Core restart?
166func (a *adapter) coreRestarted(ctx context.Context, endPoint string) error {
167 logger.Errorw(ctx, "core-restarted", log.Fields{"endpoint": endPoint})
168 return nil
169}
170
171// setAndTestCoreServiceHandler is used to test whether the remote gRPC service is up
172func setAndTestCoreServiceHandler(ctx context.Context, conn *grpc.ClientConn) interface{} {
173 svc := core.NewCoreServiceClient(conn)
174 if h, err := svc.GetHealthStatus(ctx, &empty.Empty{}); err != nil || h.State != voltha.HealthStatus_HEALTHY {
175 return nil
176 }
177 return svc
178}
179
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000180func (a *adapter) stop(ctx context.Context) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000181 // Cleanup - applies only if we had a kvClient
182 if a.kvClient != nil {
183 // Release all reservations
184 if err := a.kvClient.ReleaseAllReservations(ctx); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000185 logger.Infow(ctx, "fail-to-release-all-reservations", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000186 }
187 // Close the DB connection
dbainbri4d3a0dc2020-12-02 00:33:42 +0000188 a.kvClient.Close(ctx)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000189 }
190
khenaidoo7d3c5582021-08-11 18:09:44 -0400191 if a.eventProxy != nil {
192 a.eventProxy.Stop()
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000193 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400194
195 if a.kafkaClient != nil {
196 a.kafkaClient.Stop(ctx)
197 }
198
199 // Stop core client
200 if a.coreClient != nil {
201 a.coreClient.Stop(ctx)
202 }
203
204 // TODO: More cleanup
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000205}
206
207// #############################################
208// Adapter Utility methods ##### begin #########
209
dbainbri4d3a0dc2020-12-02 00:33:42 +0000210func newKVClient(ctx context.Context, storeType, address string, timeout time.Duration) (kvstore.Client, error) {
211 logger.Infow(ctx, "kv-store-type", log.Fields{"store": storeType})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000212 switch storeType {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000213 case "etcd":
dbainbri4d3a0dc2020-12-02 00:33:42 +0000214 return kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000215 }
216 return nil, errors.New("unsupported-kv-store")
217}
218
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800219func newKafkaClient(ctx context.Context, clientType, addr string) (kafka.Client, error) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000220
dbainbri4d3a0dc2020-12-02 00:33:42 +0000221 logger.Infow(ctx, "common-client-type", log.Fields{"client": clientType})
mpagenkoaf801632020-07-03 10:00:42 +0000222
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000223 switch clientType {
224 case "sarama":
225 return kafka.NewSaramaClient(
mpagenkoaf801632020-07-03 10:00:42 +0000226 kafka.Address(addr),
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000227 kafka.ProducerReturnOnErrors(true),
228 kafka.ProducerReturnOnSuccess(true),
229 kafka.ProducerMaxRetries(6),
230 kafka.ProducerRetryBackoff(time.Millisecond*30),
231 kafka.MetadatMaxRetries(15)), nil
232 }
233
234 return nil, errors.New("unsupported-client-type")
235}
236
dbainbri4d3a0dc2020-12-02 00:33:42 +0000237func (a *adapter) setKVClient(ctx context.Context) error {
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800238 client, err := newKVClient(ctx, a.config.KVStoreType, a.config.KVStoreAddress, a.config.KVStoreTimeout)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000239 if err != nil {
240 a.kvClient = nil
dbainbri4d3a0dc2020-12-02 00:33:42 +0000241 logger.Errorw(ctx, "error-starting-KVClient", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000242 return err
243 }
244 a.kvClient = client
245 return nil
246}
247
khenaidoo7d3c5582021-08-11 18:09:44 -0400248func (a *adapter) startVolthaInterfaceAdapter(ctx context.Context, cc *vgrpc.Client, ep eventif.EventProxy,
Matteo Scandolof1f39a72020-11-24 12:08:11 -0800249 cfg *config.AdapterFlags, cm *conf.ConfigManager) (*ac.OpenONUAC, error) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000250 var err error
khenaidoo7d3c5582021-08-11 18:09:44 -0400251 sAcONU := ac.NewOpenONUAC(ctx, cc, ep, a.kvClient, cfg, cm)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000252
253 if err = sAcONU.Start(ctx); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000254 logger.Fatalw(ctx, "error-starting-OpenOnuAdapterCore", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000255 return nil, err
256 }
257
dbainbri4d3a0dc2020-12-02 00:33:42 +0000258 logger.Info(ctx, "open-ont-OpenOnuAdapterCore-started")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000259 return sAcONU, nil
260}
261
khenaidoo7d3c5582021-08-11 18:09:44 -0400262func (a *adapter) registerWithCore(ctx context.Context, serviceName string, retries int) error {
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000263 adapterID := fmt.Sprintf("brcm_openomci_onu_%d", a.config.CurrentReplica)
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100264 vendorIdsList := strings.Split(a.config.OnuVendorIds, ",")
dbainbri4d3a0dc2020-12-02 00:33:42 +0000265 logger.Infow(ctx, "registering-with-core", log.Fields{
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000266 "adapterID": adapterID,
267 "currentReplica": a.config.CurrentReplica,
268 "totalReplicas": a.config.TotalReplicas,
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100269 "onuVendorIds": vendorIdsList,
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000270 })
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700271 adapterDescription := &voltha.Adapter{
Andrea Campanella961734c2021-01-18 11:44:47 +0100272 Id: adapterID, // Unique name for the device type ->exact type required for OLT comm????
273 Vendor: "VOLTHA OpenONUGo",
274 Version: version.VersionInfo.Version,
khenaidoo7d3c5582021-08-11 18:09:44 -0400275 Endpoint: a.config.AdapterEndpoint,
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700276 Type: "brcm_openomci_onu",
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000277 CurrentReplica: int32(a.config.CurrentReplica),
278 TotalReplicas: int32(a.config.TotalReplicas),
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700279 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000280 types := []*voltha.DeviceType{{Id: "brcm_openomci_onu",
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100281 VendorIds: vendorIdsList,
khenaidoo7d3c5582021-08-11 18:09:44 -0400282 AdapterType: "brcm_openomci_onu", // Type of adapter that handles this device type
283 Adapter: "brcm_openomci_onu", // Deprecated attribute
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000284 AcceptsBulkFlowUpdate: false, // Currently openolt adapter does not support bulk flow handling
285 AcceptsAddRemoveFlowUpdates: true}}
286 deviceTypes := &voltha.DeviceTypes{Items: types}
287 count := 0
288 for {
khenaidoo7d3c5582021-08-11 18:09:44 -0400289 gClient, err := a.coreClient.GetCoreServiceClient()
290 if gClient != nil {
291 if gClient != nil {
292 if _, err = gClient.RegisterAdapter(log.WithSpanFromContext(context.TODO(), ctx), &ic.AdapterRegistration{
293 Adapter: adapterDescription,
294 DTypes: deviceTypes}); err == nil {
295 break
296 }
297 }
298 logger.Warnw(ctx, "registering-with-core-failed", log.Fields{"endpoint": a.config.CoreEndpoint, "error": err, "count": count, "gclient": gClient})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000299 if retries == count {
300 return err
301 }
302 count++
khenaidoo7d3c5582021-08-11 18:09:44 -0400303 // Take a power nap before retrying
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000304 time.Sleep(2 * time.Second)
khenaidoo7d3c5582021-08-11 18:09:44 -0400305
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000306 }
307 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400308 probe.UpdateStatusFromContext(ctx, serviceName, probe.ServiceStatusRunning)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000309 logger.Info(ctx, "registered-with-core")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000310 return nil
311}
312
khenaidoo7d3c5582021-08-11 18:09:44 -0400313// startGRPCService creates the grpc service handlers, registers it to the grpc server and starts the server
314func (a *adapter) startGRPCService(ctx context.Context, server *vgrpc.GrpcServer, serviceName string) {
315 logger.Infow(ctx, "service-created", log.Fields{"service": serviceName})
316
317 probe.UpdateStatusFromContext(ctx, serviceName, probe.ServiceStatusRunning)
318 logger.Infow(ctx, "service-started", log.Fields{"service": serviceName})
319
320 server.Start(ctx)
321 probe.UpdateStatusFromContext(ctx, serviceName, probe.ServiceStatusStopped)
322}
323
324func (a *adapter) addAdapterService(ctx context.Context, server *vgrpc.GrpcServer, handler adapter_services.AdapterServiceServer) {
325 logger.Info(ctx, "adding-adapter-service")
326
327 server.AddService(func(gs *grpc.Server) {
328 adapter_services.RegisterAdapterServiceServer(gs, handler)
329 })
330}
331
332func (a *adapter) addOnuInterAdapterService(ctx context.Context, server *vgrpc.GrpcServer, handler adapter_services.OnuInterAdapterServiceServer) {
333 logger.Info(ctx, "adding-onu-inter-adapter-service")
334
335 server.AddService(func(gs *grpc.Server) {
336 adapter_services.RegisterOnuInterAdapterServiceServer(gs, handler)
337 })
338}
339
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000340/**
341This function checks the liveliness and readiness of the kakfa and kv-client services
342and update the status in the probe.
343*/
344func (a *adapter) checkServicesReadiness(ctx context.Context) {
345 // checks the kafka readiness
khenaidoo7d3c5582021-08-11 18:09:44 -0400346 go kafka.MonitorKafkaReadiness(ctx, a.kafkaClient, a.config.LiveProbeInterval, a.config.NotLiveProbeInterval, clusterMessagingService)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000347
348 // checks the kv-store readiness
349 go a.checkKvStoreReadiness(ctx)
350}
351
352/**
353This function checks the liveliness and readiness of the kv-store service
354and update the status in the probe.
355*/
356func (a *adapter) checkKvStoreReadiness(ctx context.Context) {
357 // dividing the live probe interval by 2 to get updated status every 30s
358 timeout := a.config.LiveProbeInterval / 2
359 kvStoreChannel := make(chan bool, 1)
360
khenaidoo7d3c5582021-08-11 18:09:44 -0400361 // Default true - we are here only after we already had a KV store connection
362 kvStoreChannel <- true
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000363 for {
364 timeoutTimer := time.NewTimer(timeout)
365 select {
366 case liveliness := <-kvStoreChannel:
367 if !liveliness {
368 // kv-store not reachable or down, updating the status to not ready state
khenaidoo7d3c5582021-08-11 18:09:44 -0400369 probe.UpdateStatusFromContext(ctx, kvService, probe.ServiceStatusNotReady)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000370 timeout = a.config.NotLiveProbeInterval
371 } else {
372 // kv-store is reachable , updating the status to running state
khenaidoo7d3c5582021-08-11 18:09:44 -0400373 probe.UpdateStatusFromContext(ctx, kvService, probe.ServiceStatusRunning)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000374 timeout = a.config.LiveProbeInterval / 2
375 }
376 // Check if the timer has expired or not
377 if !timeoutTimer.Stop() {
378 <-timeoutTimer.C
379 }
380 case <-timeoutTimer.C:
381 // Check the status of the kv-store
dbainbri4d3a0dc2020-12-02 00:33:42 +0000382 logger.Info(ctx, "kv-store liveliness-recheck")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000383 if a.kvClient.IsConnectionUp(ctx) {
384 kvStoreChannel <- true
385 } else {
386 kvStoreChannel <- false
387 }
388 }
389 }
390}
391
khenaidoo7d3c5582021-08-11 18:09:44 -0400392// WaitUntilKvStoreConnectionIsUp waits until the KV client can establish a connection to the KV server or until the
393// context times out.
394func WaitUntilKvStoreConnectionIsUp(ctx context.Context, kvClient kvstore.Client, connectionRetryInterval time.Duration, serviceName string) error {
395 if kvClient == nil {
396 return errors.New("kvclient-is-nil")
397 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000398 for {
khenaidoo7d3c5582021-08-11 18:09:44 -0400399 if !kvClient.IsConnectionUp(ctx) {
400 probe.UpdateStatusFromContext(ctx, serviceName, probe.ServiceStatusNotReady)
401 logger.Warnw(ctx, "kvconnection-down", log.Fields{"service-name": serviceName, "connect-retry-interval": connectionRetryInterval})
402 select {
403 case <-time.After(connectionRetryInterval):
404 continue
405 case <-ctx.Done():
406 return ctx.Err()
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000407 }
408 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400409 probe.UpdateStatusFromContext(ctx, serviceName, probe.ServiceStatusRunning)
410 logger.Info(ctx, "kv-connection-up")
411 break
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000412 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400413 return nil
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000414}
415
416// Adapter Utility methods ##### end #########
417// #############################################
418
dbainbri4d3a0dc2020-12-02 00:33:42 +0000419func getVerifiedCodeVersion(ctx context.Context) string {
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000420 if version.VersionInfo.Version == "unknown-version" {
421 content, err := ioutil.ReadFile("VERSION")
422 if err == nil {
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100423 return string(content)
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000424 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000425 logger.Error(ctx, "'VERSION'-file not readable")
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000426 }
427 return version.VersionInfo.Version
428}
429
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000430func printVersion(appName string) {
431 fmt.Println(appName)
432 fmt.Println(version.VersionInfo.String(" "))
433}
434
435func printBanner() {
436 fmt.Println(" ____ ____ ___ ___ _ ")
437 fmt.Println(" / __ \\ / __ \\| \\ \\ | | | | |")
438 fmt.Println(" | | | |_ __ ___ _ __ | | | | |\\ \\ | | | | | ____ ____")
439 fmt.Println(" | | | | '_ \\ / _ \\ '_ \\ | | | | | \\ \\ | | | | | / '_ \\ / _' \\")
440 fmt.Println(" | |__| | |_) | __/| | | || |__| | | \\ \\| | \\__/ || (__) | (__) |")
441 fmt.Println(" \\___ /| .__/ \\___|_| |_| \\____/|_| \\___|______| \\.___ |\\___./")
442 fmt.Println(" | | __| |")
443 fmt.Println(" |_| |____/")
444 fmt.Println(" ")
445}
446
447func waitForExit(ctx context.Context) int {
448 signalChannel := make(chan os.Signal, 1)
449 signal.Notify(signalChannel,
450 syscall.SIGHUP,
451 syscall.SIGINT,
452 syscall.SIGTERM,
453 syscall.SIGQUIT)
454
455 exitChannel := make(chan int)
456
457 go func() {
458 select {
459 case <-ctx.Done():
dbainbri4d3a0dc2020-12-02 00:33:42 +0000460 logger.Infow(ctx, "Adapter run aborted due to internal errors", log.Fields{"context": "done"})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000461 exitChannel <- 2
462 case s := <-signalChannel:
463 switch s {
464 case syscall.SIGHUP,
465 syscall.SIGINT,
466 syscall.SIGTERM,
467 syscall.SIGQUIT:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000468 logger.Infow(ctx, "closing-signal-received", log.Fields{"signal": s})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000469 exitChannel <- 0
470 default:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000471 logger.Infow(ctx, "unexpected-signal-received", log.Fields{"signal": s})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000472 exitChannel <- 1
473 }
474 }
475 }()
476
477 code := <-exitChannel
478 return code
479}
480
481func main() {
482 start := time.Now()
dbainbri4d3a0dc2020-12-02 00:33:42 +0000483 ctx, cancel := context.WithCancel(context.Background())
484 defer cancel()
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000485
khenaidoo7d3c5582021-08-11 18:09:44 -0400486 cf := &config.AdapterFlags{}
487 cf.ParseCommandArguments(os.Args[1:])
488
dbainbri4d3a0dc2020-12-02 00:33:42 +0000489 defaultAppName := cf.InstanceID + "_" + getVerifiedCodeVersion(ctx)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000490
491 // Setup logging
492
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000493 logLevel, err := log.StringToLogLevel(cf.LogLevel)
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700494 if err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000495 logger.Fatalf(ctx, "Cannot setup logging, %s", err)
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700496 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000497
498 // Setup default logger - applies for packages that do not have specific logger set
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000499 if _, err := log.SetDefaultLogger(log.JSON, logLevel, log.Fields{"instanceId": cf.InstanceID}); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000500 logger.With(log.Fields{"error": err}).Fatal(ctx, "Cannot setup logging")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000501 }
502
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000503 // Update all loggers (provisioned via init) with a common field
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000504 if err := log.UpdateAllLoggers(log.Fields{"instanceId": cf.InstanceID}); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000505 logger.With(log.Fields{"error": err}).Fatal(ctx, "Cannot setup logging")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000506 }
507
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000508 log.SetAllLogLevel(logLevel)
509
dbainbri4d3a0dc2020-12-02 00:33:42 +0000510 realMain(ctx) //fatal on httpListen(0,6060) ...
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000511
Himani Chawla4d908332020-08-31 12:30:20 +0530512 defer func() {
513 _ = log.CleanUp()
514 }()
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000515 // Print version / build information and exit
516 if cf.DisplayVersionOnly {
517 printVersion(defaultAppName)
518 return
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000519 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000520 logger.Infow(ctx, "config", log.Fields{"StartName": defaultAppName})
521 logger.Infow(ctx, "config", log.Fields{"BuildVersion": version.VersionInfo.String(" ")})
522 logger.Infow(ctx, "config", log.Fields{"Arguments": os.Args[1:]})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000523
524 // Print banner if specified
525 if cf.Banner {
526 printBanner()
527 }
528
dbainbri4d3a0dc2020-12-02 00:33:42 +0000529 logger.Infow(ctx, "config", log.Fields{"config": *cf})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000530
531 ad := newAdapter(cf)
532
533 p := &probe.Probe{}
dbainbri4d3a0dc2020-12-02 00:33:42 +0000534 logger.Infow(ctx, "resources", log.Fields{"Context": ctx, "Adapter": ad.instanceID, "ProbeCoreState": p.GetStatus("register-with-core")})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000535
dbainbri4d3a0dc2020-12-02 00:33:42 +0000536 go p.ListenAndServe(ctx, fmt.Sprintf("%s:%d", ad.config.ProbeHost, ad.config.ProbePort))
537 logger.Infow(ctx, "probeState", log.Fields{"ProbeCoreState": p.GetStatus("register-with-core")})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000538
539 probeCtx := context.WithValue(ctx, probe.ProbeContextKey, p)
540
dbainbri4d3a0dc2020-12-02 00:33:42 +0000541 closer, err := log.GetGlobalLFM().InitTracingAndLogCorrelation(cf.TraceEnabled, cf.TraceAgentAddress, cf.LogCorrelationEnabled)
542 if err != nil {
543 logger.Warnw(ctx, "unable-to-initialize-tracing-and-log-correlation-module", log.Fields{"error": err})
544 } else {
545 defer log.TerminateTracing(closer)
546 }
547
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000548 go func() {
549 err := ad.start(probeCtx)
550 // If this operation returns an error
551 // cancel all operations using this context
552 if err != nil {
553 cancel()
554 }
555 }()
556
557 code := waitForExit(ctx)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000558 logger.Infow(ctx, "received-a-closing-signal", log.Fields{"code": code})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000559
khenaidoo1fd58e02021-10-13 11:51:20 -0400560 // Set the ONU adapter GRPC service as not ready. This will prevent any request from coming to this adapter instance
561 probe.UpdateStatusFromContext(probeCtx, onuAdapterService, probe.ServiceStatusStopped)
562
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000563 // Cleanup before leaving
564 ad.stop(ctx)
565
566 elapsed := time.Since(start)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000567 logger.Infow(ctx, "run-time", log.Fields{"Name": "openadapter", "time": elapsed / time.Microsecond})
568 //logger.Infow(ctx,"run-time", log.Fields{"instanceId": ad.config.InstanceID, "time": elapsed / time.Second})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000569}