blob: 6afc63b186465a6ced2016e7f4b86b2d6009c066 [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
Stephane Barbarie694e2b92018-09-07 12:17:36 -040047//func (bus *EventBus) Advertise(eventType CallbackType, data interface{}, hash string) {
48func (bus *EventBus) Advertise(args ...interface{}) interface{} {
49 eventType := args[0].(CallbackType)
50 data := args[1]
51 hash := args[2].(string)
52
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040053 if _, ok := IGNORED_CALLBACKS[eventType]; ok {
54 fmt.Printf("ignoring event - type:%s, data:%+v\n", eventType, data)
55 }
56 var kind voltha.ConfigEventType_ConfigEventType
57 switch eventType {
58 case POST_ADD:
59 kind = voltha.ConfigEventType_add
60 case POST_REMOVE:
61 kind = voltha.ConfigEventType_remove
62 default:
63 kind = voltha.ConfigEventType_update
64 }
65
66 var msg []byte
67 var err error
68 if IsProtoMessage(data) {
69 if msg, err = json.Marshal(data); err != nil {
70 fmt.Errorf("problem marshalling data: %+v, err:%s\n", data, err.Error())
71 }
72 } else {
73 msg = data.([]byte)
74 }
75
76 event := voltha.ConfigEvent{
77 Type: kind,
78 Hash: hash,
79 Data: string(msg),
80 }
81
82 bus.client.Publish(bus.topic, event)
Stephane Barbarie694e2b92018-09-07 12:17:36 -040083
84 return nil
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040085}