main.go 11 KB

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