blob: 00e08d29dc875d7f1bd3b148f3bdfcf93e32c021 [file] [log] [blame]
Kent Hagerman45a13e42020-04-13 12:23:50 -04001/*
2 * Copyright 2020-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 event
18
19import (
Rohan Agrawal31f21802020-06-12 05:38:46 +000020 "context"
Andrea Campanella4afb2f02021-01-29 09:38:57 +010021 "encoding/binary"
Kent Hagerman45a13e42020-04-13 12:23:50 -040022 "encoding/hex"
Himani Chawlab4c25912020-11-12 17:16:38 +053023 "fmt"
Himani Chawla606a4f02021-03-23 19:45:58 +053024 "sync"
25 "time"
26
Kent Hagerman45a13e42020-04-13 12:23:50 -040027 "github.com/golang/protobuf/ptypes/empty"
Himani Chawlab4c25912020-11-12 17:16:38 +053028 "github.com/opencord/voltha-go/rw_core/utils"
Mahir Gunyelb0343bf2021-05-11 14:14:26 -070029 ev "github.com/opencord/voltha-lib-go/v4/pkg/events"
Himani Chawlab4c25912020-11-12 17:16:38 +053030 "github.com/opencord/voltha-lib-go/v4/pkg/events/eventif"
Maninderdfadc982020-10-28 14:04:33 +053031 "github.com/opencord/voltha-lib-go/v4/pkg/log"
Himani Chawlab4c25912020-11-12 17:16:38 +053032 "github.com/opencord/voltha-protos/v4/go/common"
Maninderdfadc982020-10-28 14:04:33 +053033 "github.com/opencord/voltha-protos/v4/go/openflow_13"
34 "github.com/opencord/voltha-protos/v4/go/voltha"
Himani Chawlab4c25912020-11-12 17:16:38 +053035 "github.com/opentracing/opentracing-go"
36 jtracing "github.com/uber/jaeger-client-go"
Kent Hagerman45a13e42020-04-13 12:23:50 -040037)
38
39type Manager struct {
40 packetInQueue chan openflow_13.PacketIn
41 packetInQueueDone chan bool
42 changeEventQueue chan openflow_13.ChangeEvent
43 changeEventQueueDone chan bool
Mahir Gunyelb0343bf2021-05-11 14:14:26 -070044 Agent *Agent
Kent Hagerman45a13e42020-04-13 12:23:50 -040045}
46
Mahir Gunyelb0343bf2021-05-11 14:14:26 -070047type Agent struct {
Himani Chawlab4c25912020-11-12 17:16:38 +053048 eventProxy eventif.EventProxy
49 coreInstanceID string
Himani Chawla9cfc4992021-03-22 12:43:01 +053050 stackID string
Himani Chawlab4c25912020-11-12 17:16:38 +053051}
52
Mahir Gunyelb0343bf2021-05-11 14:14:26 -070053func NewManager(proxyForEvents eventif.EventProxy, instanceID string, stackID string) *Manager {
Kent Hagerman45a13e42020-04-13 12:23:50 -040054 return &Manager{
55 packetInQueue: make(chan openflow_13.PacketIn, 100),
56 packetInQueueDone: make(chan bool, 1),
57 changeEventQueue: make(chan openflow_13.ChangeEvent, 100),
58 changeEventQueueDone: make(chan bool, 1),
Mahir Gunyelb0343bf2021-05-11 14:14:26 -070059 Agent: NewAgent(proxyForEvents, instanceID, stackID),
Kent Hagerman45a13e42020-04-13 12:23:50 -040060 }
61}
62
Mahir Gunyelb0343bf2021-05-11 14:14:26 -070063func NewAgent(proxyForEvents eventif.EventProxy, instanceID string, stackID string) *Agent {
64 return &Agent{
65 eventProxy: proxyForEvents,
Himani Chawlab4c25912020-11-12 17:16:38 +053066 coreInstanceID: instanceID,
Himani Chawla9cfc4992021-03-22 12:43:01 +053067 stackID: stackID,
Himani Chawlab4c25912020-11-12 17:16:38 +053068 }
69}
Rohan Agrawal31f21802020-06-12 05:38:46 +000070func (q *Manager) SendPacketIn(ctx context.Context, deviceID string, transationID string, packet *openflow_13.OfpPacketIn) {
Kent Hagerman45a13e42020-04-13 12:23:50 -040071 // TODO: Augment the OF PacketIn to include the transactionId
72 packetIn := openflow_13.PacketIn{Id: deviceID, PacketIn: packet}
Himani Chawlab4c25912020-11-12 17:16:38 +053073 logger.Debugw(ctx, "send-packet-in", log.Fields{"packet-in": packetIn})
Kent Hagerman45a13e42020-04-13 12:23:50 -040074 q.packetInQueue <- packetIn
75}
76
77type callTracker struct {
78 failedPacket interface{}
79}
80type streamTracker struct {
81 calls map[string]*callTracker
82 sync.Mutex
83}
84
85var streamingTracker = &streamTracker{calls: make(map[string]*callTracker)}
86
Rohan Agrawal31f21802020-06-12 05:38:46 +000087func (q *Manager) getStreamingTracker(ctx context.Context, method string, done chan<- bool) *callTracker {
Kent Hagerman45a13e42020-04-13 12:23:50 -040088 streamingTracker.Lock()
89 defer streamingTracker.Unlock()
90 if _, ok := streamingTracker.calls[method]; ok {
91 // bail out the other packet in thread
Himani Chawlab4c25912020-11-12 17:16:38 +053092 logger.Debugf(ctx, "%s-streaming-call-already-running-exiting-it", method)
Kent Hagerman45a13e42020-04-13 12:23:50 -040093 done <- true
Himani Chawlab4c25912020-11-12 17:16:38 +053094 logger.Debugf(ctx, "last-%s-exited-continuing", method)
Kent Hagerman45a13e42020-04-13 12:23:50 -040095 } else {
96 streamingTracker.calls[method] = &callTracker{failedPacket: nil}
97 }
98 return streamingTracker.calls[method]
99}
100
Rohan Agrawal31f21802020-06-12 05:38:46 +0000101func (q *Manager) flushFailedPackets(ctx context.Context, tracker *callTracker) error {
Kent Hagerman45a13e42020-04-13 12:23:50 -0400102 if tracker.failedPacket != nil {
103 switch tracker.failedPacket.(type) {
104 case openflow_13.PacketIn:
Himani Chawlab4c25912020-11-12 17:16:38 +0530105 logger.Debug(ctx, "enqueueing-last-failed-packet-in")
Kent Hagerman45a13e42020-04-13 12:23:50 -0400106 q.packetInQueue <- tracker.failedPacket.(openflow_13.PacketIn)
107 case openflow_13.ChangeEvent:
Himani Chawlab4c25912020-11-12 17:16:38 +0530108 logger.Debug(ctx, "enqueueing-last-failed-change-event")
Kent Hagerman45a13e42020-04-13 12:23:50 -0400109 q.changeEventQueue <- tracker.failedPacket.(openflow_13.ChangeEvent)
110 }
111 }
112 return nil
113}
114
115// ReceivePacketsIn receives packets from adapter
116func (q *Manager) ReceivePacketsIn(_ *empty.Empty, packetsIn voltha.VolthaService_ReceivePacketsInServer) error {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000117 ctx := context.Background()
Himani Chawlab4c25912020-11-12 17:16:38 +0530118 ctx = utils.WithRPCMetadataContext(ctx, "ReceivePacketsIn")
Rohan Agrawal31f21802020-06-12 05:38:46 +0000119 var streamingTracker = q.getStreamingTracker(ctx, "ReceivePacketsIn", q.packetInQueueDone)
Himani Chawlab4c25912020-11-12 17:16:38 +0530120 logger.Debugw(ctx, "receive-packets-in-request", log.Fields{"packets-in": packetsIn})
Kent Hagerman45a13e42020-04-13 12:23:50 -0400121
Rohan Agrawal31f21802020-06-12 05:38:46 +0000122 err := q.flushFailedPackets(ctx, streamingTracker)
Kent Hagerman45a13e42020-04-13 12:23:50 -0400123 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000124 logger.Errorw(ctx, "unable-to-flush-failed-packets", log.Fields{"error": err})
Kent Hagerman45a13e42020-04-13 12:23:50 -0400125 }
126
127loop:
128 for {
129 select {
130 case packet := <-q.packetInQueue:
Rohan Agrawal31f21802020-06-12 05:38:46 +0000131 logger.Debugw(ctx, "sending-packet-in", log.Fields{
Kent Hagerman45a13e42020-04-13 12:23:50 -0400132 "packet": hex.EncodeToString(packet.PacketIn.Data),
133 })
134 if err := packetsIn.Send(&packet); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000135 logger.Errorw(ctx, "failed-to-send-packet", log.Fields{"error": err})
Mahir Gunyelb0343bf2021-05-11 14:14:26 -0700136 go q.Agent.GetAndSendRPCEvent(ctx, packet.Id, err.Error(),
Himani Chawlab4c25912020-11-12 17:16:38 +0530137 nil, "RPC_ERROR_RAISE_EVENT", voltha.EventCategory_COMMUNICATION,
Himani Chawla606a4f02021-03-23 19:45:58 +0530138 nil, time.Now().Unix())
Kent Hagerman45a13e42020-04-13 12:23:50 -0400139 // save the last failed packet in
140 streamingTracker.failedPacket = packet
141 } else {
142 if streamingTracker.failedPacket != nil {
143 // reset last failed packet saved to avoid flush
144 streamingTracker.failedPacket = nil
145 }
146 }
147 case <-q.packetInQueueDone:
Himani Chawlab4c25912020-11-12 17:16:38 +0530148 logger.Debug(ctx, "another-receive-packets-in-running-bailing-out")
Kent Hagerman45a13e42020-04-13 12:23:50 -0400149 break loop
150 }
151 }
152
153 //TODO: Find an elegant way to get out of the above loop when the Core is stopped
154 return nil
155}
156
Rohan Agrawal31f21802020-06-12 05:38:46 +0000157func (q *Manager) SendChangeEvent(ctx context.Context, deviceID string, reason openflow_13.OfpPortReason, desc *openflow_13.OfpPort) {
Himani Chawlab4c25912020-11-12 17:16:38 +0530158 logger.Debugw(ctx, "send-change-event", log.Fields{"device-id": deviceID, "reason": reason, "desc": desc})
Kent Hagermanfa9d6d42020-05-25 11:49:40 -0400159 q.changeEventQueue <- openflow_13.ChangeEvent{
160 Id: deviceID,
161 Event: &openflow_13.ChangeEvent_PortStatus{
162 PortStatus: &openflow_13.OfpPortStatus{
163 Reason: reason,
164 Desc: desc,
165 },
166 },
167 }
Kent Hagerman45a13e42020-04-13 12:23:50 -0400168}
169
Andrea Campanella4afb2f02021-01-29 09:38:57 +0100170func (q *Manager) SendFlowChangeEvent(ctx context.Context, deviceID string, res []error, xid uint32, flowCookie uint64) {
Himani Chawlab4c25912020-11-12 17:16:38 +0530171 logger.Debugw(ctx, "send-change-event", log.Fields{"device-id": deviceID,
172 "flow-id": xid, "flow-cookie": flowCookie, "errors": res})
Maninderf421da62020-12-04 11:44:58 +0530173 errorType := openflow_13.OfpErrorType_OFPET_FLOW_MOD_FAILED
Andrea Campanella4afb2f02021-01-29 09:38:57 +0100174 //Manually creating the data payload for the flow error message
175 bs := make([]byte, 2)
176 //OF 1.3
177 bs[0] = byte(4)
178 //Flow Mod
179 bs[1] = byte(14)
180 //Length of the message
181 length := make([]byte, 2)
182 binary.BigEndian.PutUint16(length, 56)
183 bs = append(bs, length...)
184 emptyArr := []byte{0, 0, 0, 0}
185 bs = append(bs, emptyArr...)
186 //Cookie of the Flow
187 cookie := make([]byte, 52)
188 binary.BigEndian.PutUint64(cookie, flowCookie)
189 bs = append(bs, cookie...)
Maninderf421da62020-12-04 11:44:58 +0530190 q.changeEventQueue <- openflow_13.ChangeEvent{
191 Id: deviceID,
192 Event: &openflow_13.ChangeEvent_Error{
193 Error: &openflow_13.OfpErrorMsg{
194 Header: &openflow_13.OfpHeader{
Andrea Campanella4afb2f02021-01-29 09:38:57 +0100195 Type: openflow_13.OfpType_OFPT_FLOW_MOD,
196 Xid: xid,
Maninderf421da62020-12-04 11:44:58 +0530197 },
198 Type: uint32(errorType),
199 Code: uint32(openflow_13.OfpFlowModFailedCode_OFPFMFC_UNKNOWN),
Andrea Campanella4afb2f02021-01-29 09:38:57 +0100200 Data: bs,
Maninderf421da62020-12-04 11:44:58 +0530201 },
202 },
203 }
204}
205
Kent Hagerman45a13e42020-04-13 12:23:50 -0400206// ReceiveChangeEvents receives change in events
207func (q *Manager) ReceiveChangeEvents(_ *empty.Empty, changeEvents voltha.VolthaService_ReceiveChangeEventsServer) error {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000208 ctx := context.Background()
Himani Chawlab4c25912020-11-12 17:16:38 +0530209 ctx = utils.WithRPCMetadataContext(ctx, "ReceiveChangeEvents")
Rohan Agrawal31f21802020-06-12 05:38:46 +0000210 var streamingTracker = q.getStreamingTracker(ctx, "ReceiveChangeEvents", q.changeEventQueueDone)
Himani Chawlab4c25912020-11-12 17:16:38 +0530211 logger.Debugw(ctx, "receive-change-events-request", log.Fields{"change-events": changeEvents})
Kent Hagerman45a13e42020-04-13 12:23:50 -0400212
Rohan Agrawal31f21802020-06-12 05:38:46 +0000213 err := q.flushFailedPackets(ctx, streamingTracker)
Kent Hagerman45a13e42020-04-13 12:23:50 -0400214 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000215 logger.Errorw(ctx, "unable-to-flush-failed-packets", log.Fields{"error": err})
Kent Hagerman45a13e42020-04-13 12:23:50 -0400216 }
217
218loop:
219 for {
220 select {
221 // Dequeue a change event
222 case event := <-q.changeEventQueue:
Rohan Agrawal31f21802020-06-12 05:38:46 +0000223 logger.Debugw(ctx, "sending-change-event", log.Fields{"event": event})
Kent Hagerman45a13e42020-04-13 12:23:50 -0400224 if err := changeEvents.Send(&event); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000225 logger.Errorw(ctx, "failed-to-send-change-event", log.Fields{"error": err})
Mahir Gunyelb0343bf2021-05-11 14:14:26 -0700226 go q.Agent.GetAndSendRPCEvent(ctx, event.Id, err.Error(),
Himani Chawlab4c25912020-11-12 17:16:38 +0530227 nil, "RPC_ERROR_RAISE_EVENT", voltha.EventCategory_COMMUNICATION, nil,
Himani Chawla606a4f02021-03-23 19:45:58 +0530228 time.Now().Unix())
Himani Chawlab4c25912020-11-12 17:16:38 +0530229 // save last failed change event
Kent Hagerman45a13e42020-04-13 12:23:50 -0400230 streamingTracker.failedPacket = event
231 } else {
232 if streamingTracker.failedPacket != nil {
233 // reset last failed event saved on success to avoid flushing
234 streamingTracker.failedPacket = nil
235 }
236 }
237 case <-q.changeEventQueueDone:
Himani Chawlab4c25912020-11-12 17:16:38 +0530238 logger.Debug(ctx, "another-receive-change-events-already-running-bailing-out")
Kent Hagerman45a13e42020-04-13 12:23:50 -0400239 break loop
240 }
241 }
242
243 return nil
244}
245
246func (q *Manager) GetChangeEventsQueueForTest() <-chan openflow_13.ChangeEvent {
247 return q.changeEventQueue
248}
Himani Chawlab4c25912020-11-12 17:16:38 +0530249
Mahir Gunyelb0343bf2021-05-11 14:14:26 -0700250func (q *Agent) NewRPCEvent(ctx context.Context, resourceID, desc string, context map[string]string) *voltha.RPCEvent {
Himani Chawlab4c25912020-11-12 17:16:38 +0530251 logger.Debugw(ctx, "new-rpc-event", log.Fields{"resource-id": resourceID})
252 var opID string
253 var rpc string
254
255 if span := opentracing.SpanFromContext(ctx); span != nil {
256 if jSpan, ok := span.(*jtracing.Span); ok {
257 opID = fmt.Sprintf("%016x", jSpan.SpanContext().TraceID().Low) // Using Sprintf to avoid removal of leading 0s
258 }
259 }
260 rpc = utils.GetRPCMetadataFromContext(ctx)
261 rpcev := &voltha.RPCEvent{
262 Rpc: rpc,
263 OperationId: opID,
264 ResourceId: resourceID,
265 Service: q.coreInstanceID,
Himani Chawla9cfc4992021-03-22 12:43:01 +0530266 StackId: q.stackID,
Himani Chawlab4c25912020-11-12 17:16:38 +0530267 Status: &common.OperationResp{
268 Code: common.OperationResp_OPERATION_FAILURE,
269 },
270 Description: desc,
271 Context: context,
272 }
273 return rpcev
274}
275
Mahir Gunyelb0343bf2021-05-11 14:14:26 -0700276func (q *Agent) SendRPCEvent(ctx context.Context, id string, rpcEvent *voltha.RPCEvent, category voltha.EventCategory_Types, subCategory *voltha.EventSubCategory_Types, raisedTs int64) {
277 //TODO Instead of directly sending to the kafka bus, queue the message and send it asynchronously
Himani Chawlab4c25912020-11-12 17:16:38 +0530278 if rpcEvent.Rpc != "" {
Himani Chawla606a4f02021-03-23 19:45:58 +0530279 if err := q.eventProxy.SendRPCEvent(ctx, id, rpcEvent, category, subCategory, raisedTs); err != nil {
280 logger.Errorw(ctx, "failed-to-send-rpc-event", log.Fields{"resource-id": id})
281 }
Himani Chawlab4c25912020-11-12 17:16:38 +0530282 }
283}
284
Mahir Gunyelb0343bf2021-05-11 14:14:26 -0700285func (q *Agent) GetAndSendRPCEvent(ctx context.Context, resourceID, desc string, context map[string]string,
Himani Chawlab4c25912020-11-12 17:16:38 +0530286 id string, category voltha.EventCategory_Types, subCategory *voltha.EventSubCategory_Types, raisedTs int64) {
287 rpcEvent := q.NewRPCEvent(ctx, resourceID, desc, context)
Himani Chawlab4c25912020-11-12 17:16:38 +0530288 if rpcEvent.Rpc != "" {
Himani Chawla606a4f02021-03-23 19:45:58 +0530289 if err := q.eventProxy.SendRPCEvent(ctx, id, rpcEvent, category, subCategory, raisedTs); err != nil {
290 logger.Errorw(ctx, "failed-to-send-rpc-event", log.Fields{"resource-id": id})
291 }
Himani Chawlab4c25912020-11-12 17:16:38 +0530292 }
293}
Mahir Gunyelb0343bf2021-05-11 14:14:26 -0700294
295// SendDeviceStateChangeEvent sends Device State Change Event to message bus
296func (q *Agent) SendDeviceStateChangeEvent(ctx context.Context,
297 prevOperStatus voltha.OperStatus_Types, prevConnStatus voltha.ConnectStatus_Types, prevAdminStatus voltha.AdminState_Types,
298 device *voltha.Device, raisedTs int64) error {
299 de := ev.CreateDeviceStateChangeEvent(device.SerialNumber, device.Id, device.ParentId,
300 prevOperStatus, prevConnStatus, prevAdminStatus,
301 device.OperStatus, device.ConnectStatus, device.AdminState,
302 device.ParentPortNo, device.Root)
303
304 subCategory := voltha.EventSubCategory_ONU
305 if device.Root {
306 subCategory = voltha.EventSubCategory_OLT
307 }
308 if err := q.eventProxy.SendDeviceEvent(ctx, de, voltha.EventCategory_EQUIPMENT, subCategory, raisedTs); err != nil {
309 logger.Errorw(ctx, "error-sending-device-event", log.Fields{"id": device.Id, "err": err})
310 return err
311 }
312 logger.Debugw(ctx, "device-state-change-sent", log.Fields{"event": *de})
313 return nil
314}