main.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. "errors"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "github.com/go-kit/kit/log"
  22. "github.com/spf13/cobra"
  23. apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
  24. "k8s.io/client-go/kubernetes"
  25. "k8s.io/client-go/tools/clientcmd"
  26. "github.com/squat/kilo/pkg/k8s"
  27. kiloclient "github.com/squat/kilo/pkg/k8s/clientset/versioned"
  28. "github.com/squat/kilo/pkg/mesh"
  29. "github.com/squat/kilo/pkg/version"
  30. )
  31. const (
  32. logLevelAll = "all"
  33. logLevelDebug = "debug"
  34. logLevelInfo = "info"
  35. logLevelWarn = "warn"
  36. logLevelError = "error"
  37. logLevelNone = "none"
  38. )
  39. var (
  40. availableBackends = []string{
  41. k8s.Backend,
  42. }
  43. availableGranularities = []string{
  44. string(mesh.LogicalGranularity),
  45. string(mesh.FullGranularity),
  46. string(mesh.AutoGranularity),
  47. }
  48. availableLogLevels = []string{
  49. logLevelAll,
  50. logLevelDebug,
  51. logLevelInfo,
  52. logLevelWarn,
  53. logLevelError,
  54. logLevelNone,
  55. }
  56. opts struct {
  57. backend mesh.Backend
  58. granularity mesh.Granularity
  59. kc kiloclient.Interface
  60. port int
  61. }
  62. backend string
  63. granularity string
  64. kubeconfig string
  65. topologyLabel string
  66. )
  67. func runRoot(c *cobra.Command, _ []string) error {
  68. p := c
  69. for {
  70. if p.Name() == "completion" || strings.HasPrefix(p.Name(), cobra.ShellCompRequestCmd) {
  71. return nil
  72. }
  73. if !p.HasParent() {
  74. break
  75. }
  76. p = p.Parent()
  77. }
  78. if opts.port < 1 || opts.port > 1<<16-1 {
  79. return fmt.Errorf("invalid port: port mus be in range [%d:%d], but got %d", 1, 1<<16-1, opts.port)
  80. }
  81. opts.granularity = mesh.Granularity(granularity)
  82. switch opts.granularity {
  83. case mesh.LogicalGranularity:
  84. case mesh.FullGranularity:
  85. case mesh.AutoGranularity:
  86. default:
  87. return fmt.Errorf("mesh granularity %s unknown; posible values are: %s", granularity, availableGranularities)
  88. }
  89. switch backend {
  90. case k8s.Backend:
  91. config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
  92. if err != nil {
  93. return fmt.Errorf("failed to create Kubernetes config: %w", err)
  94. }
  95. c := kubernetes.NewForConfigOrDie(config)
  96. opts.kc = kiloclient.NewForConfigOrDie(config)
  97. ec := apiextensions.NewForConfigOrDie(config)
  98. opts.backend = k8s.New(c, opts.kc, ec, topologyLabel, log.NewNopLogger())
  99. default:
  100. return fmt.Errorf("backend %s unknown; posible values are: %s", backend, availableBackends)
  101. }
  102. if err := opts.backend.Nodes().Init(c.Context()); err != nil {
  103. return fmt.Errorf("failed to initialize node backend: %w", err)
  104. }
  105. if err := opts.backend.Peers().Init(c.Context()); err != nil {
  106. return fmt.Errorf("failed to initialize peer backend: %w", err)
  107. }
  108. return nil
  109. }
  110. func main() {
  111. cmd := &cobra.Command{
  112. Use: "kgctl",
  113. Short: "Manage a Kilo network",
  114. Long: "",
  115. PersistentPreRunE: runRoot,
  116. Version: version.Version,
  117. SilenceErrors: true,
  118. }
  119. cmd.PersistentFlags().StringVar(&backend, "backend", k8s.Backend, fmt.Sprintf("The backend for the mesh. Possible values: %s", strings.Join(availableBackends, ", ")))
  120. _ = cmd.RegisterFlagCompletionFunc("backend", cobra.FixedCompletions(availableBackends, cobra.ShellCompDirectiveNoFileComp))
  121. cmd.PersistentFlags().StringVar(&granularity, "mesh-granularity", string(mesh.AutoGranularity), fmt.Sprintf("The granularity of the network mesh to create. Possible values: %s", strings.Join(availableGranularities, ", ")))
  122. _ = cmd.RegisterFlagCompletionFunc("mesh-granularity", cobra.FixedCompletions(availableGranularities, cobra.ShellCompDirectiveNoFileComp))
  123. defaultKubeconfig := os.Getenv("KUBECONFIG")
  124. if _, err := os.Stat(defaultKubeconfig); os.IsNotExist(err) {
  125. defaultKubeconfig = filepath.Join(os.Getenv("HOME"), ".kube/config")
  126. }
  127. cmd.PersistentFlags().StringVar(&kubeconfig, "kubeconfig", defaultKubeconfig, "Path to kubeconfig.")
  128. cmd.PersistentFlags().IntVar(&opts.port, "port", mesh.DefaultKiloPort, "The WireGuard port over which the nodes communicate.")
  129. cmd.PersistentFlags().StringVar(&topologyLabel, "topology-label", k8s.RegionLabelKey, "Kubernetes node label used to group nodes into logical locations.")
  130. for _, subCmd := range []*cobra.Command{
  131. graph(),
  132. showConf(),
  133. connect(),
  134. } {
  135. cmd.AddCommand(subCmd)
  136. }
  137. if err := cmd.Execute(); err != nil {
  138. fmt.Fprintf(os.Stderr, "%v\n", err)
  139. os.Exit(1)
  140. }
  141. }
  142. func determineGranularity(gr mesh.Granularity, ns []*mesh.Node) (mesh.Granularity, error) {
  143. if gr == mesh.AutoGranularity {
  144. if len(ns) == 0 {
  145. return gr, errors.New("could not get any nodes")
  146. }
  147. ret := mesh.Granularity(ns[0].Granularity)
  148. switch ret {
  149. case mesh.LogicalGranularity:
  150. case mesh.FullGranularity:
  151. default:
  152. return ret, fmt.Errorf("mesh granularity %s is not supported", opts.granularity)
  153. }
  154. return ret, nil
  155. }
  156. return gr, nil
  157. }