main.go 7.9 KB

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