main.go 8.1 KB

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