graph.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  19. "github.com/squat/kilo/pkg/mesh"
  20. )
  21. func graph() *cobra.Command {
  22. return &cobra.Command{
  23. Use: "graph",
  24. Short: "Generates a graph of the Kilo network",
  25. RunE: runGraph,
  26. }
  27. }
  28. func runGraph(_ *cobra.Command, _ []string) error {
  29. ns, err := opts.backend.Nodes().List()
  30. if err != nil {
  31. return fmt.Errorf("failed to list nodes: %w", err)
  32. }
  33. ps, err := opts.backend.Peers().List()
  34. if err != nil {
  35. return fmt.Errorf("failed to list peers: %w", err)
  36. }
  37. // Obtain the Granularity by looking at the annotation of the first node.
  38. if opts.granularity, err = determineGranularity(opts.granularity, ns); err != nil {
  39. return fmt.Errorf("failed to determine granularity: %w", err)
  40. }
  41. var hostname string
  42. subnet := mesh.DefaultKiloSubnet
  43. nodes := make(map[string]*mesh.Node)
  44. for _, n := range ns {
  45. if n.Ready() {
  46. nodes[n.Name] = n
  47. hostname = n.Name
  48. }
  49. if n.WireGuardIP != nil {
  50. subnet = n.WireGuardIP
  51. }
  52. }
  53. subnet.IP = subnet.IP.Mask(subnet.Mask)
  54. if len(nodes) == 0 {
  55. return fmt.Errorf("did not find any valid Kilo nodes in the cluster")
  56. }
  57. peers := make(map[string]*mesh.Peer)
  58. for _, p := range ps {
  59. if p.Ready() {
  60. peers[p.Name] = p
  61. }
  62. }
  63. t, err := mesh.NewTopology(nodes, peers, opts.granularity, hostname, 0, wgtypes.Key{}, subnet, nil, nodes[hostname].PersistentKeepalive, nil)
  64. if err != nil {
  65. return fmt.Errorf("failed to create topology: %w", err)
  66. }
  67. g, err := t.Dot()
  68. if err != nil {
  69. return fmt.Errorf("failed to generate graph: %w", err)
  70. }
  71. fmt.Println(g)
  72. return nil
  73. }