blob: 5583023cc973684139d66d5368660911c5b91dd8 [file] [log] [blame]
Matt Jeanneretcab955f2019-04-10 15:45:57 -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 */
16
17package graph
18
19import (
20 "errors"
21 "fmt"
22 "github.com/gyuho/goraph"
23 "github.com/opencord/voltha-go/common/log"
24 "github.com/opencord/voltha-protos/go/voltha"
25 "strconv"
26 "strings"
27 "sync"
28)
29
30func init() {
31 log.AddPackage(log.JSON, log.WarnLevel, nil)
32}
33
34type RouteHop struct {
35 DeviceID string
36 Ingress uint32
37 Egress uint32
38}
39
40type OFPortLink struct {
41 Ingress uint32
42 Egress uint32
43}
44
45type ofPortLinkToPath struct {
46 link OFPortLink
47 path []RouteHop
48}
49
50type GetDeviceFunc func(id string) (*voltha.Device, error)
51
52type DeviceGraph struct {
53 logicalDeviceId string
54 GGraph goraph.Graph
55 getDeviceFromModel GetDeviceFunc
56 logicalPorts []*voltha.LogicalPort
57 rootPortsString map[string]uint32
58 nonRootPortsString map[string]uint32
59 RootPorts map[uint32]uint32
60 rootPortsLock sync.RWMutex
61 Routes map[OFPortLink][]RouteHop
62 graphBuildLock sync.RWMutex
63 boundaryPorts map[string]uint32
64 boundaryPortsLock sync.RWMutex
65 cachedDevices map[string]*voltha.Device
66 cachedDevicesLock sync.RWMutex
67 devicesAdded map[string]string
68 portsAdded map[string]string
69}
70
71func NewDeviceGraph(logicalDeviceId string, getDevice GetDeviceFunc) *DeviceGraph {
72 var dg DeviceGraph
73 dg.logicalDeviceId = logicalDeviceId
74 dg.GGraph = goraph.NewGraph()
75 dg.getDeviceFromModel = getDevice
76 dg.graphBuildLock = sync.RWMutex{}
77 dg.cachedDevicesLock = sync.RWMutex{}
78 dg.rootPortsLock = sync.RWMutex{}
79 dg.devicesAdded = make(map[string]string)
80 dg.portsAdded = make(map[string]string)
81 dg.rootPortsString = make(map[string]uint32)
82 dg.nonRootPortsString = make(map[string]uint32)
83 dg.RootPorts = make(map[uint32]uint32)
84 dg.boundaryPorts = make(map[string]uint32)
85 dg.Routes = make(map[OFPortLink][]RouteHop)
86 dg.cachedDevices = make(map[string]*voltha.Device)
87 log.Debug("new device graph created ...")
88 return &dg
89}
90
91//IsRootPort returns true if the port is a root port on a logical device
92func (dg *DeviceGraph) IsRootPort(port uint32) bool {
93 dg.rootPortsLock.RLock()
94 defer dg.rootPortsLock.RUnlock()
95 _, exist := dg.RootPorts[port]
96 return exist
97}
98
99//GetDeviceNodeIds retrieves all the nodes in the device graph
100func (dg *DeviceGraph) GetDeviceNodeIds() map[string]string {
101 dg.graphBuildLock.RLock()
102 defer dg.graphBuildLock.RUnlock()
103 nodeIds := make(map[string]string)
104 nodesMap := dg.GGraph.GetNodes()
105 for id, node := range nodesMap {
106 if len(strings.Split(node.String(), ":")) != 2 { // not port node
107 nodeIds[id.String()] = id.String()
108 }
109 }
110 return nodeIds
111}
112
113//ComputeRoutes creates a device graph from the logical ports and then calculates all the routes
114//between the logical ports. This will clear up the graph and routes if there were any.
115func (dg *DeviceGraph) ComputeRoutes(lps []*voltha.LogicalPort) {
116 if dg == nil {
117 return
118 }
119 dg.graphBuildLock.Lock()
120 defer dg.graphBuildLock.Unlock()
121
122 // Clear the graph
123 dg.reset()
124
125 dg.logicalPorts = lps
126
127 // Set the root, non-root ports and boundary ports
128 for _, lp := range lps {
129 portId := concatDeviceIdPortId(lp.DeviceId, lp.DevicePortNo)
130 if lp.RootPort {
131 dg.rootPortsString[portId] = lp.OfpPort.PortNo
132 dg.RootPorts[lp.OfpPort.PortNo] = lp.OfpPort.PortNo
133 } else {
134 dg.nonRootPortsString[portId] = lp.OfpPort.PortNo
135 }
136 dg.boundaryPorts[portId] = lp.OfpPort.PortNo
137 }
138
139 // Build the graph
140 var device *voltha.Device
141 for _, logicalPort := range dg.logicalPorts {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400142 device, _ = dg.getDevice(logicalPort.DeviceId, false)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400143 dg.GGraph = dg.addDevice(device, dg.GGraph, &dg.devicesAdded, &dg.portsAdded, dg.boundaryPorts)
144 }
145
146 dg.Routes = dg.buildRoutes()
147}
148
149// AddPort adds a port to the graph. If the graph is empty it will just invoke ComputeRoutes function
150func (dg *DeviceGraph) AddPort(lp *voltha.LogicalPort) {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400151 log.Debugw("Addport", log.Fields{"logicalPort": lp})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400152 // If the graph does not exist invoke ComputeRoutes.
153 if len(dg.boundaryPorts) == 0 {
154 dg.ComputeRoutes([]*voltha.LogicalPort{lp})
155 return
156 }
157
158 dg.graphBuildLock.Lock()
159 defer dg.graphBuildLock.Unlock()
160
161 portId := concatDeviceIdPortId(lp.DeviceId, lp.DevicePortNo)
162
163 // If the port is already part of the boundary ports, do nothing
164 if dg.portExist(portId) {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400165 return
166 }
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400167 // Add the port to the set of boundary ports
168 dg.boundaryPorts[portId] = lp.OfpPort.PortNo
169
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400170 // Add the device where this port is located to the device graph. If the device is already added then
171 // only the missing port will be added
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400172 device, _ := dg.getDevice(lp.DeviceId, false)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400173 dg.GGraph = dg.addDevice(device, dg.GGraph, &dg.devicesAdded, &dg.portsAdded, dg.boundaryPorts)
174
175 if lp.RootPort {
176 // Compute the route from this root port to all non-root ports
177 dg.rootPortsString[portId] = lp.OfpPort.PortNo
178 dg.RootPorts[lp.OfpPort.PortNo] = lp.OfpPort.PortNo
179 dg.Routes = dg.buildPathsToAllNonRootPorts(lp)
180 } else {
181 // Compute the route from this port to all root ports
182 dg.nonRootPortsString[portId] = lp.OfpPort.PortNo
183 dg.Routes = dg.buildPathsToAllRootPorts(lp)
184 }
185
186 dg.Print()
187}
188
189func (dg *DeviceGraph) Print() error {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400190 log.Debugw("Print", log.Fields{"graph": dg.logicalDeviceId, "boundaryPorts": dg.boundaryPorts})
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400191 if level, err := log.GetPackageLogLevel(); err == nil && level == log.DebugLevel {
192 output := ""
193 routeNumber := 1
194 for k, v := range dg.Routes {
195 key := fmt.Sprintf("LP:%d->LP:%d", k.Ingress, k.Egress)
196 val := ""
197 for _, i := range v {
198 val += fmt.Sprintf("{%d->%s->%d},", i.Ingress, i.DeviceID, i.Egress)
199 }
200 val = val[:len(val)-1]
201 output += fmt.Sprintf("%d:{%s=>%s} ", routeNumber, key, fmt.Sprintf("[%s]", val))
202 routeNumber += 1
203 }
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400204 if len(dg.Routes) == 0 {
205 log.Debugw("no-routes-found", log.Fields{"lDeviceId": dg.logicalDeviceId, "Graph": dg.GGraph.String()})
206 } else {
207 log.Debugw("graph_routes", log.Fields{"lDeviceId": dg.logicalDeviceId, "Routes": output})
208 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400209 }
210 return nil
211}
212
213//getDevice returns the device either from the local cache (default) or from the model.
214//TODO: Set a cache timeout such that we do not use invalid data. The full device lifecycle should also
215//be taken in consideration
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400216func (dg *DeviceGraph) getDevice(id string, useCache bool) (*voltha.Device, error) {
217 if useCache {
218 dg.cachedDevicesLock.RLock()
219 if d, exist := dg.cachedDevices[id]; exist {
220 dg.cachedDevicesLock.RUnlock()
221 //log.Debugw("getDevice - returned from cache", log.Fields{"deviceId": id})
222 return d, nil
223 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400224 dg.cachedDevicesLock.RUnlock()
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400225 }
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400226 // Not cached
227 if d, err := dg.getDeviceFromModel(id); err != nil {
228 log.Errorw("device-not-found", log.Fields{"deviceId": id, "error": err})
229 return nil, err
230 } else { // cache it
231 dg.cachedDevicesLock.Lock()
232 dg.cachedDevices[id] = d
233 dg.cachedDevicesLock.Unlock()
234 //log.Debugw("getDevice - returned from model", log.Fields{"deviceId": id})
235 return d, nil
236 }
237}
238
239// addDevice adds a device to a device graph and setup edges that represent the device connections to its peers
240func (dg *DeviceGraph) addDevice(device *voltha.Device, g goraph.Graph, devicesAdded *map[string]string, portsAdded *map[string]string,
241 boundaryPorts map[string]uint32) goraph.Graph {
242
243 if device == nil {
244 return g
245 }
246
247 if _, exist := (*devicesAdded)[device.Id]; !exist {
248 g.AddNode(goraph.NewNode(device.Id))
249 (*devicesAdded)[device.Id] = device.Id
250 }
251
252 var portId string
253 var peerPortId string
254 for _, port := range device.Ports {
255 portId = concatDeviceIdPortId(device.Id, port.PortNo)
256 if _, exist := (*portsAdded)[portId]; !exist {
257 (*portsAdded)[portId] = portId
258 g.AddNode(goraph.NewNode(portId))
259 g.AddEdge(goraph.StringID(device.Id), goraph.StringID(portId), 1)
260 g.AddEdge(goraph.StringID(portId), goraph.StringID(device.Id), 1)
261 }
262 for _, peer := range port.Peers {
263 if _, exist := (*devicesAdded)[peer.DeviceId]; !exist {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400264 d, _ := dg.getDevice(peer.DeviceId, true)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400265 g = dg.addDevice(d, g, devicesAdded, portsAdded, boundaryPorts)
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400266 }
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400267 peerPortId = concatDeviceIdPortId(peer.DeviceId, peer.PortNo)
268 g.AddEdge(goraph.StringID(portId), goraph.StringID(peerPortId), 1)
269 g.AddEdge(goraph.StringID(peerPortId), goraph.StringID(portId), 1)
270
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400271 }
272 }
273 return g
274}
275
276//portExist returns true if the port ID is already part of the boundary ports map.
277func (dg *DeviceGraph) portExist(id string) bool {
278 dg.boundaryPortsLock.RLock()
279 defer dg.boundaryPortsLock.RUnlock()
280 _, exist := dg.boundaryPorts[id]
281 return exist
282}
283
284// buildPathsToAllRootPorts builds all the paths from the non-root logical port to all root ports
285// on the logical device
286func (dg *DeviceGraph) buildPathsToAllRootPorts(lp *voltha.LogicalPort) map[OFPortLink][]RouteHop {
287 paths := dg.Routes
288 source := concatDeviceIdPortId(lp.DeviceId, lp.DevicePortNo)
289 sourcePort := lp.OfpPort.PortNo
290 ch := make(chan *ofPortLinkToPath)
291 numBuildRequest := 0
292 for target, targetPort := range dg.rootPortsString {
293 go dg.buildRoute(source, target, sourcePort, targetPort, ch)
294 numBuildRequest += 1
295 }
296 responseReceived := 0
297forloop:
298 for {
299 if responseReceived == numBuildRequest {
300 break
301 }
302 select {
303 case res, ok := <-ch:
304 if !ok {
305 log.Debug("channel closed")
306 break forloop
307 }
308 if res != nil && len(res.path) > 0 {
309 paths[res.link] = res.path
310 paths[OFPortLink{Ingress: res.link.Egress, Egress: res.link.Ingress}] = getReverseRoute(res.path)
311 }
312 }
313 responseReceived += 1
314 }
315 return paths
316}
317
318// buildPathsToAllNonRootPorts builds all the paths from the root logical port to all non-root ports
319// on the logical device
320func (dg *DeviceGraph) buildPathsToAllNonRootPorts(lp *voltha.LogicalPort) map[OFPortLink][]RouteHop {
321 paths := dg.Routes
322 source := concatDeviceIdPortId(lp.DeviceId, lp.DevicePortNo)
323 sourcePort := lp.OfpPort.PortNo
324 ch := make(chan *ofPortLinkToPath)
325 numBuildRequest := 0
326 for target, targetPort := range dg.nonRootPortsString {
327 go dg.buildRoute(source, target, sourcePort, targetPort, ch)
328 numBuildRequest += 1
329 }
330 responseReceived := 0
331forloop:
332 for {
333 if responseReceived == numBuildRequest {
334 break
335 }
336 select {
337 case res, ok := <-ch:
338 if !ok {
339 log.Debug("channel closed")
340 break forloop
341 }
342 if res != nil && len(res.path) > 0 {
343 paths[res.link] = res.path
344 paths[OFPortLink{Ingress: res.link.Egress, Egress: res.link.Ingress}] = getReverseRoute(res.path)
345 }
346 }
347 responseReceived += 1
348 }
349 return paths
350}
351
352//buildRoute builds a route between a source and a target logical port
353func (dg *DeviceGraph) buildRoute(sourceId, targetId string, sourcePort, targetPort uint32, ch chan *ofPortLinkToPath) {
354 var pathIds []goraph.ID
355 path := make([]RouteHop, 0)
356 var err error
357 var hop RouteHop
358 var result *ofPortLinkToPath
359
360 if sourceId == targetId {
361 ch <- result
362 return
363 }
364 //Ignore Root - Root Routes
365 if dg.IsRootPort(sourcePort) && dg.IsRootPort(targetPort) {
366 ch <- result
367 return
368 }
369
370 //Ignore non-Root - non-Root Routes
371 if !dg.IsRootPort(sourcePort) && !dg.IsRootPort(targetPort) {
372 ch <- result
373 return
374 }
375
376 if pathIds, _, err = goraph.Dijkstra(dg.GGraph, goraph.StringID(sourceId), goraph.StringID(targetId)); err != nil {
377 log.Errorw("no-path", log.Fields{"sourceId": sourceId, "targetId": targetId, "error": err})
378 ch <- result
379 return
380 }
381 if len(pathIds)%3 != 0 {
382 ch <- result
383 return
384 }
385 var deviceId string
386 var ingressPort uint32
387 var egressPort uint32
388 for i := 0; i < len(pathIds); i = i + 3 {
389 if deviceId, ingressPort, err = splitIntoDeviceIdPortId(pathIds[i].String()); err != nil {
390 log.Errorw("id-error", log.Fields{"sourceId": sourceId, "targetId": targetId, "error": err})
391 break
392 }
393 if _, egressPort, err = splitIntoDeviceIdPortId(pathIds[i+2].String()); err != nil {
394 log.Errorw("id-error", log.Fields{"sourceId": sourceId, "targetId": targetId, "error": err})
395 break
396 }
397 hop = RouteHop{Ingress: ingressPort, DeviceID: deviceId, Egress: egressPort}
398 path = append(path, hop)
399 }
400 result = &ofPortLinkToPath{link: OFPortLink{Ingress: sourcePort, Egress: targetPort}, path: path}
401 ch <- result
402}
403
404//buildRoutes build all routes between all the ports on the logical device
405func (dg *DeviceGraph) buildRoutes() map[OFPortLink][]RouteHop {
406 paths := make(map[OFPortLink][]RouteHop)
407 ch := make(chan *ofPortLinkToPath)
408 numBuildRequest := 0
409 for source, sourcePort := range dg.boundaryPorts {
410 for target, targetPort := range dg.boundaryPorts {
411 go dg.buildRoute(source, target, sourcePort, targetPort, ch)
412 numBuildRequest += 1
413 }
414 }
415 responseReceived := 0
416forloop:
417 for {
418 if responseReceived == numBuildRequest {
419 break
420 }
421 select {
422 case res, ok := <-ch:
423 if !ok {
424 log.Debug("channel closed")
425 break forloop
426 }
427 if res != nil && len(res.path) > 0 {
428 paths[res.link] = res.path
429 }
430 }
431 responseReceived += 1
432 }
433 return paths
434}
435
436// reset cleans up the device graph
437func (dg *DeviceGraph) reset() {
438 dg.devicesAdded = make(map[string]string)
439 dg.portsAdded = make(map[string]string)
440 dg.rootPortsString = make(map[string]uint32)
441 dg.nonRootPortsString = make(map[string]uint32)
442 dg.RootPorts = make(map[uint32]uint32)
443 dg.boundaryPorts = make(map[string]uint32)
444 dg.Routes = make(map[OFPortLink][]RouteHop)
445 dg.cachedDevices = make(map[string]*voltha.Device)
446}
447
448//concatDeviceIdPortId formats a portid using the device id and the port number
449func concatDeviceIdPortId(deviceId string, portNo uint32) string {
450 return fmt.Sprintf("%s:%d", deviceId, portNo)
451}
452
453// splitIntoDeviceIdPortId extracts the device id and port number from the portId
454func splitIntoDeviceIdPortId(id string) (string, uint32, error) {
455 result := strings.Split(id, ":")
456 if len(result) != 2 {
457 return "", 0, errors.New(fmt.Sprintf("invalid-id-%s", id))
458 }
459 if temp, err := strconv.ParseInt(result[1], 10, 32); err != nil {
460 return "", 0, errors.New(fmt.Sprintf("invalid-id-%s-%s", id, err.Error()))
461 } else {
462 return result[0], uint32(temp), nil
463 }
464}
465
466//getReverseRoute returns the reverse of the route in param
467func getReverseRoute(route []RouteHop) []RouteHop {
468 reverse := make([]RouteHop, len(route))
469 for i, j := 0, len(route)-1; i < j; i, j = i+1, j-1 {
470 reverse[i], reverse[j] = route[j], route[i]
471 }
472 return reverse
473}