graph.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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/kilo-io/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. // Obtain the Granularity by looking at the annotation of the first node.
  37. if opts.granularity, err = optainGranularity(opts.granularity, ns); err != nil {
  38. return fmt.Errorf("failed to obtain granularity: %w", err)
  39. }
  40. var hostname string
  41. subnet := mesh.DefaultKiloSubnet
  42. nodes := make(map[string]*mesh.Node)
  43. for _, n := range ns {
  44. if n.Ready() {
  45. nodes[n.Name] = n
  46. hostname = n.Name
  47. }
  48. if n.WireGuardIP != nil {
  49. subnet = n.WireGuardIP
  50. }
  51. }
  52. subnet.IP = subnet.IP.Mask(subnet.Mask)
  53. if len(nodes) == 0 {
  54. return fmt.Errorf("did not find any valid Kilo nodes in the cluster")
  55. }
  56. peers := make(map[string]*mesh.Peer)
  57. for _, p := range ps {
  58. if p.Ready() {
  59. peers[p.Name] = p
  60. }
  61. }
  62. t, err := mesh.NewTopology(nodes, peers, opts.granularity, hostname, 0, []byte{}, subnet, nodes[hostname].PersistentKeepalive, nil)
  63. if err != nil {
  64. return fmt.Errorf("failed to create topology: %v", err)
  65. }
  66. g, err := t.Dot()
  67. if err != nil {
  68. return fmt.Errorf("failed to generate graph: %v", err)
  69. }
  70. fmt.Println(g)
  71. return nil
  72. }