main.go 11 KB

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