blob: 9ddd79c2d14bc927b9e60ebd49cf83146d62641a [file] [log] [blame]
Pragya Arya324337e2020-02-20 14:35:08 +05301/*
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 */
16
17package common
18
19import (
20 "encoding/json"
21 "strconv"
22 "time"
23
24 "github.com/Shopify/sarama"
25 log "github.com/sirupsen/logrus"
26)
27
28var producer sarama.AsyncProducer
29var topic string
30
31// Event defines structure for bbsim events
32type Event struct {
33 EventType string
34 OnuSerial string
35 OltID int
36 IntfID int32
37 OnuID int32
38 EpochTime int64
39 Timestamp string
40}
41
42// InitializePublisher initalizes kafka publisher
43func InitializePublisher(oltID int) error {
44
45 var err error
46 sarama.Logger = log.New()
47 // producer config
48 config := sarama.NewConfig()
49 config.Producer.Retry.Max = 5
50 config.Metadata.Retry.Max = 10
51 config.Metadata.Retry.Backoff = 10 * time.Second
52 config.ClientID = "BBSim-OLT-" + strconv.Itoa(oltID)
53 topic = "BBSim-OLT-" + strconv.Itoa(oltID) + "-Events"
54
55 producer, err = sarama.NewAsyncProducer([]string{Options.BBSim.KafkaAddress}, config)
56 return err
57}
58
59// KafkaPublisher receives messages on eventChannel and publish them to kafka
60func KafkaPublisher(eventChannel chan Event) {
61 defer log.Debugf("KafkaPublisher stopped")
62 for {
63 select {
64 case event := <-eventChannel:
65 log.Debugf("Received event on channel %v", event)
66 jsonEvent, err := json.Marshal(event)
67 if err != nil {
68 log.Errorf("Failed to get json event %v", err)
69 continue
70 }
71 producer.Input() <- &sarama.ProducerMessage{
72 Topic: topic,
73 Value: sarama.ByteEncoder(jsonEvent),
74 }
75 log.Debugf("Event sent on kafka")
76 }
77 }
78}