main.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // Copyright 2019 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. flag "github.com/spf13/pflag"
  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/kilo-io/kilo/pkg/encapsulation"
  35. "github.com/kilo-io/kilo/pkg/k8s"
  36. kiloclient "github.com/kilo-io/kilo/pkg/k8s/clientset/versioned"
  37. "github.com/kilo-io/kilo/pkg/mesh"
  38. "github.com/kilo-io/kilo/pkg/version"
  39. "github.com/kilo-io/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. // Main is the principal function for the binary, wrapped only by `main` for convenience.
  75. func Main() error {
  76. backend := flag.String("backend", k8s.Backend, fmt.Sprintf("The backend for the mesh. Possible values: %s", availableBackends))
  77. cleanUpIface := flag.Bool("clean-up-interface", false, "Should Kilo delete its interface when it shuts down?")
  78. createIface := flag.Bool("create-interface", true, "Should kilo create an interface on startup?")
  79. cni := flag.Bool("cni", true, "Should Kilo manage the node's CNI configuration?")
  80. cniPath := flag.String("cni-path", mesh.DefaultCNIPath, "Path to CNI config.")
  81. compatibility := flag.String("compatibility", "", fmt.Sprintf("Should Kilo run in compatibility mode? Possible values: %s", availableCompatibilities))
  82. encapsulate := flag.String("encapsulate", string(encapsulation.Always), fmt.Sprintf("When should Kilo encapsulate packets within a location? Possible values: %s", availableEncapsulations))
  83. granularity := flag.String("mesh-granularity", string(mesh.LogicalGranularity), fmt.Sprintf("The granularity of the network mesh to create. Possible values: %s", availableGranularities))
  84. kubeconfig := flag.String("kubeconfig", "", "Path to kubeconfig.")
  85. hostname := flag.String("hostname", "", "Hostname of the node on which this process is running.")
  86. iface := flag.String("interface", mesh.DefaultKiloInterface, "Name of the Kilo interface to use; if it does not exist, it will be created.")
  87. listen := flag.String("listen", ":1107", "The address at which to listen for health and metrics.")
  88. local := flag.Bool("local", true, "Should Kilo manage routes within a location?")
  89. logLevel := flag.String("log-level", logLevelInfo, fmt.Sprintf("Log level to use. Possible values: %s", availableLogLevels))
  90. master := flag.String("master", "", "The address of the Kubernetes API server (overrides any value in kubeconfig).")
  91. mtu := flag.Uint("mtu", wireguard.DefaultMTU, "The MTU of the WireGuard interface created by Kilo.")
  92. topologyLabel := flag.String("topology-label", k8s.RegionLabelKey, "Kubernetes node label used to group nodes into logical locations.")
  93. var port uint
  94. flag.UintVar(&port, "port", mesh.DefaultKiloPort, "The port over which WireGuard peers should communicate.")
  95. subnet := flag.String("subnet", mesh.DefaultKiloSubnet.String(), "CIDR from which to allocate addresses for WireGuard interfaces.")
  96. resyncPeriod := flag.Duration("resync-period", 30*time.Second, "How often should the Kilo controllers reconcile?")
  97. printVersion := flag.Bool("version", false, "Print version and exit")
  98. flag.Parse()
  99. if *printVersion {
  100. fmt.Println(version.Version)
  101. return nil
  102. }
  103. _, s, err := net.ParseCIDR(*subnet)
  104. if err != nil {
  105. return fmt.Errorf("failed to parse %q as CIDR: %v", *subnet, err)
  106. }
  107. if *hostname == "" {
  108. var err error
  109. *hostname, err = os.Hostname()
  110. if *hostname == "" || err != nil {
  111. return errors.New("failed to determine hostname")
  112. }
  113. }
  114. logger := log.NewJSONLogger(log.NewSyncWriter(os.Stdout))
  115. switch *logLevel {
  116. case logLevelAll:
  117. logger = level.NewFilter(logger, level.AllowAll())
  118. case logLevelDebug:
  119. logger = level.NewFilter(logger, level.AllowDebug())
  120. case logLevelInfo:
  121. logger = level.NewFilter(logger, level.AllowInfo())
  122. case logLevelWarn:
  123. logger = level.NewFilter(logger, level.AllowWarn())
  124. case logLevelError:
  125. logger = level.NewFilter(logger, level.AllowError())
  126. case logLevelNone:
  127. logger = level.NewFilter(logger, level.AllowNone())
  128. default:
  129. return fmt.Errorf("log level %v unknown; possible values are: %s", *logLevel, availableLogLevels)
  130. }
  131. logger = log.With(logger, "ts", log.DefaultTimestampUTC)
  132. logger = log.With(logger, "caller", log.DefaultCaller)
  133. e := encapsulation.Strategy(*encapsulate)
  134. switch e {
  135. case encapsulation.Never:
  136. case encapsulation.CrossSubnet:
  137. case encapsulation.Always:
  138. default:
  139. return fmt.Errorf("encapsulation %v unknown; possible values are: %s", *encapsulate, availableEncapsulations)
  140. }
  141. var enc encapsulation.Encapsulator
  142. switch *compatibility {
  143. case "flannel":
  144. enc = encapsulation.NewFlannel(e)
  145. default:
  146. enc = encapsulation.NewIPIP(e)
  147. }
  148. gr := mesh.Granularity(*granularity)
  149. switch gr {
  150. case mesh.LogicalGranularity:
  151. case mesh.FullGranularity:
  152. default:
  153. return fmt.Errorf("mesh granularity %v unknown; possible values are: %s", *granularity, availableGranularities)
  154. }
  155. var b mesh.Backend
  156. switch *backend {
  157. case k8s.Backend:
  158. config, err := clientcmd.BuildConfigFromFlags(*master, *kubeconfig)
  159. if err != nil {
  160. return fmt.Errorf("failed to create Kubernetes config: %v", err)
  161. }
  162. c := kubernetes.NewForConfigOrDie(config)
  163. kc := kiloclient.NewForConfigOrDie(config)
  164. ec := apiextensions.NewForConfigOrDie(config)
  165. b = k8s.New(c, kc, ec, *topologyLabel)
  166. default:
  167. return fmt.Errorf("backend %v unknown; possible values are: %s", *backend, availableBackends)
  168. }
  169. m, err := mesh.New(b, enc, gr, *hostname, uint32(port), s, *local, *cni, *cniPath, *iface, *cleanUpIface, *createIface, *mtu, *resyncPeriod, log.With(logger, "component", "kilo"))
  170. if err != nil {
  171. return fmt.Errorf("failed to create Kilo mesh: %v", err)
  172. }
  173. r := prometheus.NewRegistry()
  174. r.MustRegister(
  175. prometheus.NewGoCollector(),
  176. prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),
  177. )
  178. m.RegisterMetrics(r)
  179. var g run.Group
  180. {
  181. // Run the HTTP server.
  182. mux := http.NewServeMux()
  183. mux.HandleFunc("/health", healthHandler)
  184. mux.Handle("/graph", &graphHandler{m, gr, hostname, s})
  185. mux.Handle("/metrics", promhttp.HandlerFor(r, promhttp.HandlerOpts{}))
  186. l, err := net.Listen("tcp", *listen)
  187. if err != nil {
  188. return fmt.Errorf("failed to listen on %s: %v", *listen, err)
  189. }
  190. g.Add(func() error {
  191. if err := http.Serve(l, mux); err != nil && err != http.ErrServerClosed {
  192. return fmt.Errorf("error: server exited unexpectedly: %v", err)
  193. }
  194. return nil
  195. }, func(error) {
  196. l.Close()
  197. })
  198. }
  199. {
  200. // Start the mesh.
  201. g.Add(func() error {
  202. logger.Log("msg", fmt.Sprintf("Starting Kilo network mesh '%v'.", version.Version))
  203. if err := m.Run(); err != nil {
  204. return fmt.Errorf("error: Kilo exited unexpectedly: %v", err)
  205. }
  206. return nil
  207. }, func(error) {
  208. m.Stop()
  209. })
  210. }
  211. {
  212. // Exit gracefully on SIGINT and SIGTERM.
  213. term := make(chan os.Signal, 1)
  214. signal.Notify(term, syscall.SIGINT, syscall.SIGTERM)
  215. cancel := make(chan struct{})
  216. g.Add(func() error {
  217. for {
  218. select {
  219. case <-term:
  220. logger.Log("msg", "caught interrupt; gracefully cleaning up; see you next time!")
  221. return nil
  222. case <-cancel:
  223. return nil
  224. }
  225. }
  226. }, func(error) {
  227. close(cancel)
  228. })
  229. }
  230. return g.Run()
  231. }
  232. func main() {
  233. if err := Main(); err != nil {
  234. fmt.Fprintf(os.Stderr, "%v\n", err)
  235. os.Exit(1)
  236. }
  237. }