blob: 2166feccc03d4d90f861296077c63f56de4785bd [file] [log] [blame]
Scott Baker2d897982019-09-24 11:50:08 -07001/*
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 */
16package main
17
18import (
19 "context"
20 "errors"
21 "fmt"
Matteo Scandolo5c686162020-04-17 09:36:58 -070022 "github.com/opencord/voltha-lib-go/v3/pkg/adapters"
23 com "github.com/opencord/voltha-lib-go/v3/pkg/adapters/common"
24 "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
25 "github.com/opencord/voltha-lib-go/v3/pkg/kafka"
26 "github.com/opencord/voltha-lib-go/v3/pkg/log"
27 "github.com/opencord/voltha-lib-go/v3/pkg/probe"
28 "github.com/opencord/voltha-lib-go/v3/pkg/version"
29 ic "github.com/opencord/voltha-protos/v3/go/inter_container"
30 "github.com/opencord/voltha-protos/v3/go/voltha"
Scott Baker2d897982019-09-24 11:50:08 -070031 ac "github.com/opencord/voltha-simolt-adapter/internal/pkg/adaptercore"
32 "github.com/opencord/voltha-simolt-adapter/internal/pkg/config"
33 "os"
34 "os/signal"
35 "strconv"
36 "syscall"
37 "time"
38)
39
40type adapter struct {
41 instanceId string
42 config *config.AdapterFlags
43 iAdapter adapters.IAdapter
44 kafkaClient kafka.Client
45 kvClient kvstore.Client
Matteo Scandolo5c686162020-04-17 09:36:58 -070046 kip kafka.InterContainerProxy
Scott Baker2d897982019-09-24 11:50:08 -070047 coreProxy *com.CoreProxy
48 halted bool
49 exitChannel chan int
50 receiverChannels []<-chan *ic.InterContainerMessage
51}
52
53func init() {
54 log.AddPackage(log.JSON, log.DebugLevel, nil)
55}
56
57func newAdapter(cf *config.AdapterFlags) *adapter {
58 var a adapter
59 a.instanceId = cf.InstanceID
60 a.config = cf
61 a.halted = false
62 a.exitChannel = make(chan int, 1)
63 a.receiverChannels = make([]<-chan *ic.InterContainerMessage, 0)
64 return &a
65}
66
67func (a *adapter) start(ctx context.Context) {
68 log.Info("Starting Core Adapter components")
69 var err error
70
Vignesh Ethiraj5620c672019-10-14 13:18:52 +000071 var p *probe.Probe
72 if value := ctx.Value(probe.ProbeContextKey); value != nil {
73 if _, ok := value.(*probe.Probe); ok {
74 p = value.(*probe.Probe)
75 p.RegisterService(
76 "message-bus",
77 "kv-store",
78 "container-proxy",
79 "core-request-handler",
80 "register-with-core",
81 )
82 }
83 }
84
Scott Baker2d897982019-09-24 11:50:08 -070085 // Setup KV Client
86 log.Debugw("create-kv-client", log.Fields{"kvstore": a.config.KVStoreType})
87 if err := a.setKVClient(); err != nil {
88 log.Fatal("error-setting-kv-client")
89 }
90
Vignesh Ethiraj5620c672019-10-14 13:18:52 +000091 if p != nil {
92 p.UpdateStatus("kv-store", probe.ServiceStatusRunning)
93 }
94
Scott Baker2d897982019-09-24 11:50:08 -070095 // Setup Kafka Client
96 if a.kafkaClient, err = newKafkaClient("sarama", a.config.KafkaAdapterHost, a.config.KafkaAdapterPort); err != nil {
97 log.Fatal("Unsupported-common-client")
98 }
99
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000100 if p != nil {
101 p.UpdateStatus("message-bus", probe.ServiceStatusRunning)
102 }
103
Scott Baker2d897982019-09-24 11:50:08 -0700104 // Start the common InterContainer Proxy - retries indefinitely
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000105 if a.kip, err = a.startInterContainerProxy(ctx, -1); err != nil {
Scott Baker2d897982019-09-24 11:50:08 -0700106 log.Fatal("error-starting-inter-container-proxy")
107 }
108
109 // Create the core proxy to handle requests to the Core
110 a.coreProxy = com.NewCoreProxy(a.kip, a.config.Topic, a.config.CoreTopic)
111
112 // Create the simulated OLT adapter
113 if a.iAdapter, err = a.startSimulatedOLT(ctx, a.kip, a.coreProxy, a.config.OnuNumber); err != nil {
114 log.Fatal("error-starting-inter-container-proxy")
115 }
116
117 // Register the core request handler
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000118 if err = a.setupRequestHandler(ctx, a.instanceId, a.iAdapter, a.coreProxy); err != nil {
Scott Baker2d897982019-09-24 11:50:08 -0700119 log.Fatal("error-setting-core-request-handler")
120 }
121
122 // Register this adapter to the Core - retries indefinitely
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000123 if err = a.registerWithCore(ctx, -1); err != nil {
Scott Baker2d897982019-09-24 11:50:08 -0700124 log.Fatal("error-registering-with-core")
125 }
126}
127
Matteo Scandolo5c686162020-04-17 09:36:58 -0700128func (rw *adapter) stop(ctx context.Context) {
Scott Baker2d897982019-09-24 11:50:08 -0700129 // Stop leadership tracking
130 rw.halted = true
131
132 // send exit signal
133 rw.exitChannel <- 0
134
135 // Cleanup - applies only if we had a kvClient
136 if rw.kvClient != nil {
137 // Release all reservations
Matteo Scandolo5c686162020-04-17 09:36:58 -0700138 if err := rw.kvClient.ReleaseAllReservations(ctx); err != nil {
Scott Baker2d897982019-09-24 11:50:08 -0700139 log.Infow("fail-to-release-all-reservations", log.Fields{"error": err})
140 }
141 // Close the DB connection
142 rw.kvClient.Close()
143 }
144
145 // TODO: More cleanup
146}
147
148func newKVClient(storeType string, address string, timeout int) (kvstore.Client, error) {
149
150 log.Infow("kv-store-type", log.Fields{"store": storeType})
151 switch storeType {
152 case "consul":
153 return kvstore.NewConsulClient(address, timeout)
154 case "etcd":
155 return kvstore.NewEtcdClient(address, timeout)
156 }
157 return nil, errors.New("unsupported-kv-store")
158}
159
160func newKafkaClient(clientType string, host string, port int) (kafka.Client, error) {
161
162 log.Infow("common-client-type", log.Fields{"client": clientType})
163 switch clientType {
164 case "sarama":
165 return kafka.NewSaramaClient(
166 kafka.Host(host),
167 kafka.Port(port),
168 kafka.ProducerReturnOnErrors(true),
169 kafka.ProducerReturnOnSuccess(true),
170 kafka.ProducerMaxRetries(6),
171 kafka.ProducerRetryBackoff(time.Millisecond*30)), nil
172 }
173 return nil, errors.New("unsupported-client-type")
174}
175
176func (a *adapter) setKVClient() error {
177 addr := a.config.KVStoreHost + ":" + strconv.Itoa(a.config.KVStorePort)
178 client, err := newKVClient(a.config.KVStoreType, addr, a.config.KVStoreTimeout)
179 if err != nil {
180 a.kvClient = nil
181 log.Error(err)
182 return err
183 }
184 a.kvClient = client
185 return nil
186}
187
188func toString(value interface{}) (string, error) {
189 switch t := value.(type) {
190 case []byte:
191 return string(value.([]byte)), nil
192 case string:
193 return value.(string), nil
194 default:
195 return "", fmt.Errorf("unexpected-type-%T", t)
196 }
197}
198
Matteo Scandolo5c686162020-04-17 09:36:58 -0700199func (a *adapter) startInterContainerProxy(ctx context.Context, retries int) (kafka.InterContainerProxy, error) {
Scott Baker2d897982019-09-24 11:50:08 -0700200 log.Infow("starting-intercontainer-messaging-proxy", log.Fields{"host": a.config.KafkaAdapterHost,
201 "port": a.config.KafkaAdapterPort, "topic": a.config.Topic})
202 var err error
Matteo Scandolo5c686162020-04-17 09:36:58 -0700203 kip := kafka.NewInterContainerProxy(
Scott Baker2d897982019-09-24 11:50:08 -0700204 kafka.InterContainerHost(a.config.KafkaAdapterHost),
205 kafka.InterContainerPort(a.config.KafkaAdapterPort),
206 kafka.MsgClient(a.kafkaClient),
Matteo Scandolo5c686162020-04-17 09:36:58 -0700207 kafka.DefaultTopic(&kafka.Topic{Name: a.config.Topic}))
Scott Baker2d897982019-09-24 11:50:08 -0700208 count := 0
209 for {
210 if err = kip.Start(); err != nil {
211 log.Warnw("error-starting-messaging-proxy", log.Fields{"error": err})
212 if retries == count {
213 return nil, err
214 }
215 count = +1
216 // Take a nap before retrying
217 time.Sleep(2 * time.Second)
218 } else {
219 break
220 }
221 }
222
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000223 probe.UpdateStatusFromContext(ctx, "container-proxy", probe.ServiceStatusRunning)
Scott Baker2d897982019-09-24 11:50:08 -0700224 log.Info("common-messaging-proxy-created")
225 return kip, nil
226}
227
Matteo Scandolo5c686162020-04-17 09:36:58 -0700228func (a *adapter) startSimulatedOLT(ctx context.Context, kip kafka.InterContainerProxy, cp *com.CoreProxy, onuNumber int) (*ac.SimulatedOLT, error) {
Scott Baker2d897982019-09-24 11:50:08 -0700229 log.Info("starting-simulated-olt")
230 var err error
231 sOLT := ac.NewSimulatedOLT(ctx, a.kip, cp, onuNumber)
232
233 if err = sOLT.Start(ctx); err != nil {
234 log.Fatalw("error-starting-messaging-proxy", log.Fields{"error": err})
235 return nil, err
236 }
237
238 log.Info("simulated-olt-started")
239 return sOLT, nil
240}
241
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000242func (a *adapter) setupRequestHandler(ctx context.Context, coreInstanceId string, iadapter adapters.IAdapter, coreProxy *com.CoreProxy) error {
Scott Baker2d897982019-09-24 11:50:08 -0700243 log.Info("setting-request-handler")
244 requestProxy := com.NewRequestHandlerProxy(coreInstanceId, iadapter, coreProxy)
245 if err := a.kip.SubscribeWithRequestHandlerInterface(kafka.Topic{Name: a.config.Topic}, requestProxy); err != nil {
246 log.Errorw("request-handler-setup-failed", log.Fields{"error": err})
247 return err
248
249 }
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000250 probe.UpdateStatusFromContext(ctx, "core-request-handler", probe.ServiceStatusRunning)
Scott Baker2d897982019-09-24 11:50:08 -0700251 log.Info("request-handler-setup-done")
252 return nil
253}
254
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000255func (a *adapter) registerWithCore(ctx context.Context, retries int) error {
Scott Baker2d897982019-09-24 11:50:08 -0700256 log.Info("registering-with-core")
Vignesh Ethiraje872b172019-09-26 10:01:47 +0000257 adapterDescription := &voltha.Adapter{
Matteo Scandolo5c686162020-04-17 09:36:58 -0700258 Id: "simulated_olt_1",
Vignesh Ethiraje872b172019-09-26 10:01:47 +0000259 Vendor: "Open Networking Foundation",
260 Version: version.VersionInfo.Version,
Matteo Scandolo5c686162020-04-17 09:36:58 -0700261 Type: "simulated_olt",
262 // TODO add parameters to deploy multiple replicas
263 CurrentReplica: 1,
264 TotalReplicas: 1,
265 Endpoint: "simulated_olt",
266
Vignesh Ethiraje872b172019-09-26 10:01:47 +0000267 }
Scott Baker2d897982019-09-24 11:50:08 -0700268 types := []*voltha.DeviceType{{Id: "simulated_olt", Adapter: "simulated_olt", AcceptsAddRemoveFlowUpdates: true}}
269 deviceTypes := &voltha.DeviceTypes{Items: types}
270 count := 0
271 for {
272 if err := a.coreProxy.RegisterAdapter(nil, adapterDescription, deviceTypes); err != nil {
273 log.Warnw("registering-with-core-failed", log.Fields{"error": err})
274 if retries == count {
275 return err
276 }
277 count += 1
278 // Take a nap before retrying
279 time.Sleep(2 * time.Second)
280 } else {
281 break
282 }
283 }
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000284 probe.UpdateStatusFromContext(ctx, "register-with-core", probe.ServiceStatusRunning)
Scott Baker2d897982019-09-24 11:50:08 -0700285 log.Info("registered-with-core")
286 return nil
287}
288
289func waitForExit() int {
290 signalChannel := make(chan os.Signal, 1)
291 signal.Notify(signalChannel,
292 syscall.SIGHUP,
293 syscall.SIGINT,
294 syscall.SIGTERM,
295 syscall.SIGQUIT)
296
297 exitChannel := make(chan int)
298
299 go func() {
300 s := <-signalChannel
301 switch s {
302 case syscall.SIGHUP,
303 syscall.SIGINT,
304 syscall.SIGTERM,
305 syscall.SIGQUIT:
306 log.Infow("closing-signal-received", log.Fields{"signal": s})
307 exitChannel <- 0
308 default:
309 log.Infow("unexpected-signal-received", log.Fields{"signal": s})
310 exitChannel <- 1
311 }
312 }()
313
314 code := <-exitChannel
315 return code
316}
317
318func printBanner() {
319 fmt.Println(" ____ _ _ _ _ ___ _ _____ ")
320 fmt.Println("/ ___|(_)_ __ ___ _ _| | __ _| |_ ___ __| |/ _ \\| | |_ _| ")
321 fmt.Println("\\___ \\| | '_ ` _ \\| | | | |/ _` | __/ _ \\/ _` | | | | | | | ")
322 fmt.Println(" ___) | | | | | | | |_| | | (_| | || __/ (_| | |_| | |___| | ")
323 fmt.Println("|____/|_|_| |_| |_|\\__,_|_|\\__,_|\\__\\___|\\__,_|\\___/|_____|_| ")
324 fmt.Println(" ")
325}
326
327func main() {
328 start := time.Now()
329
330 cf := config.NewAdapterFlags()
331 cf.ParseCommandArguments()
332
David Bainbridge8ea2c9d2019-10-22 21:35:22 +0000333 if cf.PrintVersion {
334 fmt.Println(version.VersionInfo.String(""))
335 return
336 }
337
Scott Baker2d897982019-09-24 11:50:08 -0700338 //// Setup logging
Matteo Scandolo5c686162020-04-17 09:36:58 -0700339 logLevel, err := log.StringToLogLevel(cf.LogLevel)
340 if err != nil {
341 log.Fatalf("Cannot setup logging, %s", err)
342 }
Scott Baker2d897982019-09-24 11:50:08 -0700343
344 //Setup default logger - applies for packages that do not have specific logger set
Matteo Scandolo5c686162020-04-17 09:36:58 -0700345 if _, err := log.SetDefaultLogger(log.JSON, logLevel, log.Fields{"instanceId": cf.InstanceID}); err != nil {
Scott Baker2d897982019-09-24 11:50:08 -0700346 log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
347 }
348
349 // Update all loggers (provisionned via init) with a common field
350 if err := log.UpdateAllLoggers(log.Fields{"instanceId": cf.InstanceID}); err != nil {
351 log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
352 }
353
Matteo Scandolo5c686162020-04-17 09:36:58 -0700354 log.SetPackageLogLevel("github.com/opencord/voltha-lib-go/v3/pkg/adapters/common", log.DebugLevel)
Scott Baker2d897982019-09-24 11:50:08 -0700355
356 defer log.CleanUp()
357
358 // Print banner if specified
359 if cf.Banner {
360 printBanner()
361 }
362
363 log.Infow("config", log.Fields{"config": *cf})
364
365 ctx, cancel := context.WithCancel(context.Background())
366 defer cancel()
367
368 ad := newAdapter(cf)
Vignesh Ethiraj5620c672019-10-14 13:18:52 +0000369
370 p := &probe.Probe{}
371 go p.ListenAndServe(fmt.Sprintf("%s:%d", ad.config.ProbeHost, ad.config.ProbePort))
372
373 probeCtx := context.WithValue(ctx, probe.ProbeContextKey, p)
374
375 go ad.start(probeCtx)
Scott Baker2d897982019-09-24 11:50:08 -0700376
377 code := waitForExit()
378 log.Infow("received-a-closing-signal", log.Fields{"code": code})
379
380 // Cleanup before leaving
Matteo Scandolo5c686162020-04-17 09:36:58 -0700381 ad.stop(ctx)
Scott Baker2d897982019-09-24 11:50:08 -0700382
383 elapsed := time.Since(start)
384 log.Infow("run-time", log.Fields{"instanceId": ad.config.InstanceID, "time": elapsed / time.Second})
385}