main.go 8.5 KB

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