blob: 4c82471dfd06568e7b87ff1d85962c00afba89b0 [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"
Richard Jankowskidbab94a2018-12-06 16:20:25 -050021 "github.com/golang-collections/go-datastructures/queue"
khenaidoobf6e7bb2018-08-14 22:27:29 -040022 "github.com/golang/protobuf/ptypes/empty"
23 da "github.com/opencord/voltha-go/common/core/northbound/grpc"
24 "github.com/opencord/voltha-go/common/log"
25 "github.com/opencord/voltha-go/protos/common"
26 "github.com/opencord/voltha-go/protos/openflow_13"
27 "github.com/opencord/voltha-go/protos/voltha"
khenaidoob9203542018-09-17 22:56:37 -040028 "google.golang.org/grpc/codes"
khenaidoobf6e7bb2018-08-14 22:27:29 -040029 "google.golang.org/grpc/metadata"
khenaidoob9203542018-09-17 22:56:37 -040030 "google.golang.org/grpc/status"
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050031 "io"
32 "time"
khenaidoobf6e7bb2018-08-14 22:27:29 -040033)
34
Richard Jankowski2755adf2019-01-17 17:16:48 -050035//TODO: Move this Tag into the proto file
36const OF_CONTROLLER_TAG= "voltha_backend_name"
37
khenaidoo9cdc1a62019-01-24 21:57:40 -050038const MAX_RESPONSE_TIME = int64(500) // milliseconds
Richard Jankowskid42826e2018-11-02 16:06:37 -040039
khenaidoof5a5bfa2019-01-23 22:20:29 -050040const (
41 IMAGE_DOWNLOAD = iota
42 CANCEL_IMAGE_DOWNLOAD = iota
43 ACTIVATE_IMAGE = iota
44 REVERT_IMAGE = iota
45)
46
khenaidoobf6e7bb2018-08-14 22:27:29 -040047type APIHandler struct {
khenaidoob9203542018-09-17 22:56:37 -040048 deviceMgr *DeviceManager
49 logicalDeviceMgr *LogicalDeviceManager
khenaidood2b6df92018-12-13 16:37:20 -050050 packetInQueue *queue.Queue
khenaidoo9cdc1a62019-01-24 21:57:40 -050051 coreInCompetingMode bool
khenaidoobf6e7bb2018-08-14 22:27:29 -040052 da.DefaultAPIHandler
53}
54
khenaidoo9cdc1a62019-01-24 21:57:40 -050055func NewAPIHandler(deviceMgr *DeviceManager, lDeviceMgr *LogicalDeviceManager, inCompetingMode bool) *APIHandler {
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050056 handler := &APIHandler{
57 deviceMgr: deviceMgr,
58 logicalDeviceMgr: lDeviceMgr,
khenaidoo9cdc1a62019-01-24 21:57:40 -050059 coreInCompetingMode:inCompetingMode,
Richard Jankowskidbab94a2018-12-06 16:20:25 -050060 // TODO: Figure out what the 'hint' parameter to queue.New does
khenaidood2b6df92018-12-13 16:37:20 -050061 packetInQueue: queue.New(10),
Stephane Barbarie6e1bd502018-11-05 22:44:45 -050062 }
khenaidoobf6e7bb2018-08-14 22:27:29 -040063 return handler
64}
khenaidoo4d4802d2018-10-04 21:59:49 -040065
66// isTestMode is a helper function to determine a function is invoked for testing only
khenaidoobf6e7bb2018-08-14 22:27:29 -040067func isTestMode(ctx context.Context) bool {
68 md, _ := metadata.FromIncomingContext(ctx)
69 _, exist := md[common.TestModeKeys_api_test.String()]
70 return exist
71}
72
Richard Jankowskid42826e2018-11-02 16:06:37 -040073// This function attempts to extract the serial number from the request metadata
74// and create a KV transaction for that serial number for the current core.
75func (handler *APIHandler) createKvTransaction(ctx context.Context) (*KVTransaction, error) {
76 var (
khenaidoo43c82122018-11-22 18:38:28 -050077 err error
78 ok bool
79 md metadata.MD
Richard Jankowskid42826e2018-11-02 16:06:37 -040080 serNum []string
81 )
82 if md, ok = metadata.FromIncomingContext(ctx); !ok {
83 err = errors.New("metadata-not-found")
84 } else if serNum, ok = md["voltha_serial_number"]; !ok {
85 err = errors.New("serial-number-not-found")
86 }
87 if !ok {
88 log.Error(err)
89 return nil, err
90 }
91 // Create KV transaction
92 txn := NewKVTransaction(serNum[0])
93 return txn, nil
94}
95
Richard Jankowski2755adf2019-01-17 17:16:48 -050096// isOFControllerRequest is a helper function to determine if a request was initiated
97// from the OpenFlow controller (or its proxy, e.g. OFAgent)
98func isOFControllerRequest(ctx context.Context) bool {
khenaidoo9cdc1a62019-01-24 21:57:40 -050099 if md, ok := metadata.FromIncomingContext(ctx); ok {
100 // Metadata in context
101 if _, ok = md[OF_CONTROLLER_TAG]; ok {
102 // OFAgent field in metadata
103 return true
104 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500105 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500106 return false
107}
108
109// competeForTransaction is a helper function to determine whether every request needs to compete with another
110// Core to execute the request
111func (handler *APIHandler) competeForTransaction() bool {
112 return handler.coreInCompetingMode
113}
114
115func (handler *APIHandler) acquireTransaction(ctx context.Context, maxTimeout ...int64) (*KVTransaction, error) {
116 timeout := MAX_RESPONSE_TIME
117 if len(maxTimeout) > 0 {
118 timeout = maxTimeout[0]
Richard Jankowski2755adf2019-01-17 17:16:48 -0500119 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500120 txn, err := handler.createKvTransaction(ctx)
121 if txn == nil {
122 return nil, err
123 } else if txn.Acquired(timeout) {
124 return txn, nil
125 } else {
126 return nil, errors.New("failed-to-seize-request")
Richard Jankowski2755adf2019-01-17 17:16:48 -0500127 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500128}
129
khenaidoo4d4802d2018-10-04 21:59:49 -0400130// waitForNilResponseOnSuccess is a helper function to wait for a response on channel ch where an nil
131// response is expected in a successful scenario
132func waitForNilResponseOnSuccess(ctx context.Context, ch chan interface{}) (*empty.Empty, error) {
133 select {
134 case res := <-ch:
135 if res == nil {
136 return new(empty.Empty), nil
137 } else if err, ok := res.(error); ok {
138 return new(empty.Empty), err
139 } else {
140 log.Warnw("unexpected-return-type", log.Fields{"result": res})
141 err = status.Errorf(codes.Internal, "%s", res)
142 return new(empty.Empty), err
143 }
144 case <-ctx.Done():
145 log.Debug("client-timeout")
146 return nil, ctx.Err()
147 }
148}
149
khenaidoobf6e7bb2018-08-14 22:27:29 -0400150func (handler *APIHandler) UpdateLogLevel(ctx context.Context, logging *voltha.Logging) (*empty.Empty, error) {
khenaidoo6f2fbe32019-01-18 16:16:50 -0500151 log.Debugw("UpdateLogLevel-request", log.Fields{"package": logging.PackageName, "intval": int(logging.Level)})
khenaidoo92e62c52018-10-03 14:02:54 -0400152 out := new(empty.Empty)
khenaidoo6f2fbe32019-01-18 16:16:50 -0500153 if logging.PackageName == "" {
154 log.SetAllLogLevel(int(logging.Level))
155 } else {
156 log.SetPackageLogLevel(logging.PackageName, int(logging.Level))
157 }
khenaidoo92e62c52018-10-03 14:02:54 -0400158 return out, nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400159}
160
161func (handler *APIHandler) EnableLogicalDevicePort(ctx context.Context, id *voltha.LogicalPortId) (*empty.Empty, error) {
162 log.Debugw("EnableLogicalDevicePort-request", log.Fields{"id": id, "test": common.TestModeKeys_api_test.String()})
163 if isTestMode(ctx) {
164 out := new(empty.Empty)
165 return out, nil
166 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500167
khenaidoo9cdc1a62019-01-24 21:57:40 -0500168 if handler.competeForTransaction() {
169 if txn, err := handler.acquireTransaction(ctx); err != nil {
Richard Jankowski2755adf2019-01-17 17:16:48 -0500170 return new(empty.Empty), err
Richard Jankowski2755adf2019-01-17 17:16:48 -0500171 } else {
khenaidoo9cdc1a62019-01-24 21:57:40 -0500172 defer txn.Close()
Richard Jankowski2755adf2019-01-17 17:16:48 -0500173 }
174 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500175
khenaidoo4d4802d2018-10-04 21:59:49 -0400176 ch := make(chan interface{})
177 defer close(ch)
khenaidoo19d7b632018-10-30 10:49:50 -0400178 go handler.logicalDeviceMgr.enableLogicalPort(ctx, id, ch)
khenaidoo4d4802d2018-10-04 21:59:49 -0400179 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400180}
181
182func (handler *APIHandler) DisableLogicalDevicePort(ctx context.Context, id *voltha.LogicalPortId) (*empty.Empty, error) {
183 log.Debugw("DisableLogicalDevicePort-request", log.Fields{"id": id, "test": common.TestModeKeys_api_test.String()})
184 if isTestMode(ctx) {
185 out := new(empty.Empty)
186 return out, nil
187 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500188
khenaidoo9cdc1a62019-01-24 21:57:40 -0500189 if handler.competeForTransaction() {
190 if txn, err := handler.acquireTransaction(ctx); err != nil {
Richard Jankowski2755adf2019-01-17 17:16:48 -0500191 return new(empty.Empty), err
Richard Jankowski2755adf2019-01-17 17:16:48 -0500192 } else {
khenaidoo9cdc1a62019-01-24 21:57:40 -0500193 defer txn.Close()
Richard Jankowski2755adf2019-01-17 17:16:48 -0500194 }
195 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500196
khenaidoo19d7b632018-10-30 10:49:50 -0400197 ch := make(chan interface{})
198 defer close(ch)
199 go handler.logicalDeviceMgr.disableLogicalPort(ctx, id, ch)
200 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400201}
202
203func (handler *APIHandler) UpdateLogicalDeviceFlowTable(ctx context.Context, flow *openflow_13.FlowTableUpdate) (*empty.Empty, error) {
204 log.Debugw("UpdateLogicalDeviceFlowTable-request", log.Fields{"flow": flow, "test": common.TestModeKeys_api_test.String()})
205 if isTestMode(ctx) {
206 out := new(empty.Empty)
207 return out, nil
208 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500209
khenaidoo9cdc1a62019-01-24 21:57:40 -0500210 if handler.competeForTransaction() {
211 if !isOFControllerRequest(ctx) { // No need to acquire the transaction as request is sent to one core only
212 if txn, err := handler.acquireTransaction(ctx); err != nil {
213 return new(empty.Empty), err
214 } else {
215 defer txn.Close()
216 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500217 }
218 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500219
khenaidoo19d7b632018-10-30 10:49:50 -0400220 ch := make(chan interface{})
221 defer close(ch)
222 go handler.logicalDeviceMgr.updateFlowTable(ctx, flow.Id, flow.FlowMod, ch)
223 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400224}
225
226func (handler *APIHandler) UpdateLogicalDeviceFlowGroupTable(ctx context.Context, flow *openflow_13.FlowGroupTableUpdate) (*empty.Empty, error) {
227 log.Debugw("UpdateLogicalDeviceFlowGroupTable-request", log.Fields{"flow": flow, "test": common.TestModeKeys_api_test.String()})
228 if isTestMode(ctx) {
229 out := new(empty.Empty)
230 return out, nil
231 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500232
khenaidoo9cdc1a62019-01-24 21:57:40 -0500233 if handler.competeForTransaction() {
234 if !isOFControllerRequest(ctx) { // No need to acquire the transaction as request is sent to one core only
235 if txn, err := handler.acquireTransaction(ctx); err != nil {
236 return new(empty.Empty), err
237 } else {
238 defer txn.Close()
239 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500240 }
241 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500242
khenaidoo19d7b632018-10-30 10:49:50 -0400243 ch := make(chan interface{})
244 defer close(ch)
245 go handler.logicalDeviceMgr.updateGroupTable(ctx, flow.Id, flow.GroupMod, ch)
246 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400247}
248
khenaidoob9203542018-09-17 22:56:37 -0400249// GetDevice must be implemented in the read-only containers - should it also be implemented here?
250func (handler *APIHandler) GetDevice(ctx context.Context, id *voltha.ID) (*voltha.Device, error) {
251 log.Debugw("GetDevice-request", log.Fields{"id": id})
khenaidoo19d7b632018-10-30 10:49:50 -0400252 return handler.deviceMgr.GetDevice(id.Id)
khenaidoob9203542018-09-17 22:56:37 -0400253}
254
255// GetDevice must be implemented in the read-only containers - should it also be implemented here?
256func (handler *APIHandler) ListDevices(ctx context.Context, empty *empty.Empty) (*voltha.Devices, error) {
257 log.Debug("ListDevices")
258 return handler.deviceMgr.ListDevices()
259}
260
khenaidoo7ccedd52018-12-14 16:48:54 -0500261// ListDeviceIds returns the list of device ids managed by a voltha core
262func (handler *APIHandler) ListDeviceIds(ctx context.Context, empty *empty.Empty) (*voltha.IDs, error) {
263 log.Debug("ListDeviceIDs")
264 if isTestMode(ctx) {
265 out := &voltha.IDs{Items: make([]*voltha.ID, 0)}
266 return out, nil
267 }
268 return handler.deviceMgr.ListDeviceIds()
269}
270
271//ReconcileDevices is a request to a voltha core to managed a list of devices based on their IDs
272func (handler *APIHandler) ReconcileDevices(ctx context.Context, ids *voltha.IDs) (*empty.Empty, error) {
273 log.Debug("ReconcileDevices")
274 if isTestMode(ctx) {
275 out := new(empty.Empty)
276 return out, nil
277 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500278
khenaidoo9cdc1a62019-01-24 21:57:40 -0500279 // No need to grab a transaction as this request is core specific
280
khenaidoo7ccedd52018-12-14 16:48:54 -0500281 ch := make(chan interface{})
282 defer close(ch)
283 go handler.deviceMgr.ReconcileDevices(ctx, ids, ch)
284 return waitForNilResponseOnSuccess(ctx, ch)
285}
286
khenaidoob9203542018-09-17 22:56:37 -0400287// GetLogicalDevice must be implemented in the read-only containers - should it also be implemented here?
288func (handler *APIHandler) GetLogicalDevice(ctx context.Context, id *voltha.ID) (*voltha.LogicalDevice, error) {
289 log.Debugw("GetLogicalDevice-request", log.Fields{"id": id})
290 return handler.logicalDeviceMgr.getLogicalDevice(id.Id)
291}
292
293// ListLogicalDevices must be implemented in the read-only containers - should it also be implemented here?
294func (handler *APIHandler) ListLogicalDevices(ctx context.Context, empty *empty.Empty) (*voltha.LogicalDevices, error) {
295 log.Debug("ListLogicalDevices")
296 return handler.logicalDeviceMgr.listLogicalDevices()
297}
298
khenaidoo19d7b632018-10-30 10:49:50 -0400299// ListLogicalDevicePorts must be implemented in the read-only containers - should it also be implemented here?
300func (handler *APIHandler) ListLogicalDevicePorts(ctx context.Context, id *voltha.ID) (*voltha.LogicalPorts, error) {
301 log.Debugw("ListLogicalDevicePorts", log.Fields{"logicaldeviceid": id})
302 return handler.logicalDeviceMgr.ListLogicalDevicePorts(ctx, id.Id)
303}
304
khenaidoo4d4802d2018-10-04 21:59:49 -0400305// CreateDevice creates a new parent device in the data model
khenaidoobf6e7bb2018-08-14 22:27:29 -0400306func (handler *APIHandler) CreateDevice(ctx context.Context, device *voltha.Device) (*voltha.Device, error) {
khenaidoob9203542018-09-17 22:56:37 -0400307 log.Debugw("createdevice", log.Fields{"device": *device})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400308 if isTestMode(ctx) {
309 return &voltha.Device{Id: device.Id}, nil
310 }
Richard Jankowskid42826e2018-11-02 16:06:37 -0400311
khenaidoo9cdc1a62019-01-24 21:57:40 -0500312 if handler.competeForTransaction() {
313 if txn, err := handler.acquireTransaction(ctx); err != nil {
Richard Jankowski2755adf2019-01-17 17:16:48 -0500314 return &voltha.Device{}, err
Richard Jankowski2755adf2019-01-17 17:16:48 -0500315 } else {
khenaidoo9cdc1a62019-01-24 21:57:40 -0500316 defer txn.Close()
Richard Jankowski2755adf2019-01-17 17:16:48 -0500317 }
318 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500319
khenaidoob9203542018-09-17 22:56:37 -0400320 ch := make(chan interface{})
321 defer close(ch)
322 go handler.deviceMgr.createDevice(ctx, device, ch)
323 select {
324 case res := <-ch:
khenaidoo92e62c52018-10-03 14:02:54 -0400325 if res != nil {
326 if err, ok := res.(error); ok {
327 return &voltha.Device{}, err
328 }
329 if d, ok := res.(*voltha.Device); ok {
330 return d, nil
331 }
khenaidoob9203542018-09-17 22:56:37 -0400332 }
khenaidoo92e62c52018-10-03 14:02:54 -0400333 log.Warnw("create-device-unexpected-return-type", log.Fields{"result": res})
334 err := status.Errorf(codes.Internal, "%s", res)
335 return &voltha.Device{}, err
khenaidoob9203542018-09-17 22:56:37 -0400336 case <-ctx.Done():
337 log.Debug("createdevice-client-timeout")
338 return nil, ctx.Err()
339 }
khenaidoobf6e7bb2018-08-14 22:27:29 -0400340}
341
khenaidoo4d4802d2018-10-04 21:59:49 -0400342// EnableDevice activates a device by invoking the adopt_device API on the appropriate adapter
khenaidoobf6e7bb2018-08-14 22:27:29 -0400343func (handler *APIHandler) EnableDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
khenaidoob9203542018-09-17 22:56:37 -0400344 log.Debugw("enabledevice", log.Fields{"id": id})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400345 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400346 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400347 }
Richard Jankowskid42826e2018-11-02 16:06:37 -0400348
khenaidoo9cdc1a62019-01-24 21:57:40 -0500349 if handler.competeForTransaction() {
350 if txn, err := handler.acquireTransaction(ctx); err != nil {
Richard Jankowski2755adf2019-01-17 17:16:48 -0500351 return new(empty.Empty), err
Richard Jankowski2755adf2019-01-17 17:16:48 -0500352 } else {
khenaidoo9cdc1a62019-01-24 21:57:40 -0500353 defer txn.Close()
Richard Jankowski2755adf2019-01-17 17:16:48 -0500354 }
355 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500356
khenaidoob9203542018-09-17 22:56:37 -0400357 ch := make(chan interface{})
358 defer close(ch)
359 go handler.deviceMgr.enableDevice(ctx, id, ch)
khenaidoo4d4802d2018-10-04 21:59:49 -0400360 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400361}
362
khenaidoo4d4802d2018-10-04 21:59:49 -0400363// DisableDevice disables a device along with any child device it may have
khenaidoobf6e7bb2018-08-14 22:27:29 -0400364func (handler *APIHandler) DisableDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
365 log.Debugw("disabledevice-request", log.Fields{"id": id})
366 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400367 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400368 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500369
khenaidoo9cdc1a62019-01-24 21:57:40 -0500370 if handler.competeForTransaction() {
371 if txn, err := handler.acquireTransaction(ctx); err != nil {
Richard Jankowski2755adf2019-01-17 17:16:48 -0500372 return new(empty.Empty), err
Richard Jankowski2755adf2019-01-17 17:16:48 -0500373 } else {
khenaidoo9cdc1a62019-01-24 21:57:40 -0500374 defer txn.Close()
Richard Jankowski2755adf2019-01-17 17:16:48 -0500375 }
376 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500377
khenaidoo92e62c52018-10-03 14:02:54 -0400378 ch := make(chan interface{})
379 defer close(ch)
380 go handler.deviceMgr.disableDevice(ctx, id, ch)
khenaidoo4d4802d2018-10-04 21:59:49 -0400381 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400382}
383
khenaidoo4d4802d2018-10-04 21:59:49 -0400384//RebootDevice invoked the reboot API to the corresponding adapter
khenaidoobf6e7bb2018-08-14 22:27:29 -0400385func (handler *APIHandler) RebootDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400386 log.Debugw("rebootDevice-request", log.Fields{"id": id})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400387 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400388 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400389 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500390
khenaidoo9cdc1a62019-01-24 21:57:40 -0500391 if handler.competeForTransaction() {
392 if txn, err := handler.acquireTransaction(ctx); err != nil {
Richard Jankowski2755adf2019-01-17 17:16:48 -0500393 return new(empty.Empty), err
Richard Jankowski2755adf2019-01-17 17:16:48 -0500394 } else {
khenaidoo9cdc1a62019-01-24 21:57:40 -0500395 defer txn.Close()
Richard Jankowski2755adf2019-01-17 17:16:48 -0500396 }
397 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500398
khenaidoo4d4802d2018-10-04 21:59:49 -0400399 ch := make(chan interface{})
400 defer close(ch)
401 go handler.deviceMgr.rebootDevice(ctx, id, ch)
402 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400403}
404
khenaidoo4d4802d2018-10-04 21:59:49 -0400405// DeleteDevice removes a device from the data model
khenaidoobf6e7bb2018-08-14 22:27:29 -0400406func (handler *APIHandler) DeleteDevice(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
407 log.Debugw("deletedevice-request", log.Fields{"id": id})
408 if isTestMode(ctx) {
khenaidoo4d4802d2018-10-04 21:59:49 -0400409 return new(empty.Empty), nil
khenaidoobf6e7bb2018-08-14 22:27:29 -0400410 }
Richard Jankowski2755adf2019-01-17 17:16:48 -0500411
khenaidoo9cdc1a62019-01-24 21:57:40 -0500412 if handler.competeForTransaction() {
413 if txn, err := handler.acquireTransaction(ctx); err != nil {
Richard Jankowski2755adf2019-01-17 17:16:48 -0500414 return new(empty.Empty), err
Richard Jankowski2755adf2019-01-17 17:16:48 -0500415 } else {
khenaidoo9cdc1a62019-01-24 21:57:40 -0500416 defer txn.Close()
Richard Jankowski2755adf2019-01-17 17:16:48 -0500417 }
418 }
khenaidoo9cdc1a62019-01-24 21:57:40 -0500419
khenaidoo4d4802d2018-10-04 21:59:49 -0400420 ch := make(chan interface{})
421 defer close(ch)
422 go handler.deviceMgr.deleteDevice(ctx, id, ch)
423 return waitForNilResponseOnSuccess(ctx, ch)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400424}
425
khenaidoof5a5bfa2019-01-23 22:20:29 -0500426// processImageRequest is a helper method to execute an image download request
427func (handler *APIHandler) processImageRequest(ctx context.Context, img *voltha.ImageDownload, requestType int) (*common.OperationResp, error) {
428 log.Debugw("processImageDownload", log.Fields{"img": *img, "requestType": requestType})
429 if isTestMode(ctx) {
430 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
431 return resp, nil
432 }
433
khenaidoo9cdc1a62019-01-24 21:57:40 -0500434 if handler.competeForTransaction() {
435 if txn, err := handler.acquireTransaction(ctx); err != nil {
436 return &common.OperationResp{}, err
437 } else {
438 defer txn.Close()
439 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500440 }
441
442 failedresponse := &common.OperationResp{Code:voltha.OperationResp_OPERATION_FAILURE}
443
444 ch := make(chan interface{})
445 defer close(ch)
446 switch requestType {
447 case IMAGE_DOWNLOAD:
448 go handler.deviceMgr.downloadImage(ctx, img, ch)
449 case CANCEL_IMAGE_DOWNLOAD:
450 go handler.deviceMgr.cancelImageDownload(ctx, img, ch)
451 case ACTIVATE_IMAGE:
452 go handler.deviceMgr.activateImage(ctx, img, ch)
453 case REVERT_IMAGE:
454 go handler.deviceMgr.revertImage(ctx, img, ch)
455 default:
456 log.Warn("invalid-request-type", log.Fields{"requestType": requestType})
457 return failedresponse, status.Errorf(codes.InvalidArgument, "%d", requestType)
458 }
459 select {
460 case res := <-ch:
461 if res != nil {
462 if err, ok := res.(error); ok {
463 return failedresponse, err
464 }
465 if opResp, ok := res.(*common.OperationResp); ok {
466 return opResp, nil
467 }
468 }
469 log.Warnw("download-image-unexpected-return-type", log.Fields{"result": res})
470 return failedresponse, status.Errorf(codes.Internal, "%s", res)
471 case <-ctx.Done():
472 log.Debug("downloadImage-client-timeout")
473 return nil, ctx.Err()
474 }
475}
476
khenaidoobf6e7bb2018-08-14 22:27:29 -0400477func (handler *APIHandler) DownloadImage(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
478 log.Debugw("DownloadImage-request", log.Fields{"img": *img})
479 if isTestMode(ctx) {
480 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
481 return resp, nil
482 }
483
khenaidoof5a5bfa2019-01-23 22:20:29 -0500484 return handler.processImageRequest(ctx, img, IMAGE_DOWNLOAD)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400485}
486
487func (handler *APIHandler) CancelImageDownload(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500488 log.Debugw("cancelImageDownload-request", log.Fields{"img": *img})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400489 if isTestMode(ctx) {
490 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
491 return resp, nil
492 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500493 return handler.processImageRequest(ctx, img, CANCEL_IMAGE_DOWNLOAD)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400494}
495
496func (handler *APIHandler) ActivateImageUpdate(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500497 log.Debugw("activateImageUpdate-request", log.Fields{"img": *img})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400498 if isTestMode(ctx) {
499 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
500 return resp, nil
501 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500502
503 return handler.processImageRequest(ctx, img, ACTIVATE_IMAGE)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400504}
505
506func (handler *APIHandler) RevertImageUpdate(ctx context.Context, img *voltha.ImageDownload) (*common.OperationResp, error) {
khenaidoof5a5bfa2019-01-23 22:20:29 -0500507 log.Debugw("revertImageUpdate-request", log.Fields{"img": *img})
khenaidoobf6e7bb2018-08-14 22:27:29 -0400508 if isTestMode(ctx) {
509 resp := &common.OperationResp{Code: common.OperationResp_OPERATION_SUCCESS}
510 return resp, nil
511 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500512
513 return handler.processImageRequest(ctx, img, REVERT_IMAGE)
khenaidoobf6e7bb2018-08-14 22:27:29 -0400514}
515
khenaidoof5a5bfa2019-01-23 22:20:29 -0500516func (handler *APIHandler) GetImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
517 log.Debugw("getImageDownloadStatus-request", log.Fields{"img": *img})
518 if isTestMode(ctx) {
519 resp := &voltha.ImageDownload{State: voltha.ImageDownload_DOWNLOAD_SUCCEEDED}
520 return resp, nil
521 }
522
523 failedresponse := &voltha.ImageDownload{State: voltha.ImageDownload_DOWNLOAD_UNKNOWN}
524
khenaidoo9cdc1a62019-01-24 21:57:40 -0500525 if handler.competeForTransaction() {
526 if txn, err := handler.acquireTransaction(ctx); err != nil {
527 return failedresponse, err
528 } else {
529 defer txn.Close()
530 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500531 }
532
533 ch := make(chan interface{})
534 defer close(ch)
535 go handler.deviceMgr.getImageDownloadStatus(ctx, img, ch)
536
537 select {
538 case res := <-ch:
539 if res != nil {
540 if err, ok := res.(error); ok {
541 return failedresponse, err
542 }
543 if downloadResp, ok := res.(*voltha.ImageDownload); ok {
544 return downloadResp, nil
545 }
546 }
547 log.Warnw("download-image-status", log.Fields{"result": res})
548 return failedresponse, status.Errorf(codes.Internal, "%s", res)
549 case <-ctx.Done():
550 log.Debug("downloadImage-client-timeout")
551 return failedresponse, ctx.Err()
552 }
553}
554
555func (handler *APIHandler) GetImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
556 log.Debugw("GetImageDownload-request", log.Fields{"img": *img})
557 if isTestMode(ctx) {
558 resp := &voltha.ImageDownload{State: voltha.ImageDownload_DOWNLOAD_SUCCEEDED}
559 return resp, nil
560 }
561
562 if download, err := handler.deviceMgr.getImageDownload(ctx, img); err != nil {
563 return &voltha.ImageDownload{State: voltha.ImageDownload_DOWNLOAD_UNKNOWN}, err
564 } else {
565 return download, nil
566 }
567}
568
569func (handler *APIHandler) ListImageDownloads(ctx context.Context, id *voltha.ID) (*voltha.ImageDownloads, error) {
570 log.Debugw("ListImageDownloads-request", log.Fields{"deviceId": id.Id})
571 if isTestMode(ctx) {
572 resp := &voltha.ImageDownloads{Items:[]*voltha.ImageDownload{}}
573 return resp, nil
574 }
575
576 if downloads, err := handler.deviceMgr.listImageDownloads(ctx, id.Id); err != nil {
577 failedResp := &voltha.ImageDownloads{
578 Items:[]*voltha.ImageDownload{
579 &voltha.ImageDownload{State: voltha.ImageDownload_DOWNLOAD_UNKNOWN},
580 },
581 }
582 return failedResp, err
583 } else {
584 return downloads, nil
585 }
586}
587
588
khenaidoobf6e7bb2018-08-14 22:27:29 -0400589func (handler *APIHandler) UpdateDevicePmConfigs(ctx context.Context, configs *voltha.PmConfigs) (*empty.Empty, error) {
590 log.Debugw("UpdateDevicePmConfigs-request", log.Fields{"configs": *configs})
591 if isTestMode(ctx) {
592 out := new(empty.Empty)
593 return out, nil
594 }
595 return nil, errors.New("UnImplemented")
596}
597
598func (handler *APIHandler) CreateAlarmFilter(ctx context.Context, filter *voltha.AlarmFilter) (*voltha.AlarmFilter, error) {
599 log.Debugw("CreateAlarmFilter-request", log.Fields{"filter": *filter})
600 if isTestMode(ctx) {
601 f := &voltha.AlarmFilter{Id: filter.Id}
602 return f, nil
603 }
604 return nil, errors.New("UnImplemented")
605}
606
607func (handler *APIHandler) UpdateAlarmFilter(ctx context.Context, filter *voltha.AlarmFilter) (*voltha.AlarmFilter, error) {
608 log.Debugw("UpdateAlarmFilter-request", log.Fields{"filter": *filter})
609 if isTestMode(ctx) {
610 f := &voltha.AlarmFilter{Id: filter.Id}
611 return f, nil
612 }
613 return nil, errors.New("UnImplemented")
614}
615
616func (handler *APIHandler) DeleteAlarmFilter(ctx context.Context, id *voltha.ID) (*empty.Empty, error) {
617 log.Debugw("DeleteAlarmFilter-request", log.Fields{"id": *id})
618 if isTestMode(ctx) {
619 out := new(empty.Empty)
620 return out, nil
621 }
622 return nil, errors.New("UnImplemented")
623}
624
625func (handler *APIHandler) SelfTest(ctx context.Context, id *voltha.ID) (*voltha.SelfTestResponse, error) {
626 log.Debugw("SelfTest-request", log.Fields{"id": id})
627 if isTestMode(ctx) {
628 resp := &voltha.SelfTestResponse{Result: voltha.SelfTestResponse_SUCCESS}
629 return resp, nil
630 }
631 return nil, errors.New("UnImplemented")
632}
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500633
634func (handler *APIHandler) forwardPacketOut(packet *openflow_13.PacketOut) {
635 log.Debugw("forwardPacketOut-request", log.Fields{"packet": packet})
Richard Jankowski2755adf2019-01-17 17:16:48 -0500636 agent := handler.logicalDeviceMgr.getLogicalDeviceAgent(packet.Id)
637 agent.packetOut(packet.PacketOut)
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500638}
639func (handler *APIHandler) StreamPacketsOut(
640 packets voltha.VolthaService_StreamPacketsOutServer,
641) error {
642 log.Debugw("StreamPacketsOut-request", log.Fields{"packets": packets})
643 for {
644 packet, err := packets.Recv()
645
646 if err == io.EOF {
647 break
648 } else if err != nil {
649 log.Errorw("Failed to receive packet", log.Fields{"error": err})
650 }
651
652 handler.forwardPacketOut(packet)
653 }
654
655 log.Debugw("StreamPacketsOut-request-done", log.Fields{"packets": packets})
656 return nil
657}
658
659func (handler *APIHandler) sendPacketIn(deviceId string, packet *openflow_13.OfpPacketIn) {
660 packetIn := openflow_13.PacketIn{Id: deviceId, PacketIn: packet}
661 log.Debugw("sendPacketIn", log.Fields{"packetIn": packetIn})
Richard Jankowskidbab94a2018-12-06 16:20:25 -0500662 // Enqueue the packet
663 if err := handler.packetInQueue.Put(packetIn); err != nil {
664 log.Errorw("failed-to-enqueue-packet", log.Fields{"error": err})
665 }
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500666}
667
668func (handler *APIHandler) ReceivePacketsIn(
669 empty *empty.Empty,
670 packetsIn voltha.VolthaService_ReceivePacketsInServer,
671) error {
672 log.Debugw("ReceivePacketsIn-request", log.Fields{"packetsIn": packetsIn})
673
674 for {
Richard Jankowskidbab94a2018-12-06 16:20:25 -0500675 // Dequeue a packet
676 if packets, err := handler.packetInQueue.Get(1); err == nil {
677 log.Debugw("dequeued-packet", log.Fields{"packet": packets[0]})
678 if packet, ok := packets[0].(openflow_13.PacketIn); ok {
679 log.Debugw("sending-packet-in", log.Fields{"packet": packet})
680 if err := packetsIn.Send(&packet); err != nil {
681 log.Errorw("failed-to-send-packet", log.Fields{"error": err})
682 }
683 }
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500684 }
685 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500686 //TODO: FInd an elegant way to get out of the above loop when the Core is stopped
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500687}
688
689func (handler *APIHandler) sendChangeEvent(deviceId string, portStatus *openflow_13.OfpPortStatus) {
690 // TODO: validate the type of portStatus parameter
691 //if _, ok := portStatus.(*openflow_13.OfpPortStatus); ok {
692 //}
693 event := openflow_13.ChangeEvent{Id: deviceId, Event: &openflow_13.ChangeEvent_PortStatus{PortStatus: portStatus}}
694 log.Debugw("sendChangeEvent", log.Fields{"event": event})
695 // TODO: put the packet in the queue
696}
697
698func (handler *APIHandler) ReceiveChangeEvents(
699 empty *empty.Empty,
700 changeEvents voltha.VolthaService_ReceiveChangeEventsServer,
701) error {
702 log.Debugw("ReceiveChangeEvents-request", log.Fields{"changeEvents": changeEvents})
703 for {
704 // TODO: need to retrieve packet from queue
705 event := &openflow_13.ChangeEvent{}
706 time.Sleep(time.Duration(5) * time.Second)
707 err := changeEvents.Send(event)
708 if err != nil {
709 log.Errorw("Failed to send change event", log.Fields{"error": err})
710 }
711 }
khenaidoof5a5bfa2019-01-23 22:20:29 -0500712 // TODO: put the packet in the queue
713 }
Stephane Barbarie6e1bd502018-11-05 22:44:45 -0500714
715func (handler *APIHandler) Subscribe(
716 ctx context.Context,
717 ofAgent *voltha.OfAgentSubscriber,
718) (*voltha.OfAgentSubscriber, error) {
719 log.Debugw("Subscribe-request", log.Fields{"ofAgent": ofAgent})
720 return &voltha.OfAgentSubscriber{OfagentId: ofAgent.OfagentId, VolthaId: ofAgent.VolthaId}, nil
721}