blob: 152447413dd0daef14c99e02a62f35bb60952569 [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 */
khenaidoob9203542018-09-17 22:56:37 -040016package core
khenaidoobf6e7bb2018-08-14 22:27:29 -040017
18import (
19 "context"
20 "errors"
21 "github.com/golang/protobuf/ptypes/empty"
22 da "github.com/opencord/voltha-go/common/core/northbound/grpc"
23 "github.com/opencord/voltha-go/common/log"
24 "github.com/opencord/voltha-go/protos/common"
25 "github.com/opencord/voltha-go/protos/openflow_13"
26 "github.com/opencord/voltha-go/protos/voltha"
khenaidoob9203542018-09-17 22:56:37 -040027 "google.golang.org/grpc/codes"
khenaidoobf6e7bb2018-08-14 22:27:29 -040028 "google.golang.org/grpc/metadata"
khenaidoob9203542018-09-17 22:56:37 -040029 "google.golang.org/grpc/status"
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050030 "io"
31 "time"
khenaidoobf6e7bb2018-08-14 22:27:29 -040032)
33
Richard Jankowskid42826e2018-11-02 16:06:37 -040034const MAX_RESPONSE_TIME = 500 // milliseconds
35
khenaidoobf6e7bb2018-08-14 22:27:29 -040036type APIHandler struct {
khenaidoob9203542018-09-17 22:56:37 -040037 deviceMgr *DeviceManager
38 logicalDeviceMgr *LogicalDeviceManager
khenaidoobf6e7bb2018-08-14 22:27:29 -040039 da.DefaultAPIHandler
40}
41
khenaidoo9a468962018-09-19 15:33:13 -040042func NewAPIHandler(deviceMgr *DeviceManager, lDeviceMgr *LogicalDeviceManager) *APIHandler {
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050043 handler := &APIHandler{
44 deviceMgr: deviceMgr,
45 logicalDeviceMgr: lDeviceMgr,
46 }
khenaidoobf6e7bb2018-08-14 22:27:29 -040047 return handler
48}
khenaidoo4d4802d2018-10-04 21:59:49 -040049
50// isTestMode is a helper function to determine a function is invoked for testing only
khenaidoobf6e7bb2018-08-14 22:27:29 -040051func isTestMode(ctx context.Context) bool {
52 md, _ := metadata.FromIncomingContext(ctx)
53 _, exist := md[common.TestModeKeys_api_test.String()]
54 return exist
55}
56
Richard Jankowskid42826e2018-11-02 16:06:37 -040057// This function attempts to extract the serial number from the request metadata
58// and create a KV transaction for that serial number for the current core.
59func (handler *APIHandler) createKvTransaction(ctx context.Context) (*KVTransaction, error) {
60 var (
61 err error
62 ok bool
63 md metadata.MD
64 serNum []string
65 )
66 if md, ok = metadata.FromIncomingContext(ctx); !ok {
67 err = errors.New("metadata-not-found")
68 } else if serNum, ok = md["voltha_serial_number"]; !ok {
69 err = errors.New("serial-number-not-found")
70 }
71 if !ok {
72 log.Error(err)
73 return nil, err
74 }
75 // Create KV transaction
76 txn := NewKVTransaction(serNum[0])
77 return txn, nil
78}
79
khenaidoo4d4802d2018-10-04 21:59:49 -040080// waitForNilResponseOnSuccess is a helper function to wait for a response on channel ch where an nil
81// response is expected in a successful scenario
82func waitForNilResponseOnSuccess(ctx context.Context, ch chan interface{}) (*empty.Empty, error) {
83 select {
84 case res := <-ch:
85 if res == nil {
86 return new(empty.Empty), nil
87 } else if err, ok := res.(error); ok {
88 return new(empty.Empty), err
89 } else {
90 log.Warnw("unexpected-return-type", log.Fields{"result": res})
91 err = status.Errorf(codes.Internal, "%s", res)
92 return new(empty.Empty), err
93 }
94 case <-ctx.Done():
95 log.Debug("client-timeout")
96 return nil, ctx.Err()
97 }
98}
99
khenaidoobf6e7bb2018-08-14 22:27:29 -0400100func (handler *APIHandler) UpdateLogLevel(ctx context.Context, logging *voltha.Logging) (*empty.Empty, error) {
101 log.Debugw("UpdateLogLevel-request", log.Fields{"newloglevel": logging.Level, "intval": int(logging.Level)})
khenaidoo92e62c52018-10-03 14:02:54 -0400102 out := new(empty.Empty)
103 log.SetPackageLogLevel(logging.PackageName, int(logging.Level))
104 return out, nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400105}
106
107func (handler *APIHandler) EnableLogicalDevicePort(ctx context.Context, id *voltha.LogicalPortId) (*empty.Empty, error) {
108 log.Debugw("EnableLogicalDevicePort-request", log.Fields{"id": id, "test": common.TestModeKeys_api_test.String()})
109 if isTestMode(ctx) {
110 out := new(empty.Empty)
111 return out, nil
112 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400113 ch := make(chan interface{})
114 defer close(ch)
khenaidoo19d7b632018-10-30 10:49:50 -0400115 go handler.logicalDeviceMgr.enableLogicalPort(ctx, id, ch)
khenaidoo4d4802d2018-10-04 21:59:49 -0400116 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400117}
118
119func (handler *APIHandler) DisableLogicalDevicePort(ctx context.Context, id *voltha.LogicalPortId) (*empty.Empty, error) {
120 log.Debugw("DisableLogicalDevicePort-request", log.Fields{"id": id, "test": common.TestModeKeys_api_test.String()})
121 if isTestMode(ctx) {
122 out := new(empty.Empty)
123 return out, nil
124 }
khenaidoo19d7b632018-10-30 10:49:50 -0400125 ch := make(chan interface{})
126 defer close(ch)
127 go handler.logicalDeviceMgr.disableLogicalPort(ctx, id, ch)
128 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400129}
130
131func (handler *APIHandler) UpdateLogicalDeviceFlowTable(ctx context.Context, flow *openflow_13.FlowTableUpdate) (*empty.Empty, error) {
132 log.Debugw("UpdateLogicalDeviceFlowTable-request", log.Fields{"flow": flow, "test": common.TestModeKeys_api_test.String()})
133 if isTestMode(ctx) {
134 out := new(empty.Empty)
135 return out, nil
136 }
khenaidoo19d7b632018-10-30 10:49:50 -0400137 ch := make(chan interface{})
138 defer close(ch)
139 go handler.logicalDeviceMgr.updateFlowTable(ctx, flow.Id, flow.FlowMod, ch)
140 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400141}
142
143func (handler *APIHandler) UpdateLogicalDeviceFlowGroupTable(ctx context.Context, flow *openflow_13.FlowGroupTableUpdate) (*empty.Empty, error) {
144 log.Debugw("UpdateLogicalDeviceFlowGroupTable-request", log.Fields{"flow": flow, "test": common.TestModeKeys_api_test.String()})
145 if isTestMode(ctx) {
146 out := new(empty.Empty)
147 return out, nil
148 }
khenaidoo19d7b632018-10-30 10:49:50 -0400149 ch := make(chan interface{})
150 defer close(ch)
151 go handler.logicalDeviceMgr.updateGroupTable(ctx, flow.Id, flow.GroupMod, ch)
152 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400153}
154
khenaidoob9203542018-09-17 22:56:37 -0400155// GetDevice must be implemented in the read-only containers - should it also be implemented here?
156func (handler *APIHandler) GetDevice(ctx context.Context, id *voltha.ID) (*voltha.Device, error) {
157 log.Debugw("GetDevice-request", log.Fields{"id": id})
khenaidoo19d7b632018-10-30 10:49:50 -0400158 return handler.deviceMgr.GetDevice(id.Id)
khenaidoob9203542018-09-17 22:56:37 -0400159}
160
161// GetDevice must be implemented in the read-only containers - should it also be implemented here?
162func (handler *APIHandler) ListDevices(ctx context.Context, empty *empty.Empty) (*voltha.Devices, error) {
163 log.Debug("ListDevices")
164 return handler.deviceMgr.ListDevices()
165}
166
167// GetLogicalDevice must be implemented in the read-only containers - should it also be implemented here?
168func (handler *APIHandler) GetLogicalDevice(ctx context.Context, id *voltha.ID) (*voltha.LogicalDevice, error) {
169 log.Debugw("GetLogicalDevice-request", log.Fields{"id": id})
170 return handler.logicalDeviceMgr.getLogicalDevice(id.Id)
171}
172
173// ListLogicalDevices must be implemented in the read-only containers - should it also be implemented here?
174func (handler *APIHandler) ListLogicalDevices(ctx context.Context, empty *empty.Empty) (*voltha.LogicalDevices, error) {
175 log.Debug("ListLogicalDevices")
176 return handler.logicalDeviceMgr.listLogicalDevices()
177}
178
khenaidoo19d7b632018-10-30 10:49:50 -0400179// ListLogicalDevicePorts must be implemented in the read-only containers - should it also be implemented here?
180func (handler *APIHandler) ListLogicalDevicePorts(ctx context.Context, id *voltha.ID) (*voltha.LogicalPorts, error) {
181 log.Debugw("ListLogicalDevicePorts", log.Fields{"logicaldeviceid": id})
182 return handler.logicalDeviceMgr.ListLogicalDevicePorts(ctx, id.Id)
183}
184
khenaidoo4d4802d2018-10-04 21:59:49 -0400185// CreateDevice creates a new parent device in the data model
khenaidoobf6e7bb2018-08-14 22:27:29 -0400186func (handler *APIHandler) CreateDevice(ctx context.Context, device *voltha.Device) (*voltha.Device, error) {
khenaidoob9203542018-09-17 22:56:37 -0400187 log.Debugw("createdevice", log.Fields{"device": *device})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400188 if isTestMode(ctx) {
189 return &voltha.Device{Id: device.Id}, nil
190 }
Richard Jankowskid42826e2018-11-02 16:06:37 -0400191
192 txn, err := handler.createKvTransaction(ctx)
193 if txn == nil {
194 return &voltha.Device{}, err
195 } else if txn.Acquired(MAX_RESPONSE_TIME) {
196 defer txn.Close() // Ensure active core signals "done" to standby
197 } else {
198 return &voltha.Device{}, nil
199 }
200
khenaidoob9203542018-09-17 22:56:37 -0400201 ch := make(chan interface{})
202 defer close(ch)
203 go handler.deviceMgr.createDevice(ctx, device, ch)
204 select {
205 case res := <-ch:
khenaidoo92e62c52018-10-03 14:02:54 -0400206 if res != nil {
207 if err, ok := res.(error); ok {
208 return &voltha.Device{}, err
209 }
210 if d, ok := res.(*voltha.Device); ok {
211 return d, nil
212 }
khenaidoob9203542018-09-17 22:56:37 -0400213 }
khenaidoo92e62c52018-10-03 14:02:54 -0400214 log.Warnw("create-device-unexpected-return-type", log.Fields{"result": res})
215 err := status.Errorf(codes.Internal, "%s", res)
216 return &voltha.Device{}, err
khenaidoob9203542018-09-17 22:56:37 -0400217 case <-ctx.Done():
218 log.Debug("createdevice-client-timeout")
219 return nil, ctx.Err()
220 }
khenaidoobf6e7bb2018-08-14 22:27:29 -0400221}
222
khenaidoo4d4802d2018-10-04 21:59:49 -0400223// EnableDevice activates a device by invoking the adopt_device API on the appropriate adapter
khenaidoobf6e7bb2018-08-14 22:27:29 -0400224func (handler *APIHandler) EnableDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
khenaidoob9203542018-09-17 22:56:37 -0400225 log.Debugw("enabledevice", log.Fields{"id": id})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400226 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400227 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400228 }
Richard Jankowskid42826e2018-11-02 16:06:37 -0400229
230 txn, err := handler.createKvTransaction(ctx)
231 if txn == nil {
232 return new(empty.Empty), err
233 } else if txn.Acquired(MAX_RESPONSE_TIME) {
234 defer txn.Close() // Ensure active core signals "done" to standby
235 } else {
236 return new(empty.Empty), nil
237 }
238
khenaidoob9203542018-09-17 22:56:37 -0400239 ch := make(chan interface{})
240 defer close(ch)
241 go handler.deviceMgr.enableDevice(ctx, id, ch)
khenaidoo4d4802d2018-10-04 21:59:49 -0400242 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400243}
244
khenaidoo4d4802d2018-10-04 21:59:49 -0400245// DisableDevice disables a device along with any child device it may have
khenaidoobf6e7bb2018-08-14 22:27:29 -0400246func (handler *APIHandler) DisableDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
247 log.Debugw("disabledevice-request", log.Fields{"id": id})
248 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400249 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400250 }
khenaidoo92e62c52018-10-03 14:02:54 -0400251 ch := make(chan interface{})
252 defer close(ch)
253 go handler.deviceMgr.disableDevice(ctx, id, ch)
khenaidoo4d4802d2018-10-04 21:59:49 -0400254 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400255}
256
khenaidoo4d4802d2018-10-04 21:59:49 -0400257//RebootDevice invoked the reboot API to the corresponding adapter
khenaidoobf6e7bb2018-08-14 22:27:29 -0400258func (handler *APIHandler) RebootDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400259 log.Debugw("rebootDevice-request", log.Fields{"id": id})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400260 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400261 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400262 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400263 ch := make(chan interface{})
264 defer close(ch)
265 go handler.deviceMgr.rebootDevice(ctx, id, ch)
266 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400267}
268
khenaidoo4d4802d2018-10-04 21:59:49 -0400269// DeleteDevice removes a device from the data model
khenaidoobf6e7bb2018-08-14 22:27:29 -0400270func (handler *APIHandler) DeleteDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
271 log.Debugw("deletedevice-request", log.Fields{"id": id})
272 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400273 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400274 }
khenaidoo4d4802d2018-10-04 21:59:49 -0400275 ch := make(chan interface{})
276 defer close(ch)
277 go handler.deviceMgr.deleteDevice(ctx, id, ch)
278 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400279}
280
281func (handler *APIHandler) DownloadImage(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
282 log.Debugw("DownloadImage-request", log.Fields{"img": *img})
283 if isTestMode(ctx) {
284 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
285 return resp, nil
286 }
287
288 return nil, errors.New("UnImplemented")
289}
290
291func (handler *APIHandler) CancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
292 log.Debugw("CancelImageDownload-request", log.Fields{"img": *img})
293 if isTestMode(ctx) {
294 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
295 return resp, nil
296 }
297 return nil, errors.New("UnImplemented")
298}
299
300func (handler *APIHandler) ActivateImageUpdate(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
301 log.Debugw("ActivateImageUpdate-request", log.Fields{"img": *img})
302 if isTestMode(ctx) {
303 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
304 return resp, nil
305 }
306 return nil, errors.New("UnImplemented")
307}
308
309func (handler *APIHandler) RevertImageUpdate(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
310 log.Debugw("RevertImageUpdate-request", log.Fields{"img": *img})
311 if isTestMode(ctx) {
312 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
313 return resp, nil
314 }
315 return nil, errors.New("UnImplemented")
316}
317
318func (handler *APIHandler) UpdateDevicePmConfigs(ctx context.Context, configs *voltha.PmConfigs) (*empty.Empty, error) {
319 log.Debugw("UpdateDevicePmConfigs-request", log.Fields{"configs": *configs})
320 if isTestMode(ctx) {
321 out := new(empty.Empty)
322 return out, nil
323 }
324 return nil, errors.New("UnImplemented")
325}
326
327func (handler *APIHandler) CreateAlarmFilter(ctx context.Context, filter *voltha.AlarmFilter) (*voltha.AlarmFilter, error) {
328 log.Debugw("CreateAlarmFilter-request", log.Fields{"filter": *filter})
329 if isTestMode(ctx) {
330 f := &voltha.AlarmFilter{Id: filter.Id}
331 return f, nil
332 }
333 return nil, errors.New("UnImplemented")
334}
335
336func (handler *APIHandler) UpdateAlarmFilter(ctx context.Context, filter *voltha.AlarmFilter) (*voltha.AlarmFilter, error) {
337 log.Debugw("UpdateAlarmFilter-request", log.Fields{"filter": *filter})
338 if isTestMode(ctx) {
339 f := &voltha.AlarmFilter{Id: filter.Id}
340 return f, nil
341 }
342 return nil, errors.New("UnImplemented")
343}
344
345func (handler *APIHandler) DeleteAlarmFilter(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
346 log.Debugw("DeleteAlarmFilter-request", log.Fields{"id": *id})
347 if isTestMode(ctx) {
348 out := new(empty.Empty)
349 return out, nil
350 }
351 return nil, errors.New("UnImplemented")
352}
353
354func (handler *APIHandler) SelfTest(ctx context.Context, id *voltha.ID) (*voltha.SelfTestResponse, error) {
355 log.Debugw("SelfTest-request", log.Fields{"id": id})
356 if isTestMode(ctx) {
357 resp := &voltha.SelfTestResponse{Result: voltha.SelfTestResponse_SUCCESS}
358 return resp, nil
359 }
360 return nil, errors.New("UnImplemented")
361}
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500362
363func (handler *APIHandler) forwardPacketOut(packet *openflow_13.PacketOut) {
364 log.Debugw("forwardPacketOut-request", log.Fields{"packet": packet})
365 //agent := handler.logicalDeviceMgr.getLogicalDeviceAgent(packet.Id)
366 //agent.packetOut(packet.PacketOut)
367}
368func (handler *APIHandler) StreamPacketsOut(
369 packets voltha.VolthaService_StreamPacketsOutServer,
370) error {
371 log.Debugw("StreamPacketsOut-request", log.Fields{"packets": packets})
372 for {
373 packet, err := packets.Recv()
374
375 if err == io.EOF {
376 break
377 } else if err != nil {
378 log.Errorw("Failed to receive packet", log.Fields{"error": err})
379 }
380
381 handler.forwardPacketOut(packet)
382 }
383
384 log.Debugw("StreamPacketsOut-request-done", log.Fields{"packets": packets})
385 return nil
386}
387
388func (handler *APIHandler) sendPacketIn(deviceId string, packet *openflow_13.OfpPacketIn) {
389 packetIn := openflow_13.PacketIn{Id: deviceId, PacketIn: packet}
390 log.Debugw("sendPacketIn", log.Fields{"packetIn": packetIn})
391 // TODO: put the packet in the queue
392}
393
394func (handler *APIHandler) ReceivePacketsIn(
395 empty *empty.Empty,
396 packetsIn voltha.VolthaService_ReceivePacketsInServer,
397) error {
398 log.Debugw("ReceivePacketsIn-request", log.Fields{"packetsIn": packetsIn})
399
400 for {
401 // TODO: need to retrieve packet from queue
402 packet := &openflow_13.PacketIn{}
403 time.Sleep(time.Duration(5) * time.Second)
404 err := packetsIn.Send(packet)
405 if err != nil {
406 log.Errorw("Failed to send packet", log.Fields{"error": err})
407 }
408 }
409 log.Debugw("ReceivePacketsIn-request-done", log.Fields{"packetsIn": packetsIn})
410 return nil
411}
412
413func (handler *APIHandler) sendChangeEvent(deviceId string, portStatus *openflow_13.OfpPortStatus) {
414 // TODO: validate the type of portStatus parameter
415 //if _, ok := portStatus.(*openflow_13.OfpPortStatus); ok {
416 //}
417 event := openflow_13.ChangeEvent{Id: deviceId, Event: &openflow_13.ChangeEvent_PortStatus{PortStatus: portStatus}}
418 log.Debugw("sendChangeEvent", log.Fields{"event": event})
419 // TODO: put the packet in the queue
420}
421
422func (handler *APIHandler) ReceiveChangeEvents(
423 empty *empty.Empty,
424 changeEvents voltha.VolthaService_ReceiveChangeEventsServer,
425) error {
426 log.Debugw("ReceiveChangeEvents-request", log.Fields{"changeEvents": changeEvents})
427 for {
428 // TODO: need to retrieve packet from queue
429 event := &openflow_13.ChangeEvent{}
430 time.Sleep(time.Duration(5) * time.Second)
431 err := changeEvents.Send(event)
432 if err != nil {
433 log.Errorw("Failed to send change event", log.Fields{"error": err})
434 }
435 }
436 return nil
437}
438
439func (handler *APIHandler) Subscribe(
440 ctx context.Context,
441 ofAgent *voltha.OfAgentSubscriber,
442) (*voltha.OfAgentSubscriber, error) {
443 log.Debugw("Subscribe-request", log.Fields{"ofAgent": ofAgent})
444 return &voltha.OfAgentSubscriber{OfagentId: ofAgent.OfagentId, VolthaId: ofAgent.VolthaId}, nil
445}