blob: c42cef42b413560bb7162ac442db82abdc67e1af [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
Girish Gowdra50e56422021-06-01 16:46:04 -070031 "github.com/opencord/voltha-lib-go/v5/pkg/adapters"
32 "github.com/opencord/voltha-lib-go/v5/pkg/adapters/adapterif"
33 com "github.com/opencord/voltha-lib-go/v5/pkg/adapters/common"
34 conf "github.com/opencord/voltha-lib-go/v5/pkg/config"
35 "github.com/opencord/voltha-lib-go/v5/pkg/db/kvstore"
36 "github.com/opencord/voltha-lib-go/v5/pkg/events"
37 "github.com/opencord/voltha-lib-go/v5/pkg/events/eventif"
38 "github.com/opencord/voltha-lib-go/v5/pkg/kafka"
39 "github.com/opencord/voltha-lib-go/v5/pkg/log"
40 "github.com/opencord/voltha-lib-go/v5/pkg/probe"
41 "github.com/opencord/voltha-lib-go/v5/pkg/version"
dbainbri4d3a0dc2020-12-02 00:33:42 +000042 ic "github.com/opencord/voltha-protos/v4/go/inter_container"
43 "github.com/opencord/voltha-protos/v4/go/voltha"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000044
Matteo Scandolo761f7512020-11-23 15:52:40 -080045 "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/config"
46 ac "github.com/opencord/voltha-openonu-adapter-go/internal/pkg/onuadaptercore"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000047)
48
49type adapter struct {
Himani Chawla4d908332020-08-31 12:30:20 +053050 //defaultAppName string
Holger Hildebrandtfa074992020-03-27 15:42:06 +000051 instanceID string
52 config *config.AdapterFlags
53 iAdapter adapters.IAdapter // from Voltha interface adapters
54 kafkaClient kafka.Client
55 kvClient kvstore.Client
56 kip kafka.InterContainerProxy
57 coreProxy adapterif.CoreProxy
58 adapterProxy adapterif.AdapterProxy
Himani Chawlac07fda02020-12-09 16:21:21 +053059 eventProxy eventif.EventProxy
Holger Hildebrandtfa074992020-03-27 15:42:06 +000060 halted bool
61 exitChannel chan int
62 receiverChannels []<-chan *ic.InterContainerMessage //from inter-container
63}
64
Holger Hildebrandtfa074992020-03-27 15:42:06 +000065func newAdapter(cf *config.AdapterFlags) *adapter {
66 var a adapter
67 a.instanceID = cf.InstanceID
68 a.config = cf
69 a.halted = false
70 a.exitChannel = make(chan int, 1)
71 a.receiverChannels = make([]<-chan *ic.InterContainerMessage, 0)
72 return &a
73}
74
75func (a *adapter) start(ctx context.Context) error {
dbainbri4d3a0dc2020-12-02 00:33:42 +000076 logger.Info(ctx, "Starting Core Adapter components")
Holger Hildebrandtfa074992020-03-27 15:42:06 +000077 var err error
78
79 var p *probe.Probe
80 if value := ctx.Value(probe.ProbeContextKey); value != nil {
81 if _, ok := value.(*probe.Probe); ok {
82 p = value.(*probe.Probe)
83 p.RegisterService(
dbainbri4d3a0dc2020-12-02 00:33:42 +000084 ctx,
Holger Hildebrandtfa074992020-03-27 15:42:06 +000085 "message-bus",
86 "kv-store",
87 "container-proxy",
88 "core-request-handler",
89 "register-with-core",
90 )
91 }
92 }
93
94 // Setup KV Client
dbainbri4d3a0dc2020-12-02 00:33:42 +000095 logger.Debugw(ctx, "create-kv-client", log.Fields{"kvstore": a.config.KVStoreType})
96 if err = a.setKVClient(ctx); err != nil {
97 logger.Fatalw(ctx, "error-setting-kv-client", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +000098 }
99
100 if p != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000101 p.UpdateStatus(ctx, "kv-store", probe.ServiceStatusRunning)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000102 }
103
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000104 // Setup Log Config
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800105 cm := conf.NewConfigManager(ctx, a.kvClient, a.config.KVStoreType, a.config.KVStoreAddress, a.config.KVStoreTimeout)
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000106 go conf.StartLogLevelConfigProcessing(cm, ctx)
107
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000108 // Setup Kafka Client
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800109 if a.kafkaClient, err = newKafkaClient(ctx, "sarama", a.config.KafkaAdapterAddress); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000110 logger.Fatalw(ctx, "Unsupported-common-client", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000111 }
112
113 if p != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000114 p.UpdateStatus(ctx, "message-bus", probe.ServiceStatusRunning)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000115 }
116
117 // Start the common InterContainer Proxy - retries as per program arguments or indefinitely per default
118 if a.kip, err = a.startInterContainerProxy(ctx, a.config.KafkaReconnectRetries); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000119 logger.Fatalw(ctx, "error-starting-inter-container-proxy", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000120 //aborting the complete processing here (does notmake sense after set Retry number [else use -1 for infinite])
121 return err
122 }
123
124 // Create the core proxy to handle requests to the Core
dbainbri4d3a0dc2020-12-02 00:33:42 +0000125 a.coreProxy = com.NewCoreProxy(ctx, a.kip, a.config.Topic, a.config.CoreTopic)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000126
Andrea Campanella961734c2021-01-18 11:44:47 +0100127 logger.Debugw(ctx, "create adapter proxy", log.Fields{"CoreTopic": a.config.CoreTopic})
dbainbri4d3a0dc2020-12-02 00:33:42 +0000128 a.adapterProxy = com.NewAdapterProxy(ctx, a.kip, a.config.CoreTopic, cm.Backend)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000129
130 // Create the event proxy to post events to KAFKA
Himani Chawlac07fda02020-12-09 16:21:21 +0530131 a.eventProxy = events.NewEventProxy(events.MsgClient(a.kafkaClient), events.MsgTopic(kafka.Topic{Name: a.config.EventTopic}))
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000132
133 // Create the open ONU interface adapter
134 if a.iAdapter, err = a.startVolthaInterfaceAdapter(ctx, a.kip, a.coreProxy, a.adapterProxy, a.eventProxy,
Matteo Scandolof1f39a72020-11-24 12:08:11 -0800135 a.config, cm); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000136 logger.Fatalw(ctx, "error-starting-volthaInterfaceAdapter for OpenOnt", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000137 }
138
139 // Register the core request handler
140 if err = a.setupRequestHandler(ctx, a.instanceID, a.iAdapter); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000141 logger.Fatalw(ctx, "error-setting-core-request-handler", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000142 }
143
144 // Register this adapter to the Core - retries indefinitely
145 if err = a.registerWithCore(ctx, -1); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000146 logger.Fatalw(ctx, "error-registering-with-core", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000147 }
148
149 // check the readiness and liveliness and update the probe status
150 a.checkServicesReadiness(ctx)
151 return err
152}
153
154func (a *adapter) stop(ctx context.Context) {
155 // Stop leadership tracking
156 a.halted = true
157
158 // send exit signal
159 a.exitChannel <- 0
160
161 // Cleanup - applies only if we had a kvClient
162 if a.kvClient != nil {
163 // Release all reservations
164 if err := a.kvClient.ReleaseAllReservations(ctx); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000165 logger.Infow(ctx, "fail-to-release-all-reservations", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000166 }
167 // Close the DB connection
dbainbri4d3a0dc2020-12-02 00:33:42 +0000168 a.kvClient.Close(ctx)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000169 }
170
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000171 if a.kip != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000172 a.kip.Stop(ctx)
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000173 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000174}
175
176// #############################################
177// Adapter Utility methods ##### begin #########
178
dbainbri4d3a0dc2020-12-02 00:33:42 +0000179func newKVClient(ctx context.Context, storeType, address string, timeout time.Duration) (kvstore.Client, error) {
180 logger.Infow(ctx, "kv-store-type", log.Fields{"store": storeType})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000181 switch storeType {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000182 case "etcd":
dbainbri4d3a0dc2020-12-02 00:33:42 +0000183 return kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000184 }
185 return nil, errors.New("unsupported-kv-store")
186}
187
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800188func newKafkaClient(ctx context.Context, clientType, addr string) (kafka.Client, error) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000189
dbainbri4d3a0dc2020-12-02 00:33:42 +0000190 logger.Infow(ctx, "common-client-type", log.Fields{"client": clientType})
mpagenkoaf801632020-07-03 10:00:42 +0000191
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000192 switch clientType {
193 case "sarama":
194 return kafka.NewSaramaClient(
mpagenkoaf801632020-07-03 10:00:42 +0000195 kafka.Address(addr),
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000196 kafka.ProducerReturnOnErrors(true),
197 kafka.ProducerReturnOnSuccess(true),
198 kafka.ProducerMaxRetries(6),
199 kafka.ProducerRetryBackoff(time.Millisecond*30),
200 kafka.MetadatMaxRetries(15)), nil
201 }
202
203 return nil, errors.New("unsupported-client-type")
204}
205
dbainbri4d3a0dc2020-12-02 00:33:42 +0000206func (a *adapter) setKVClient(ctx context.Context) error {
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800207 client, err := newKVClient(ctx, a.config.KVStoreType, a.config.KVStoreAddress, a.config.KVStoreTimeout)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000208 if err != nil {
209 a.kvClient = nil
dbainbri4d3a0dc2020-12-02 00:33:42 +0000210 logger.Errorw(ctx, "error-starting-KVClient", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000211 return err
212 }
213 a.kvClient = client
214 return nil
215}
216
217func (a *adapter) startInterContainerProxy(ctx context.Context, retries int) (kafka.InterContainerProxy, error) {
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800218 logger.Infow(ctx, "starting-intercontainer-messaging-proxy", log.Fields{"addr": a.config.KafkaAdapterAddress, "topic": a.config.Topic})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000219 var err error
mpagenkoaf801632020-07-03 10:00:42 +0000220 /* address config update acc. to [VOL-2736] */
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000221 kip := kafka.NewInterContainerProxy(
Matteo Scandolo127c59d2021-01-28 11:31:18 -0800222 kafka.InterContainerAddress(a.config.KafkaAdapterAddress),
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000223 kafka.MsgClient(a.kafkaClient),
224 kafka.DefaultTopic(&kafka.Topic{Name: a.config.Topic}))
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000225 count := 0
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000226 for {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000227 if err = kip.Start(ctx); err != nil {
228 logger.Warnw(ctx, "error-starting-messaging-proxy", log.Fields{"error": err, "retry": retries, "count": count})
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000229 if retries == count {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000230 return nil, err
231 }
232 count++
233 // Take a nap before retrying
234 time.Sleep(2 * time.Second)
235 } else {
236 break
237 }
238 }
239 probe.UpdateStatusFromContext(ctx, "container-proxy", probe.ServiceStatusRunning)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000240 logger.Info(ctx, "common-messaging-proxy-created")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000241 return kip, nil
242}
243
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000244func (a *adapter) startVolthaInterfaceAdapter(ctx context.Context, kip kafka.InterContainerProxy,
Himani Chawlac07fda02020-12-09 16:21:21 +0530245 cp adapterif.CoreProxy, ap adapterif.AdapterProxy, ep eventif.EventProxy,
Matteo Scandolof1f39a72020-11-24 12:08:11 -0800246 cfg *config.AdapterFlags, cm *conf.ConfigManager) (*ac.OpenONUAC, error) {
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000247 var err error
Matteo Scandolof1f39a72020-11-24 12:08:11 -0800248 sAcONU := ac.NewOpenONUAC(ctx, a.kip, cp, ap, ep, a.kvClient, cfg, cm)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000249
250 if err = sAcONU.Start(ctx); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000251 logger.Fatalw(ctx, "error-starting-OpenOnuAdapterCore", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000252 return nil, err
253 }
254
dbainbri4d3a0dc2020-12-02 00:33:42 +0000255 logger.Info(ctx, "open-ont-OpenOnuAdapterCore-started")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000256 return sAcONU, nil
257}
258
259func (a *adapter) setupRequestHandler(ctx context.Context, coreInstanceID string, iadapter adapters.IAdapter) error {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000260 logger.Info(ctx, "setting-request-handler")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000261 requestProxy := com.NewRequestHandlerProxy(coreInstanceID, iadapter, a.coreProxy)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000262 if err := a.kip.SubscribeWithRequestHandlerInterface(ctx, kafka.Topic{Name: a.config.Topic}, requestProxy); err != nil {
263 logger.Errorw(ctx, "request-handler-setup-failed", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000264 return err
265
266 }
267 probe.UpdateStatusFromContext(ctx, "core-request-handler", probe.ServiceStatusRunning)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000268 logger.Info(ctx, "request-handler-setup-done")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000269 return nil
270}
271
272func (a *adapter) registerWithCore(ctx context.Context, retries int) error {
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000273 adapterID := fmt.Sprintf("brcm_openomci_onu_%d", a.config.CurrentReplica)
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100274 vendorIdsList := strings.Split(a.config.OnuVendorIds, ",")
dbainbri4d3a0dc2020-12-02 00:33:42 +0000275 logger.Infow(ctx, "registering-with-core", log.Fields{
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000276 "adapterID": adapterID,
277 "currentReplica": a.config.CurrentReplica,
278 "totalReplicas": a.config.TotalReplicas,
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100279 "onuVendorIds": vendorIdsList,
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000280 })
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700281 adapterDescription := &voltha.Adapter{
Andrea Campanella961734c2021-01-18 11:44:47 +0100282 Id: adapterID, // Unique name for the device type ->exact type required for OLT comm????
283 Vendor: "VOLTHA OpenONUGo",
284 Version: version.VersionInfo.Version,
Matteo Scandoloefbec272020-11-17 10:33:09 -0800285 Endpoint: a.config.Topic,
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700286 Type: "brcm_openomci_onu",
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000287 CurrentReplica: int32(a.config.CurrentReplica),
288 TotalReplicas: int32(a.config.TotalReplicas),
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700289 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000290 types := []*voltha.DeviceType{{Id: "brcm_openomci_onu",
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100291 VendorIds: vendorIdsList,
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000292 Adapter: "brcm_openomci_onu", // Name of the adapter that handles device type
293 AcceptsBulkFlowUpdate: false, // Currently openolt adapter does not support bulk flow handling
294 AcceptsAddRemoveFlowUpdates: true}}
295 deviceTypes := &voltha.DeviceTypes{Items: types}
296 count := 0
297 for {
298 if err := a.coreProxy.RegisterAdapter(context.TODO(), adapterDescription, deviceTypes); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000299 logger.Warnw(ctx, "registering-with-core-failed", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000300 if retries == count {
301 return err
302 }
303 count++
304 // Take a nap before retrying
305 time.Sleep(2 * time.Second)
306 } else {
307 break
308 }
309 }
310 probe.UpdateStatusFromContext(ctx, "register-with-core", probe.ServiceStatusRunning)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000311 logger.Info(ctx, "registered-with-core")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000312 return nil
313}
314
315/**
316This function checks the liveliness and readiness of the kakfa and kv-client services
317and update the status in the probe.
318*/
319func (a *adapter) checkServicesReadiness(ctx context.Context) {
320 // checks the kafka readiness
321 go a.checkKafkaReadiness(ctx)
322
323 // checks the kv-store readiness
324 go a.checkKvStoreReadiness(ctx)
325}
326
327/**
328This function checks the liveliness and readiness of the kv-store service
329and update the status in the probe.
330*/
331func (a *adapter) checkKvStoreReadiness(ctx context.Context) {
332 // dividing the live probe interval by 2 to get updated status every 30s
333 timeout := a.config.LiveProbeInterval / 2
334 kvStoreChannel := make(chan bool, 1)
335
336 // Default false to check the liveliness.
337 kvStoreChannel <- false
338 for {
339 timeoutTimer := time.NewTimer(timeout)
340 select {
341 case liveliness := <-kvStoreChannel:
342 if !liveliness {
343 // kv-store not reachable or down, updating the status to not ready state
344 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
345 timeout = a.config.NotLiveProbeInterval
346 } else {
347 // kv-store is reachable , updating the status to running state
348 probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusRunning)
349 timeout = a.config.LiveProbeInterval / 2
350 }
351 // Check if the timer has expired or not
352 if !timeoutTimer.Stop() {
353 <-timeoutTimer.C
354 }
355 case <-timeoutTimer.C:
356 // Check the status of the kv-store
dbainbri4d3a0dc2020-12-02 00:33:42 +0000357 logger.Info(ctx, "kv-store liveliness-recheck")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000358 if a.kvClient.IsConnectionUp(ctx) {
359 kvStoreChannel <- true
360 } else {
361 kvStoreChannel <- false
362 }
363 }
364 }
365}
366
367/**
368This function checks the liveliness and readiness of the kafka service
369and update the status in the probe.
370*/
371func (a *adapter) checkKafkaReadiness(ctx context.Context) {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000372 livelinessChannel := a.kafkaClient.EnableLivenessChannel(ctx, true)
373 healthinessChannel := a.kafkaClient.EnableHealthinessChannel(ctx, true)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000374 timeout := a.config.LiveProbeInterval
375 for {
376 timeoutTimer := time.NewTimer(timeout)
377
378 select {
379 case healthiness := <-healthinessChannel:
380 if !healthiness {
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000381 // logger.Fatal will call os.Exit(1) to terminate
dbainbri4d3a0dc2020-12-02 00:33:42 +0000382 logger.Fatal(ctx, "Kafka service has become unhealthy")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000383 }
384 case liveliness := <-livelinessChannel:
385 if !liveliness {
386 // kafka not reachable or down, updating the status to not ready state
387 probe.UpdateStatusFromContext(ctx, "message-bus", probe.ServiceStatusNotReady)
388 timeout = a.config.NotLiveProbeInterval
389 } else {
390 // kafka is reachable , updating the status to running state
391 probe.UpdateStatusFromContext(ctx, "message-bus", probe.ServiceStatusRunning)
392 timeout = a.config.LiveProbeInterval
393 }
394 // Check if the timer has expired or not
395 if !timeoutTimer.Stop() {
396 <-timeoutTimer.C
397 }
398 case <-timeoutTimer.C:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000399 logger.Info(ctx, "kafka-proxy-liveness-recheck")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000400 // send the liveness probe in a goroutine; we don't want to deadlock ourselves as
401 // the liveness probe may wait (and block) writing to our channel.
dbainbri4d3a0dc2020-12-02 00:33:42 +0000402 err := a.kafkaClient.SendLiveness(ctx)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000403 if err != nil {
404 // Catch possible error case if sending liveness after Sarama has been stopped.
dbainbri4d3a0dc2020-12-02 00:33:42 +0000405 logger.Warnw(ctx, "error-kafka-send-liveness", log.Fields{"error": err})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000406 }
407 }
408 }
409}
410
411// Adapter Utility methods ##### end #########
412// #############################################
413
dbainbri4d3a0dc2020-12-02 00:33:42 +0000414func getVerifiedCodeVersion(ctx context.Context) string {
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000415 if version.VersionInfo.Version == "unknown-version" {
416 content, err := ioutil.ReadFile("VERSION")
417 if err == nil {
Andrea Campanella3d7c9312021-01-19 09:20:49 +0100418 return string(content)
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000419 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000420 logger.Error(ctx, "'VERSION'-file not readable")
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000421 }
422 return version.VersionInfo.Version
423}
424
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000425func printVersion(appName string) {
426 fmt.Println(appName)
427 fmt.Println(version.VersionInfo.String(" "))
428}
429
430func printBanner() {
431 fmt.Println(" ____ ____ ___ ___ _ ")
432 fmt.Println(" / __ \\ / __ \\| \\ \\ | | | | |")
433 fmt.Println(" | | | |_ __ ___ _ __ | | | | |\\ \\ | | | | | ____ ____")
434 fmt.Println(" | | | | '_ \\ / _ \\ '_ \\ | | | | | \\ \\ | | | | | / '_ \\ / _' \\")
435 fmt.Println(" | |__| | |_) | __/| | | || |__| | | \\ \\| | \\__/ || (__) | (__) |")
436 fmt.Println(" \\___ /| .__/ \\___|_| |_| \\____/|_| \\___|______| \\.___ |\\___./")
437 fmt.Println(" | | __| |")
438 fmt.Println(" |_| |____/")
439 fmt.Println(" ")
440}
441
442func waitForExit(ctx context.Context) int {
443 signalChannel := make(chan os.Signal, 1)
444 signal.Notify(signalChannel,
445 syscall.SIGHUP,
446 syscall.SIGINT,
447 syscall.SIGTERM,
448 syscall.SIGQUIT)
449
450 exitChannel := make(chan int)
451
452 go func() {
453 select {
454 case <-ctx.Done():
dbainbri4d3a0dc2020-12-02 00:33:42 +0000455 logger.Infow(ctx, "Adapter run aborted due to internal errors", log.Fields{"context": "done"})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000456 exitChannel <- 2
457 case s := <-signalChannel:
458 switch s {
459 case syscall.SIGHUP,
460 syscall.SIGINT,
461 syscall.SIGTERM,
462 syscall.SIGQUIT:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000463 logger.Infow(ctx, "closing-signal-received", log.Fields{"signal": s})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000464 exitChannel <- 0
465 default:
dbainbri4d3a0dc2020-12-02 00:33:42 +0000466 logger.Infow(ctx, "unexpected-signal-received", log.Fields{"signal": s})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000467 exitChannel <- 1
468 }
469 }
470 }()
471
472 code := <-exitChannel
473 return code
474}
475
476func main() {
477 start := time.Now()
dbainbri4d3a0dc2020-12-02 00:33:42 +0000478 ctx, cancel := context.WithCancel(context.Background())
479 defer cancel()
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000480
481 cf := config.NewAdapterFlags()
dbainbri4d3a0dc2020-12-02 00:33:42 +0000482 defaultAppName := cf.InstanceID + "_" + getVerifiedCodeVersion(ctx)
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000483 cf.ParseCommandArguments()
484
485 // Setup logging
486
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000487 logLevel, err := log.StringToLogLevel(cf.LogLevel)
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700488 if err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000489 logger.Fatalf(ctx, "Cannot setup logging, %s", err)
Matteo Scandolo2e6f1e32020-04-15 11:28:45 -0700490 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000491
492 // Setup default logger - applies for packages that do not have specific logger set
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000493 if _, err := log.SetDefaultLogger(log.JSON, logLevel, log.Fields{"instanceId": cf.InstanceID}); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000494 logger.With(log.Fields{"error": err}).Fatal(ctx, "Cannot setup logging")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000495 }
496
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000497 // Update all loggers (provisioned via init) with a common field
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000498 if err := log.UpdateAllLoggers(log.Fields{"instanceId": cf.InstanceID}); err != nil {
dbainbri4d3a0dc2020-12-02 00:33:42 +0000499 logger.With(log.Fields{"error": err}).Fatal(ctx, "Cannot setup logging")
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000500 }
501
Holger Hildebrandt0f9b88d2020-04-20 13:33:25 +0000502 log.SetAllLogLevel(logLevel)
503
dbainbri4d3a0dc2020-12-02 00:33:42 +0000504 realMain(ctx) //fatal on httpListen(0,6060) ...
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000505
Himani Chawla4d908332020-08-31 12:30:20 +0530506 defer func() {
507 _ = log.CleanUp()
508 }()
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000509 // Print version / build information and exit
510 if cf.DisplayVersionOnly {
511 printVersion(defaultAppName)
512 return
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000513 }
dbainbri4d3a0dc2020-12-02 00:33:42 +0000514 logger.Infow(ctx, "config", log.Fields{"StartName": defaultAppName})
515 logger.Infow(ctx, "config", log.Fields{"BuildVersion": version.VersionInfo.String(" ")})
516 logger.Infow(ctx, "config", log.Fields{"Arguments": os.Args[1:]})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000517
518 // Print banner if specified
519 if cf.Banner {
520 printBanner()
521 }
522
dbainbri4d3a0dc2020-12-02 00:33:42 +0000523 logger.Infow(ctx, "config", log.Fields{"config": *cf})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000524
525 ad := newAdapter(cf)
526
527 p := &probe.Probe{}
dbainbri4d3a0dc2020-12-02 00:33:42 +0000528 logger.Infow(ctx, "resources", log.Fields{"Context": ctx, "Adapter": ad.instanceID, "ProbeCoreState": p.GetStatus("register-with-core")})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000529
dbainbri4d3a0dc2020-12-02 00:33:42 +0000530 go p.ListenAndServe(ctx, fmt.Sprintf("%s:%d", ad.config.ProbeHost, ad.config.ProbePort))
531 logger.Infow(ctx, "probeState", log.Fields{"ProbeCoreState": p.GetStatus("register-with-core")})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000532
533 probeCtx := context.WithValue(ctx, probe.ProbeContextKey, p)
534
dbainbri4d3a0dc2020-12-02 00:33:42 +0000535 closer, err := log.GetGlobalLFM().InitTracingAndLogCorrelation(cf.TraceEnabled, cf.TraceAgentAddress, cf.LogCorrelationEnabled)
536 if err != nil {
537 logger.Warnw(ctx, "unable-to-initialize-tracing-and-log-correlation-module", log.Fields{"error": err})
538 } else {
539 defer log.TerminateTracing(closer)
540 }
541
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000542 go func() {
543 err := ad.start(probeCtx)
544 // If this operation returns an error
545 // cancel all operations using this context
546 if err != nil {
547 cancel()
548 }
549 }()
550
551 code := waitForExit(ctx)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000552 logger.Infow(ctx, "received-a-closing-signal", log.Fields{"code": code})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000553
554 // Cleanup before leaving
555 ad.stop(ctx)
556
557 elapsed := time.Since(start)
dbainbri4d3a0dc2020-12-02 00:33:42 +0000558 logger.Infow(ctx, "run-time", log.Fields{"Name": "openadapter", "time": elapsed / time.Microsecond})
559 //logger.Infow(ctx,"run-time", log.Fields{"instanceId": ad.config.InstanceID, "time": elapsed / time.Second})
Holger Hildebrandtfa074992020-03-27 15:42:06 +0000560}