| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package l2topology |
| 4 | |
| 5 | import "strings" |
| 6 | |
| 7 | const ( |
| 8 | adjacencyLabelPairID = "pair_id" |
| 9 | adjacencyLabelPairPass = "pair_pass" |
| 10 | ) |
| 11 | |
| 12 | type matchedPairMetadata struct { |
| 13 | id string |
| 14 | pass string |
| 15 | } |
| 16 | |
| 17 | func canonicalAdjacencyPairID(protocol, leftDeviceID, leftPort, rightDeviceID, rightPort string) string { |
| 18 | protocol = strings.ToLower(strings.TrimSpace(protocol)) |
| 19 | leftKey := topologyMatchCompositeKey(strings.TrimSpace(leftDeviceID), strings.TrimSpace(leftPort)) |
| 20 | rightKey := topologyMatchCompositeKey(strings.TrimSpace(rightDeviceID), strings.TrimSpace(rightPort)) |
| 21 | if protocol == "" || leftKey == "" || rightKey == "" { |
| 22 | return "" |
| 23 | } |
| 24 | if rightKey < leftKey { |
| 25 | leftKey, rightKey = rightKey, leftKey |
| 26 | } |
| 27 | return protocol + ":" + leftKey + "<->" + rightKey |
| 28 | } |
| 29 | |
| 30 | func applyAdjacencyPairMetadata(adj *Adjacency, metadata matchedPairMetadata) { |
| 31 | if adj == nil || metadata.id == "" { |
| 32 | return |
| 33 | } |
| 34 | if adj.Labels == nil { |
| 35 | adj.Labels = make(map[string]string) |
| 36 | } |
| 37 | adj.Labels[adjacencyLabelPairID] = metadata.id |
| 38 | if metadata.pass != "" { |
| 39 | adj.Labels[adjacencyLabelPairPass] = metadata.pass |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func addAdjacency(adjacencies map[string]Adjacency, adj Adjacency) bool { |
| 44 | sourceID := strings.TrimSpace(adj.SourceID) |
| 45 | targetID := strings.TrimSpace(adj.TargetID) |
| 46 | if sourceID == "" || targetID == "" { |
| 47 | return false |
| 48 | } |
| 49 | if sourceID == targetID { |
| 50 | sourcePort := strings.TrimSpace(adj.SourcePort) |
| 51 | targetPort := strings.TrimSpace(adj.TargetPort) |
| 52 | if sourcePort == "" || targetPort == "" || sourcePort == targetPort { |
| 53 | return false |
| 54 | } |
| 55 | } |
| 56 | key := adjacencyKey(adj) |
| 57 | if _, ok := adjacencies[key]; ok { |
| 58 | return false |
| 59 | } |
| 60 | adjacencies[key] = adj |
| 61 | return true |
| 62 | } |
| 63 | |
| 64 | func addAttachment(attachments map[string]Attachment, attachment Attachment) bool { |
| 65 | if strings.TrimSpace(attachment.DeviceID) == "" || strings.TrimSpace(attachment.EndpointID) == "" { |
| 66 | return false |
| 67 | } |
| 68 | key := attachmentKey(attachment) |
| 69 | if _, ok := attachments[key]; ok { |
| 70 | return false |
| 71 | } |
| 72 | attachments[key] = attachment |
| 73 | return true |
| 74 | } |