blob: e907aad13aa217404d3ff54723ab7d0e3dd98032 [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:
Matteo Scandolo446fc9e2020-03-13 15:48:13 -070065 log.WithFields(log.Fields{
66 "EventType": event.EventType,
67 "OnuSerial": event.OnuSerial,
68 "OltID": event.OltID,
69 "IntfID": event.IntfID,
70 "OnuID": event.OnuID,
71 "EpochTime": event.EpochTime,
72 "Timestamp": event.Timestamp,
73 }).Trace("Received event on channel")
Pragya Arya324337e2020-02-20 14:35:08 +053074 jsonEvent, err := json.Marshal(event)
75 if err != nil {
76 log.Errorf("Failed to get json event %v", err)
77 continue
78 }
79 producer.Input() <- &sarama.ProducerMessage{
80 Topic: topic,
81 Value: sarama.ByteEncoder(jsonEvent),
82 }
Matteo Scandolo446fc9e2020-03-13 15:48:13 -070083 log.WithFields(log.Fields{
84 "EventType": event.EventType,
85 "OnuSerial": event.OnuSerial,
86 "OltID": event.OltID,
87 "IntfID": event.IntfID,
88 "OnuID": event.OnuID,
89 "EpochTime": event.EpochTime,
90 "Timestamp": event.Timestamp,
91 }).Debug("Event sent on kafka")
Pragya Arya324337e2020-02-20 14:35:08 +053092 }
93 }
94}