main.go 8.3 KB

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