main.go 12 KB

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