|
| 1 | +package internal |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "opennetworktools/netmap/internal/arista" |
| 7 | + "opennetworktools/netmap/internal/utils" |
| 8 | + "opennetworktools/netmap/internal/visualizer" |
| 9 | +) |
| 10 | + |
| 11 | +func Traverse(hostname, username, password string) { |
| 12 | + ctx := context.Background() |
| 13 | + |
| 14 | + // hostname := "roi460" |
| 15 | + // username := "admin" |
| 16 | + // password := "" |
| 17 | + enablePasswd := "" |
| 18 | + port := 80 |
| 19 | + |
| 20 | + networkMap := &visualizer.NetworkMap{ |
| 21 | + Devices: make(map[string][]visualizer.Edge), |
| 22 | + } |
| 23 | + |
| 24 | + // Queue for traversal |
| 25 | + pendingDevices := []string{hostname} |
| 26 | + visited := make(map[string]bool) |
| 27 | + |
| 28 | + for len(pendingDevices) > 0 { |
| 29 | + device := pendingDevices[0] |
| 30 | + pendingDevices = pendingDevices[1:] |
| 31 | + |
| 32 | + // Skip if already visited |
| 33 | + if visited[device] { |
| 34 | + continue |
| 35 | + } |
| 36 | + visited[device] = true |
| 37 | + |
| 38 | + fmt.Printf("\nDiscovering neighbors for %s...", device) |
| 39 | + |
| 40 | + // Get LLDP neighbors |
| 41 | + neighbors, err := arista.GetNeighbors(device, username, password, enablePasswd, port) |
| 42 | + if err != nil { |
| 43 | + fmt.Printf("\n%s", err.Error()) |
| 44 | + continue |
| 45 | + } |
| 46 | + |
| 47 | + // Store device in topology (ensure it's initialized) |
| 48 | + if _, exists := networkMap.Devices[device]; !exists { |
| 49 | + networkMap.Devices[device] = []visualizer.Edge{} |
| 50 | + } |
| 51 | + |
| 52 | + fmt.Printf(" Found %d for %s!", len(neighbors.LLDPNeighbors), device) |
| 53 | + |
| 54 | + // Process each neighbor |
| 55 | + for _, obj := range neighbors.LLDPNeighbors { |
| 56 | + neighborDevice := obj.NeighborDevice |
| 57 | + // fmt.Printf("\n - Found neighbor: %s", neighborDevice) |
| 58 | + |
| 59 | + // Store the connection in the network map |
| 60 | + networkMap.Devices[device] = append(networkMap.Devices[device], visualizer.Edge{ |
| 61 | + LocalPort: obj.Port, |
| 62 | + Neighbor: neighborDevice, |
| 63 | + NeighborPort: obj.NeighborPort, |
| 64 | + }) |
| 65 | + |
| 66 | + // Add neighbor to queue if not visited |
| 67 | + if !visited[neighborDevice] { |
| 68 | + pendingDevices = append(pendingDevices, neighborDevice) |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + // Exporting networkMap to a JSON file |
| 74 | + err := utils.SaveStructAsJson("networkMap", networkMap) |
| 75 | + if err != nil { |
| 76 | + fmt.Println("Error writing the file: ", err) |
| 77 | + return |
| 78 | + } |
| 79 | + |
| 80 | + // Creating a graph and exporting it to a PNG file using go-graphviz |
| 81 | + err = visualizer.SaveTopologyWithGraphviz(ctx, networkMap) |
| 82 | + if err != nil { |
| 83 | + fmt.Println("Error rendering the topology: ", err) |
| 84 | + return |
| 85 | + } |
| 86 | +} |
0 commit comments