main.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // Copyright 2021 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. "net"
  19. "net/http"
  20. "os"
  21. "os/signal"
  22. "strings"
  23. "syscall"
  24. "time"
  25. "github.com/go-kit/kit/log"
  26. "github.com/go-kit/kit/log/level"
  27. "github.com/oklog/run"
  28. "github.com/prometheus/client_golang/prometheus"
  29. "github.com/prometheus/client_golang/prometheus/promhttp"
  30. "github.com/spf13/cobra"
  31. apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
  32. "k8s.io/client-go/kubernetes"
  33. "k8s.io/client-go/tools/clientcmd"
  34. "github.com/squat/kilo/pkg/encapsulation"
  35. "github.com/squat/kilo/pkg/k8s"
  36. kiloclient "github.com/squat/kilo/pkg/k8s/clientset/versioned"
  37. "github.com/squat/kilo/pkg/mesh"
  38. "github.com/squat/kilo/pkg/version"
  39. "github.com/squat/kilo/pkg/wireguard"
  40. )
  41. const (
  42. logLevelAll = "all"
  43. logLevelDebug = "debug"
  44. logLevelInfo = "info"
  45. logLevelWarn = "warn"
  46. logLevelError = "error"
  47. logLevelNone = "none"
  48. )
  49. var (
  50. availableBackends = strings.Join([]string{
  51. k8s.Backend,
  52. }, ", ")
  53. availableCompatibilities = strings.Join([]string{
  54. "flannel",
  55. }, ", ")
  56. availableEncapsulations = strings.Join([]string{
  57. string(encapsulation.Never),
  58. string(encapsulation.CrossSubnet),
  59. string(encapsulation.Always),
  60. }, ", ")
  61. availableGranularities = strings.Join([]string{
  62. string(mesh.LogicalGranularity),
  63. string(mesh.FullGranularity),
  64. }, ", ")
  65. availableLogLevels = strings.Join([]string{
  66. logLevelAll,
  67. logLevelDebug,
  68. logLevelInfo,
  69. logLevelWarn,
  70. logLevelError,
  71. logLevelNone,
  72. }, ", ")
  73. )
  74. var cmd = &cobra.Command{
  75. Use: "kg",
  76. Short: "kg is the Kilo agent",
  77. Long: `kg is the Kilo agent.
  78. It runs on every node of a cluster,
  79. setting up the public and private keys for the VPN
  80. as well as the necessary rules to route packets between locations.`,
  81. PreRunE: preRun,
  82. RunE: runRoot,
  83. SilenceUsage: true,
  84. SilenceErrors: true,
  85. }
  86. var (
  87. backend string
  88. cleanUpIface bool
  89. createIface bool
  90. cni bool
  91. cniPath string
  92. compatibility string
  93. encapsulate string
  94. granularity string
  95. hostname string
  96. kubeconfig string
  97. iface string
  98. listen string
  99. local bool
  100. master string
  101. mtu uint
  102. topologyLabel string
  103. port uint
  104. subnet string
  105. resyncPeriod time.Duration
  106. printVersion bool
  107. logLevel string
  108. logger log.Logger
  109. registry *prometheus.Registry
  110. )
  111. func init() {
  112. cmd.Flags().StringVar(&backend, "backend", k8s.Backend, fmt.Sprintf("The backend for the mesh. Possible values: %s", availableBackends))
  113. cmd.Flags().BoolVar(&cleanUpIface, "clean-up-interface", false, "Should Kilo delete its interface when it shuts down?")
  114. cmd.Flags().BoolVar(&createIface, "create-interface", true, "Should kilo create an interface on startup?")
  115. cmd.Flags().BoolVar(&cni, "cni", true, "Should Kilo manage the node's CNI configuration?")
  116. cmd.Flags().StringVar(&cniPath, "cni-path", mesh.DefaultCNIPath, "Path to CNI config.")
  117. cmd.Flags().StringVar(&compatibility, "compatibility", "", fmt.Sprintf("Should Kilo run in compatibility mode? Possible values: %s", availableCompatibilities))
  118. cmd.Flags().StringVar(&encapsulate, "encapsulate", string(encapsulation.Always), fmt.Sprintf("When should Kilo encapsulate packets within a location? Possible values: %s", availableEncapsulations))
  119. cmd.Flags().StringVar(&granularity, "mesh-granularity", string(mesh.LogicalGranularity), fmt.Sprintf("The granularity of the network mesh to create. Possible values: %s", availableGranularities))
  120. cmd.Flags().StringVar(&kubeconfig, "kubeconfig", "", "Path to kubeconfig.")
  121. cmd.Flags().StringVar(&hostname, "hostname", "", "Hostname of the node on which this process is running.")
  122. cmd.Flags().StringVar(&iface, "interface", mesh.DefaultKiloInterface, "Name of the Kilo interface to use; if it does not exist, it will be created.")
  123. cmd.Flags().StringVar(&listen, "listen", ":1107", "The address at which to listen for health and metrics.")
  124. cmd.Flags().BoolVar(&local, "local", true, "Should Kilo manage routes within a location?")
  125. cmd.Flags().StringVar(&master, "master", "", "The address of the Kubernetes API server (overrides any value in kubeconfig).")
  126. cmd.Flags().UintVar(&mtu, "mtu", wireguard.DefaultMTU, "The MTU of the WireGuard interface created by Kilo.")
  127. cmd.Flags().StringVar(&topologyLabel, "topology-label", k8s.RegionLabelKey, "Kubernetes node label used to group nodes into logical locations.")
  128. cmd.Flags().UintVar(&port, "port", mesh.DefaultKiloPort, "The port over which WireGuard peers should communicate.")
  129. cmd.Flags().StringVar(&subnet, "subnet", mesh.DefaultKiloSubnet.String(), "CIDR from which to allocate addresses for WireGuard interfaces.")
  130. cmd.Flags().DurationVar(&resyncPeriod, "resync-period", 30*time.Second, "How often should the Kilo controllers reconcile?")
  131. cmd.PersistentFlags().BoolVar(&printVersion, "version", false, "Print version and exit")
  132. cmd.PersistentFlags().StringVar(&logLevel, "log-level", logLevelInfo, fmt.Sprintf("Log level to use. Possible values: %s", availableLogLevels))
  133. }
  134. func preRun(_ *cobra.Command, _ []string) error {
  135. logger = log.NewJSONLogger(log.NewSyncWriter(os.Stdout))
  136. switch logLevel {
  137. case logLevelAll:
  138. logger = level.NewFilter(logger, level.AllowAll())
  139. case logLevelDebug:
  140. logger = level.NewFilter(logger, level.AllowDebug())
  141. case logLevelInfo:
  142. logger = level.NewFilter(logger, level.AllowInfo())
  143. case logLevelWarn:
  144. logger = level.NewFilter(logger, level.AllowWarn())
  145. case logLevelError:
  146. logger = level.NewFilter(logger, level.AllowError())
  147. case logLevelNone:
  148. logger = level.NewFilter(logger, level.AllowNone())
  149. default:
  150. return fmt.Errorf("log level %v unknown; possible values are: %s", logLevel, availableLogLevels)
  151. }
  152. logger = log.With(logger, "ts", log.DefaultTimestampUTC)
  153. logger = log.With(logger, "caller", log.DefaultCaller)
  154. registry = prometheus.NewRegistry()
  155. registry.MustRegister(
  156. prometheus.NewGoCollector(),
  157. prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),
  158. )
  159. return nil
  160. }
  161. // runRoot is the principal function for the binary.
  162. func runRoot(_ *cobra.Command, _ []string) error {
  163. if printVersion {
  164. fmt.Println(version.Version)
  165. return nil
  166. }
  167. _, s, err := net.ParseCIDR(subnet)
  168. if err != nil {
  169. return fmt.Errorf("failed to parse %q as CIDR: %v", subnet, err)
  170. }
  171. if hostname == "" {
  172. var err error
  173. hostname, err = os.Hostname()
  174. if hostname == "" || err != nil {
  175. return errors.New("failed to determine hostname")
  176. }
  177. }
  178. e := encapsulation.Strategy(encapsulate)
  179. switch e {
  180. case encapsulation.Never:
  181. case encapsulation.CrossSubnet:
  182. case encapsulation.Always:
  183. default:
  184. return fmt.Errorf("encapsulation %v unknown; possible values are: %s", encapsulate, availableEncapsulations)
  185. }
  186. var enc encapsulation.Encapsulator
  187. switch compatibility {
  188. case "flannel":
  189. enc = encapsulation.NewFlannel(e)
  190. default:
  191. enc = encapsulation.NewIPIP(e)
  192. }
  193. gr := mesh.Granularity(granularity)
  194. switch gr {
  195. case mesh.LogicalGranularity:
  196. case mesh.FullGranularity:
  197. default:
  198. return fmt.Errorf("mesh granularity %v unknown; possible values are: %s", granularity, availableGranularities)
  199. }
  200. var b mesh.Backend
  201. switch backend {
  202. case k8s.Backend:
  203. config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
  204. if err != nil {
  205. return fmt.Errorf("failed to create Kubernetes config: %v", err)
  206. }
  207. c := kubernetes.NewForConfigOrDie(config)
  208. kc := kiloclient.NewForConfigOrDie(config)
  209. ec := apiextensions.NewForConfigOrDie(config)
  210. b = k8s.New(c, kc, ec, topologyLabel)
  211. default:
  212. return fmt.Errorf("backend %v unknown; possible values are: %s", backend, availableBackends)
  213. }
  214. m, err := mesh.New(b, enc, gr, hostname, uint32(port), s, local, cni, cniPath, iface, cleanUpIface, createIface, mtu, resyncPeriod, log.With(logger, "component", "kilo"))
  215. if err != nil {
  216. return fmt.Errorf("failed to create Kilo mesh: %v", err)
  217. }
  218. m.RegisterMetrics(registry)
  219. var g run.Group
  220. {
  221. // Run the HTTP server.
  222. mux := http.NewServeMux()
  223. mux.HandleFunc("/health", healthHandler)
  224. mux.Handle("/graph", &graphHandler{m, gr, &hostname, s})
  225. mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
  226. l, err := net.Listen("tcp", listen)
  227. if err != nil {
  228. return fmt.Errorf("failed to listen on %s: %v", listen, err)
  229. }
  230. g.Add(func() error {
  231. if err := http.Serve(l, mux); err != nil && err != http.ErrServerClosed {
  232. return fmt.Errorf("error: server exited unexpectedly: %v", err)
  233. }
  234. return nil
  235. }, func(error) {
  236. l.Close()
  237. })
  238. }
  239. {
  240. // Start the mesh.
  241. g.Add(func() error {
  242. logger.Log("msg", fmt.Sprintf("Starting Kilo network mesh '%v'.", version.Version))
  243. if err := m.Run(); err != nil {
  244. return fmt.Errorf("error: Kilo exited unexpectedly: %v", err)
  245. }
  246. return nil
  247. }, func(error) {
  248. m.Stop()
  249. })
  250. }
  251. {
  252. // Exit gracefully on SIGINT and SIGTERM.
  253. term := make(chan os.Signal, 1)
  254. signal.Notify(term, syscall.SIGINT, syscall.SIGTERM)
  255. cancel := make(chan struct{})
  256. g.Add(func() error {
  257. for {
  258. select {
  259. case <-term:
  260. logger.Log("msg", "caught interrupt; gracefully cleaning up; see you next time!")
  261. return nil
  262. case <-cancel:
  263. return nil
  264. }
  265. }
  266. }, func(error) {
  267. close(cancel)
  268. })
  269. }
  270. return g.Run()
  271. }
  272. var versionCmd = &cobra.Command{
  273. Use: "version",
  274. Short: "Print the version and exit.",
  275. Run: func(_ *cobra.Command, _ []string) { fmt.Println(version.Version) },
  276. }
  277. func main() {
  278. cmd.AddCommand(webhookCmd, versionCmd)
  279. if err := cmd.Execute(); err != nil {
  280. fmt.Fprintf(os.Stderr, "%v\n", err)
  281. os.Exit(1)
  282. }
  283. }