graph.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "github.com/spf13/cobra"
  18. "github.com/squat/kilo/pkg/mesh"
  19. )
  20. func graph() *cobra.Command {
  21. return &cobra.Command{
  22. Use: "graph",
  23. Short: "Generates a graph of the Kilo network",
  24. RunE: runGraph,
  25. }
  26. }
  27. func runGraph(_ *cobra.Command, _ []string) error {
  28. ns, err := opts.backend.Nodes().List()
  29. if err != nil {
  30. return fmt.Errorf("failed to list nodes: %v", err)
  31. }
  32. ps, err := opts.backend.Peers().List()
  33. if err != nil {
  34. return fmt.Errorf("failed to list peers: %v", err)
  35. }
  36. var hostname string
  37. subnet := mesh.DefaultKiloSubnet
  38. nodes := make(map[string]*mesh.Node)
  39. for _, n := range ns {
  40. if n.Ready() {
  41. nodes[n.Name] = n
  42. hostname = n.Name
  43. }
  44. if n.WireGuardIP != nil {
  45. subnet = n.WireGuardIP
  46. }
  47. }
  48. subnet.IP = subnet.IP.Mask(subnet.Mask)
  49. if len(nodes) == 0 {
  50. return fmt.Errorf("did not find any valid Kilo nodes in the cluster")
  51. }
  52. peers := make(map[string]*mesh.Peer)
  53. for _, p := range ps {
  54. if p.Ready() {
  55. peers[p.Name] = p
  56. }
  57. }
  58. t, err := mesh.NewTopology(nodes, peers, opts.granularity, hostname, 0, []byte{}, subnet, nodes[hostname].PersistentKeepalive)
  59. if err != nil {
  60. return fmt.Errorf("failed to create topology: %v", err)
  61. }
  62. g, err := t.Dot()
  63. if err != nil {
  64. return fmt.Errorf("failed to generate graph: %v", err)
  65. }
  66. fmt.Println(g)
  67. return nil
  68. }