blob: 3af255609e9b390952dda0edf94d4ffe2c4fba99 [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -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 */
16
17package model
18
19import (
20 "encoding/json"
21 "github.com/golang/protobuf/proto"
Scott Bakere73f91e2019-10-17 12:58:11 -070022 "github.com/opencord/voltha-lib-go/pkg/log"
Scott Baker2c1c4822019-10-16 11:02:41 -070023 "github.com/opencord/voltha-protos/go/voltha"
24)
25
26// EventBus contains the details required to communicate with the event bus mechanism
27type EventBus struct {
28 client *EventBusClient
29 topic string
30}
31
32// ignoredCallbacks keeps a list of callbacks that should not be advertised on the event bus
33var (
34 ignoredCallbacks = map[CallbackType]struct{}{
35 PRE_ADD: {},
36 GET: {},
37 POST_LISTCHANGE: {},
38 PRE_REMOVE: {},
39 PRE_UPDATE: {},
40 }
41)
42
43// NewEventBus creates a new instance of the EventBus structure
44func NewEventBus() *EventBus {
45 bus := &EventBus{
46 client: NewEventBusClient(),
47 topic: "model-change-events",
48 }
49 return bus
50}
51
52// Advertise will publish the provided information to the event bus
53func (bus *EventBus) Advertise(args ...interface{}) interface{} {
54 eventType := args[0].(CallbackType)
55 hash := args[1].(string)
56 data := args[2:]
57
58 if _, ok := ignoredCallbacks[eventType]; ok {
59 log.Debugf("ignoring event - type:%s, data:%+v", eventType, data)
60 }
61 var kind voltha.ConfigEventType_ConfigEventType
62 switch eventType {
63 case POST_ADD:
64 kind = voltha.ConfigEventType_add
65 case POST_REMOVE:
66 kind = voltha.ConfigEventType_remove
67 default:
68 kind = voltha.ConfigEventType_update
69 }
70
71 var msg []byte
72 var err error
73 if IsProtoMessage(data) {
74 if msg, err = proto.Marshal(data[0].(proto.Message)); err != nil {
75 log.Debugf("problem marshalling proto data: %+v, err:%s", data[0], err.Error())
76 }
77 } else if data[0] != nil {
78 if msg, err = json.Marshal(data[0]); err != nil {
79 log.Debugf("problem marshalling json data: %+v, err:%s", data[0], err.Error())
80 }
81 } else {
82 log.Debugf("no data to advertise : %+v", data[0])
83 }
84
85 event := voltha.ConfigEvent{
86 Type: kind,
87 Hash: hash,
88 Data: string(msg),
89 }
90
91 bus.client.Publish(bus.topic, event)
92
93 return nil
94}