blob: c20eac377becfc2c22ef8a963cbea1bd37faae59 [file] [log] [blame]
khenaidoobf6e7bb2018-08-14 22:27:29 -04001/*
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 */
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040016package model
17
18import (
19 "encoding/json"
20 "fmt"
Stephane Barbarieec0919b2018-09-05 14:14:29 -040021 "github.com/opencord/voltha-go/protos/voltha"
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040022)
23
24type EventBus struct {
25 client *EventBusClient
26 topic string
27}
28
29var (
30 IGNORED_CALLBACKS = map[CallbackType]struct{}{
31 PRE_ADD: {},
32 GET: {},
33 POST_LISTCHANGE: {},
34 PRE_REMOVE: {},
35 PRE_UPDATE: {},
36 }
37)
38
39func NewEventBus() *EventBus {
40 bus := &EventBus{
41 client: NewEventBusClient(),
42 topic: "model-change-events",
43 }
44 return bus
45}
46
47func (bus *EventBus) Advertise(eventType CallbackType, data interface{}, hash string) {
48 if _, ok := IGNORED_CALLBACKS[eventType]; ok {
49 fmt.Printf("ignoring event - type:%s, data:%+v\n", eventType, data)
50 }
51 var kind voltha.ConfigEventType_ConfigEventType
52 switch eventType {
53 case POST_ADD:
54 kind = voltha.ConfigEventType_add
55 case POST_REMOVE:
56 kind = voltha.ConfigEventType_remove
57 default:
58 kind = voltha.ConfigEventType_update
59 }
60
61 var msg []byte
62 var err error
63 if IsProtoMessage(data) {
64 if msg, err = json.Marshal(data); err != nil {
65 fmt.Errorf("problem marshalling data: %+v, err:%s\n", data, err.Error())
66 }
67 } else {
68 msg = data.([]byte)
69 }
70
71 event := voltha.ConfigEvent{
72 Type: kind,
73 Hash: hash,
74 Data: string(msg),
75 }
76
77 bus.client.Publish(bus.topic, event)
78}