main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. cleanUp bool
  91. cleanUpIface bool
  92. createIface bool
  93. cni bool
  94. cniPath string
  95. compatibility string
  96. encapsulate string
  97. granularity string
  98. hostname string
  99. kubeconfig string
  100. iface string
  101. listen string
  102. local bool
  103. master string
  104. mtu uint
  105. topologyLabel string
  106. port int
  107. serviceCIDRsRaw []string
  108. subnet string
  109. resyncPeriod time.Duration
  110. iptablesForwardRule bool
  111. prioritisePrivateAddr bool
  112. printVersion bool
  113. logLevel string
  114. logger log.Logger
  115. registry *prometheus.Registry
  116. )
  117. func init() {
  118. cmd.Flags().StringVar(&backend, "backend", k8s.Backend, fmt.Sprintf("The backend for the mesh. Possible values: %s", availableBackends))
  119. cmd.Flags().BoolVar(&cleanUp, "clean-up", true, "Should kilo clean up network modifications on shutdown?")
  120. cmd.Flags().BoolVar(&cleanUpIface, "clean-up-interface", false, "Should Kilo delete its interface when it shuts down?")
  121. cmd.Flags().BoolVar(&createIface, "create-interface", true, "Should kilo create an interface on startup?")
  122. cmd.Flags().BoolVar(&cni, "cni", true, "Should Kilo manage the node's CNI configuration?")
  123. cmd.Flags().StringVar(&cniPath, "cni-path", mesh.DefaultCNIPath, "Path to CNI config.")
  124. cmd.Flags().StringVar(&compatibility, "compatibility", "", fmt.Sprintf("Should Kilo run in compatibility mode? Possible values: %s", availableCompatibilities))
  125. cmd.Flags().StringVar(&encapsulate, "encapsulate", string(encapsulation.Always), fmt.Sprintf("When should Kilo encapsulate packets within a location? Possible values: %s", availableEncapsulations))
  126. cmd.Flags().StringVar(&granularity, "mesh-granularity", string(mesh.LogicalGranularity), fmt.Sprintf("The granularity of the network mesh to create. Possible values: %s", availableGranularities))
  127. cmd.Flags().StringVar(&kubeconfig, "kubeconfig", "", "Path to kubeconfig.")
  128. cmd.Flags().StringVar(&hostname, "hostname", "", "Hostname of the node on which this process is running.")
  129. cmd.Flags().StringVar(&iface, "interface", mesh.DefaultKiloInterface, "Name of the Kilo interface to use; if it does not exist, it will be created.")
  130. cmd.Flags().StringVar(&listen, "listen", ":1107", "The address at which to listen for health and metrics.")
  131. cmd.Flags().BoolVar(&local, "local", true, "Should Kilo manage routes within a location?")
  132. cmd.Flags().StringVar(&master, "master", "", "The address of the Kubernetes API server (overrides any value in kubeconfig).")
  133. cmd.Flags().UintVar(&mtu, "mtu", wireguard.DefaultMTU, "The MTU of the WireGuard interface created by Kilo.")
  134. cmd.Flags().StringVar(&topologyLabel, "topology-label", k8s.RegionLabelKey, "Kubernetes node label used to group nodes into logical locations.")
  135. cmd.Flags().IntVar(&port, "port", mesh.DefaultKiloPort, "The port over which WireGuard peers should communicate.")
  136. cmd.Flags().StringSliceVar(&serviceCIDRsRaw, "service-cidr", nil, "The service CIDR for the Kubernetes cluster. Can be provided optionally to avoid masquerading packets sent to service IPs. Can be specified multiple times.")
  137. cmd.Flags().StringVar(&subnet, "subnet", mesh.DefaultKiloSubnet.String(), "CIDR from which to allocate addresses for WireGuard interfaces.")
  138. cmd.Flags().DurationVar(&resyncPeriod, "resync-period", 30*time.Second, "How often should the Kilo controllers reconcile?")
  139. 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!")
  140. cmd.Flags().BoolVar(&prioritisePrivateAddr, "prioritise-private-addresses", false, "Prefer to assign a private IP address to the node's endpoint.")
  141. cmd.PersistentFlags().BoolVar(&printVersion, "version", false, "Print version and exit")
  142. cmd.PersistentFlags().StringVar(&logLevel, "log-level", logLevelInfo, fmt.Sprintf("Log level to use. Possible values: %s", availableLogLevels))
  143. }
  144. func preRun(_ *cobra.Command, _ []string) error {
  145. logger = log.NewJSONLogger(log.NewSyncWriter(os.Stdout))
  146. switch logLevel {
  147. case logLevelAll:
  148. logger = level.NewFilter(logger, level.AllowAll())
  149. case logLevelDebug:
  150. logger = level.NewFilter(logger, level.AllowDebug())
  151. case logLevelInfo:
  152. logger = level.NewFilter(logger, level.AllowInfo())
  153. case logLevelWarn:
  154. logger = level.NewFilter(logger, level.AllowWarn())
  155. case logLevelError:
  156. logger = level.NewFilter(logger, level.AllowError())
  157. case logLevelNone:
  158. logger = level.NewFilter(logger, level.AllowNone())
  159. default:
  160. return fmt.Errorf("log level %v unknown; possible values are: %s", logLevel, availableLogLevels)
  161. }
  162. logger = log.With(logger, "ts", log.DefaultTimestampUTC)
  163. logger = log.With(logger, "caller", log.DefaultCaller)
  164. registry = prometheus.NewRegistry()
  165. registry.MustRegister(
  166. collectors.NewGoCollector(),
  167. collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
  168. )
  169. return nil
  170. }
  171. // runRoot is the principal function for the binary.
  172. func runRoot(_ *cobra.Command, _ []string) error {
  173. if printVersion {
  174. fmt.Println(version.Version)
  175. return nil
  176. }
  177. _, s, err := net.ParseCIDR(subnet)
  178. if err != nil {
  179. return fmt.Errorf("failed to parse %q as CIDR: %v", subnet, err)
  180. }
  181. if hostname == "" {
  182. var err error
  183. hostname, err = os.Hostname()
  184. if hostname == "" || err != nil {
  185. return errors.New("failed to determine hostname")
  186. }
  187. }
  188. e := encapsulation.Strategy(encapsulate)
  189. switch e {
  190. case encapsulation.Never:
  191. case encapsulation.CrossSubnet:
  192. case encapsulation.Always:
  193. default:
  194. return fmt.Errorf("encapsulation %v unknown; possible values are: %s", encapsulate, availableEncapsulations)
  195. }
  196. var enc encapsulation.Encapsulator
  197. switch compatibility {
  198. case "flannel":
  199. enc = encapsulation.NewFlannel(e)
  200. case "cilium":
  201. enc = encapsulation.NewCilium(e)
  202. default:
  203. enc = encapsulation.NewIPIP(e)
  204. }
  205. gr := mesh.Granularity(granularity)
  206. switch gr {
  207. case mesh.LogicalGranularity:
  208. case mesh.FullGranularity:
  209. default:
  210. return fmt.Errorf("mesh granularity %v unknown; possible values are: %s", granularity, availableGranularities)
  211. }
  212. var b mesh.Backend
  213. switch backend {
  214. case k8s.Backend:
  215. config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
  216. if err != nil {
  217. return fmt.Errorf("failed to create Kubernetes config: %v", err)
  218. }
  219. c := kubernetes.NewForConfigOrDie(config)
  220. kc := kiloclient.NewForConfigOrDie(config)
  221. ec := apiextensions.NewForConfigOrDie(config)
  222. b = k8s.New(c, kc, ec, topologyLabel, log.With(logger, "component", "k8s backend"))
  223. default:
  224. return fmt.Errorf("backend %v unknown; possible values are: %s", backend, availableBackends)
  225. }
  226. if port < 1 || port > 1<<16-1 {
  227. return fmt.Errorf("invalid port: port mus be in range [%d:%d], but got %d", 1, 1<<16-1, port)
  228. }
  229. var serviceCIDRs []*net.IPNet
  230. for _, serviceCIDR := range serviceCIDRsRaw {
  231. _, s, err := net.ParseCIDR(serviceCIDR)
  232. if err != nil {
  233. return fmt.Errorf("failed to parse %q as CIDR: %v", serviceCIDR, err)
  234. }
  235. serviceCIDRs = append(serviceCIDRs, s)
  236. }
  237. m, err := mesh.New(b, enc, gr, hostname, port, s, local, cni, cniPath, iface, cleanUp, cleanUpIface, createIface, mtu, resyncPeriod, prioritisePrivateAddr, iptablesForwardRule, serviceCIDRs, log.With(logger, "component", "kilo"), registry)
  238. if err != nil {
  239. return fmt.Errorf("failed to create Kilo mesh: %v", err)
  240. }
  241. var g run.Group
  242. {
  243. h := internalserver.NewHandler(
  244. internalserver.WithName("Internal Kilo API"),
  245. internalserver.WithPrometheusRegistry(registry),
  246. internalserver.WithPProf(),
  247. )
  248. h.AddEndpoint("/health", "Exposes health checks", healthHandler)
  249. h.AddEndpoint("/graph", "Exposes Kilo mesh topology graph", (&graphHandler{m, gr, &hostname, s, serviceCIDRs}).ServeHTTP)
  250. // Run the HTTP server.
  251. l, err := net.Listen("tcp", listen)
  252. if err != nil {
  253. return fmt.Errorf("failed to listen on %s: %v", listen, err)
  254. }
  255. g.Add(func() error {
  256. if err := http.Serve(l, h); err != nil && err != http.ErrServerClosed {
  257. return fmt.Errorf("error: server exited unexpectedly: %v", err)
  258. }
  259. return nil
  260. }, func(error) {
  261. l.Close()
  262. })
  263. }
  264. {
  265. ctx, cancel := context.WithCancel(context.Background())
  266. // Start the mesh.
  267. g.Add(func() error {
  268. logger.Log("msg", fmt.Sprintf("Starting Kilo network mesh '%v'.", version.Version))
  269. if err := m.Run(ctx); err != nil {
  270. return fmt.Errorf("error: Kilo exited unexpectedly: %v", err)
  271. }
  272. return nil
  273. }, func(error) {
  274. cancel()
  275. })
  276. }
  277. {
  278. // Exit gracefully on SIGINT and SIGTERM.
  279. term := make(chan os.Signal, 1)
  280. signal.Notify(term, syscall.SIGINT, syscall.SIGTERM)
  281. cancel := make(chan struct{})
  282. g.Add(func() error {
  283. for {
  284. select {
  285. case <-term:
  286. logger.Log("msg", "caught interrupt; gracefully cleaning up; see you next time!")
  287. return nil
  288. case <-cancel:
  289. return nil
  290. }
  291. }
  292. }, func(error) {
  293. close(cancel)
  294. })
  295. }
  296. return g.Run()
  297. }
  298. var versionCmd = &cobra.Command{
  299. Use: "version",
  300. Short: "Print the version and exit.",
  301. Run: func(_ *cobra.Command, _ []string) { fmt.Println(version.Version) },
  302. }
  303. func main() {
  304. cmd.AddCommand(webhookCmd, versionCmd)
  305. if err := cmd.Execute(); err != nil {
  306. fmt.Fprintf(os.Stderr, "%v\n", err)
  307. os.Exit(1)
  308. }
  309. }