blob: caa29c07ad70183258c53957f85f5f525776594c [file] [log] [blame]
Scott Bakereee8dd82019-09-24 12:52:34 -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"
Scott Baker611f6bd2019-10-18 13:45:19 -070022 "github.com/opencord/voltha-lib-go/pkg/adapters"
23 com "github.com/opencord/voltha-lib-go/pkg/adapters/common"
24 "github.com/opencord/voltha-lib-go/pkg/db/kvstore"
25 "github.com/opencord/voltha-lib-go/pkg/kafka"
26 "github.com/opencord/voltha-lib-go/pkg/log"
27 "github.com/opencord/voltha-lib-go/pkg/probe"
28 "github.com/opencord/voltha-lib-go/pkg/version"
Scott Bakereee8dd82019-09-24 12:52:34 -070029 ic "github.com/opencord/voltha-protos/go/inter_container"
30 "github.com/opencord/voltha-protos/go/voltha"
Scott Baker70c16092019-09-30 17:08:54 -070031 ac "github.com/opencord/voltha-simonu-adapter/internal/pkg/adaptercore"
32 "github.com/opencord/voltha-simonu-adapter/internal/pkg/config"
Scott Bakereee8dd82019-09-24 12:52:34 -070033 "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
46 kip *kafka.InterContainerProxy
47 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 Ethiraj531322b2019-10-14 14:07:19 +000071 // If the context has a probe then fetch it and register our services
72 var p *probe.Probe
73 if value := ctx.Value(probe.ProbeContextKey); value != nil {
74 if _, ok := value.(*probe.Probe); ok {
75 p = value.(*probe.Probe)
76 p.RegisterService(
77 "message-bus",
78 "kv-store",
79 "container-proxy",
80 "core-request-handler",
81 "register-with-core",
82 )
83 }
84 }
85
Scott Bakereee8dd82019-09-24 12:52:34 -070086 // Setup KV Client
87 log.Debugw("create-kv-client", log.Fields{"kvstore": a.config.KVStoreType})
88 if err := a.setKVClient(); err != nil {
89 log.Fatal("error-setting-kv-client")
90 }
91
Vignesh Ethiraj531322b2019-10-14 14:07:19 +000092 if p != nil {
93 p.UpdateStatus("kv-store", probe.ServiceStatusRunning)
94 }
95
Scott Bakereee8dd82019-09-24 12:52:34 -070096 // Setup Kafka Client
97 if a.kafkaClient, err = newKafkaClient("sarama", a.config.KafkaAdapterHost, a.config.KafkaAdapterPort); err != nil {
98 log.Fatal("Unsupported-common-client")
99 }
100
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000101 if p != nil {
102 p.UpdateStatus("message-bus", probe.ServiceStatusRunning)
103 }
104
Scott Bakereee8dd82019-09-24 12:52:34 -0700105 // Start the common InterContainer Proxy - retry indefinitely
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000106 if a.kip, err = a.startInterContainerProxy(ctx, -1); err != nil {
Scott Bakereee8dd82019-09-24 12:52:34 -0700107 log.Fatal("error-starting-inter-container-proxy")
108 }
109
110 // Create the core proxy to handle requests to the Core
111 a.coreProxy = com.NewCoreProxy(a.kip, a.config.Topic, a.config.CoreTopic)
112
113 // Create the simulated OLT adapter
114 if a.iAdapter, err = a.startSimulatedONU(ctx, a.kip, a.coreProxy); err != nil {
115 log.Fatal("error-starting-inter-container-proxy")
116 }
117
118 // Register the core request handler
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000119 if err = a.setupRequestHandler(ctx, a.instanceId, a.iAdapter, a.coreProxy); err != nil {
Scott Bakereee8dd82019-09-24 12:52:34 -0700120 log.Fatal("error-setting-core-request-handler")
121 }
122
123 // Register this adapter to the Core - retry indefinitely
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000124 if err = a.registerWithCore(ctx, -1); err != nil {
Scott Bakereee8dd82019-09-24 12:52:34 -0700125 log.Fatal("error-registering-with-core")
126 }
127}
128
129func (rw *adapter) stop() {
130 // Stop leadership tracking
131 rw.halted = true
132
133 // send exit signal
134 rw.exitChannel <- 0
135
136 // Cleanup - applies only if we had a kvClient
137 if rw.kvClient != nil {
138 // Release all reservations
139 if err := rw.kvClient.ReleaseAllReservations(); err != nil {
140 log.Infow("fail-to-release-all-reservations", log.Fields{"error": err})
141 }
142 // Close the DB connection
143 rw.kvClient.Close()
144 }
145
146 // TODO: More cleanup
147}
148
149func newKVClient(storeType string, address string, timeout int) (kvstore.Client, error) {
150
151 log.Infow("kv-store-type", log.Fields{"store": storeType})
152 switch storeType {
153 case "consul":
154 return kvstore.NewConsulClient(address, timeout)
155 case "etcd":
156 return kvstore.NewEtcdClient(address, timeout)
157 }
158 return nil, errors.New("unsupported-kv-store")
159}
160
161func newKafkaClient(clientType string, host string, port int) (kafka.Client, error) {
162
163 log.Infow("common-client-type", log.Fields{"client": clientType})
164 switch clientType {
165 case "sarama":
166 return kafka.NewSaramaClient(
167 kafka.Host(host),
168 kafka.Port(port),
169 kafka.ProducerReturnOnErrors(true),
170 kafka.ProducerReturnOnSuccess(true),
171 kafka.ProducerMaxRetries(6),
172 kafka.ProducerRetryBackoff(time.Millisecond*30)), nil
173 }
174 return nil, errors.New("unsupported-client-type")
175}
176
177func (a *adapter) setKVClient() error {
178 addr := a.config.KVStoreHost + ":" + strconv.Itoa(a.config.KVStorePort)
179 client, err := newKVClient(a.config.KVStoreType, addr, a.config.KVStoreTimeout)
180 if err != nil {
181 a.kvClient = nil
182 log.Error(err)
183 return err
184 }
185 a.kvClient = client
186 return nil
187}
188
189func toString(value interface{}) (string, error) {
190 switch t := value.(type) {
191 case []byte:
192 return string(value.([]byte)), nil
193 case string:
194 return value.(string), nil
195 default:
196 return "", fmt.Errorf("unexpected-type-%T", t)
197 }
198}
199
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000200func (a *adapter) startInterContainerProxy(ctx context.Context, retries int) (*kafka.InterContainerProxy, error) {
Scott Bakereee8dd82019-09-24 12:52:34 -0700201 log.Infow("starting-intercontainer-messaging-proxy", log.Fields{"host": a.config.KafkaAdapterHost,
202 "port": a.config.KafkaAdapterPort, "topic": a.config.Topic})
203 var err error
204 var kip *kafka.InterContainerProxy
205 if kip, err = kafka.NewInterContainerProxy(
206 kafka.InterContainerHost(a.config.KafkaAdapterHost),
207 kafka.InterContainerPort(a.config.KafkaAdapterPort),
208 kafka.MsgClient(a.kafkaClient),
209 kafka.DefaultTopic(&kafka.Topic{Name: a.config.Topic})); err != nil {
210 log.Errorw("fail-to-create-common-proxy", log.Fields{"error": err})
211 return nil, err
212 }
213 count := 0
214 for {
215 if err = kip.Start(); err != nil {
216 log.Warnw("error-starting-messaging-proxy", log.Fields{"error": err})
217 if retries == count {
218 return nil, err
219 }
220 count = +1
221 // Take a nap before retrying
222 time.Sleep(2 * time.Second)
223 } else {
224 break
225 }
226 }
227
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000228 probe.UpdateStatusFromContext(ctx, "container-proxy", probe.ServiceStatusRunning)
Scott Bakereee8dd82019-09-24 12:52:34 -0700229 log.Info("common-messaging-proxy-created")
230 return kip, nil
231}
232
233func (a *adapter) startSimulatedONU(ctx context.Context, kip *kafka.InterContainerProxy, cp *com.CoreProxy) (*ac.SimulatedONU, error) {
234 log.Info("starting-simulated-onu")
235 var err error
236 sOLT := ac.NewSimulatedONU(ctx, a.kip, cp)
237
238 if err = sOLT.Start(ctx); err != nil {
239 log.Fatalw("error-starting-messaging-proxy", log.Fields{"error": err})
240 return nil, err
241 }
242
243 log.Info("simulated-olt-started")
244 return sOLT, nil
245}
246
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000247func (a *adapter) setupRequestHandler(ctx context.Context, coreInstanceId string, iadapter adapters.IAdapter, coreProxy *com.CoreProxy) error {
Scott Bakereee8dd82019-09-24 12:52:34 -0700248 log.Info("setting-request-handler")
249 requestProxy := com.NewRequestHandlerProxy(coreInstanceId, iadapter, coreProxy)
250 if err := a.kip.SubscribeWithRequestHandlerInterface(kafka.Topic{Name: a.config.Topic}, requestProxy); err != nil {
251 log.Errorw("adaptercore-request-handler-setup-failed", log.Fields{"error": err})
252 return err
253
254 }
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000255 probe.UpdateStatusFromContext(ctx, "core-request-handler", probe.ServiceStatusRunning)
Scott Bakereee8dd82019-09-24 12:52:34 -0700256 log.Info("request-handler-setup-done")
257 return nil
258}
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000259func (a *adapter) registerWithCore(ctx context.Context, retries int) error {
Scott Bakereee8dd82019-09-24 12:52:34 -0700260 log.Info("registering-with-core")
Vignesh Ethiraj893bd8d2019-09-26 10:07:49 +0000261 adapterDescription := &voltha.Adapter{
262 Id: "simulated_onu",
263 Vendor: "Open Networking Foundation",
264 Version: version.VersionInfo.Version,
265 }
Scott Bakereee8dd82019-09-24 12:52:34 -0700266 types := []*voltha.DeviceType{{Id: "simulated_onu", Adapter: "simulated_onu"}}
267 deviceTypes := &voltha.DeviceTypes{Items: types}
268 count := 0
269 for {
270 if err := a.coreProxy.RegisterAdapter(nil, adapterDescription, deviceTypes); err != nil {
271 log.Warnw("registering-with-core-failed", log.Fields{"error": err})
272 if retries == count {
273 return err
274 }
275 count += 1
276 // Take a nap before retrying
277 time.Sleep(2 * time.Second)
278 } else {
279 break
280 }
281 }
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000282 probe.UpdateStatusFromContext(ctx, "register-with-core", probe.ServiceStatusRunning)
Scott Bakereee8dd82019-09-24 12:52:34 -0700283 log.Info("registered-with-core")
284 return nil
285}
286
287func waitForExit() int {
288 signalChannel := make(chan os.Signal, 1)
289 signal.Notify(signalChannel,
290 syscall.SIGHUP,
291 syscall.SIGINT,
292 syscall.SIGTERM,
293 syscall.SIGQUIT)
294
295 exitChannel := make(chan int)
296
297 go func() {
298 s := <-signalChannel
299 switch s {
300 case syscall.SIGHUP,
301 syscall.SIGINT,
302 syscall.SIGTERM,
303 syscall.SIGQUIT:
304 log.Infow("closing-signal-received", log.Fields{"signal": s})
305 exitChannel <- 0
306 default:
307 log.Infow("unexpected-signal-received", log.Fields{"signal": s})
308 exitChannel <- 1
309 }
310 }()
311
312 code := <-exitChannel
313 return code
314}
315
316func printBanner() {
317 fmt.Println(" _ _ _ _ ")
318 fmt.Println(" ___(_)_ __ ___ _ _| | __ _| |_ ___ __| | ___ _ __ _ _ ")
319 fmt.Println("/ __| | '_ ` _ \\| | | | |/ _` | __/ _ \\/ _` | / _ \\| '_ \\| | | | ")
320 fmt.Println("\\__ \\ | | | | | | |_| | | (_| | || __/ (_| | | (_) | | | | |_| | ")
321 fmt.Println("|___/_|_| |_| |_|\\__,_|_|\\__,_|\\__\\___|\\__,_|___\\___/|_| |_|\\__,_| ")
322 fmt.Println(" |_____| ")
323 fmt.Println(" ")
324}
325
326func main() {
327 start := time.Now()
328
329 cf := config.NewAdapterFlags()
330 cf.ParseCommandArguments()
331
332 //// Setup logging
333
334 //Setup default logger - applies for packages that do not have specific logger set
335 if _, err := log.SetDefaultLogger(log.JSON, cf.LogLevel, log.Fields{"instanceId": cf.InstanceID}); err != nil {
336 log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
337 }
338
339 // Update all loggers (provisionned via init) with a common field
340 if err := log.UpdateAllLoggers(log.Fields{"instanceId": cf.InstanceID}); err != nil {
341 log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
342 }
343
Scott Baker611f6bd2019-10-18 13:45:19 -0700344 log.SetPackageLogLevel("github.com/opencord/voltha-lib-go/pkg/adapters/common", log.DebugLevel)
Scott Bakereee8dd82019-09-24 12:52:34 -0700345
346 defer log.CleanUp()
347
348 // Print banner if specified
349 if cf.Banner {
350 printBanner()
351 }
352
353 log.Infow("config", log.Fields{"config": *cf})
354
355 ctx, cancel := context.WithCancel(context.Background())
356 defer cancel()
357
358 ad := newAdapter(cf)
Vignesh Ethiraj531322b2019-10-14 14:07:19 +0000359
360 p := &probe.Probe{}
361 go p.ListenAndServe(fmt.Sprintf("%s:%d", ad.config.ProbeHost, ad.config.ProbePort))
362 probeCtx := context.WithValue(ctx, probe.ProbeContextKey, p)
363 go ad.start(probeCtx)
Scott Bakereee8dd82019-09-24 12:52:34 -0700364
365 code := waitForExit()
366 log.Infow("received-a-closing-signal", log.Fields{"code": code})
367
368 // Cleanup before leaving
369 ad.stop()
370
371 elapsed := time.Since(start)
372 log.Infow("runtime", log.Fields{"instanceId": ad.config.InstanceID, "time": elapsed / time.Second})
373}