main.go 7.8 KB

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