main.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. "k8s.io/client-go/kubernetes"
  31. "k8s.io/client-go/tools/clientcmd"
  32. "github.com/squat/kilo/pkg/k8s"
  33. "github.com/squat/kilo/pkg/mesh"
  34. "github.com/squat/kilo/pkg/version"
  35. )
  36. const (
  37. logLevelAll = "all"
  38. logLevelDebug = "debug"
  39. logLevelInfo = "info"
  40. logLevelWarn = "warn"
  41. logLevelError = "error"
  42. logLevelNone = "none"
  43. )
  44. var (
  45. availableBackends = strings.Join([]string{
  46. k8s.Backend,
  47. }, ", ")
  48. availableEncapsulations = strings.Join([]string{
  49. string(mesh.NeverEncapsulate),
  50. string(mesh.CrossSubnetEncapsulate),
  51. string(mesh.AlwaysEncapsulate),
  52. }, ", ")
  53. availableGranularities = strings.Join([]string{
  54. string(mesh.DataCenterGranularity),
  55. string(mesh.NodeGranularity),
  56. }, ", ")
  57. availableLogLevels = strings.Join([]string{
  58. logLevelAll,
  59. logLevelDebug,
  60. logLevelInfo,
  61. logLevelWarn,
  62. logLevelError,
  63. logLevelNone,
  64. }, ", ")
  65. )
  66. // Main is the principal function for the binary, wrapped only by `main` for convenience.
  67. func Main() error {
  68. backend := flag.String("backend", k8s.Backend, fmt.Sprintf("The backend for the mesh. Possible values: %s", availableBackends))
  69. encapsulate := flag.String("encapsulate", string(mesh.AlwaysEncapsulate), fmt.Sprintf("When should Kilo encapsulate packets within a location. Possible values: %s", availableEncapsulations))
  70. granularity := flag.String("mesh-granularity", string(mesh.DataCenterGranularity), fmt.Sprintf("The granularity of the network mesh to create. Possible values: %s", availableGranularities))
  71. kubeconfig := flag.String("kubeconfig", "", "Path to kubeconfig.")
  72. hostname := flag.String("hostname", "", "Hostname of the node on which this process is running.")
  73. listen := flag.String("listen", "localhost:1107", "The address at which to listen for health and metrics.")
  74. local := flag.Bool("local", true, "Should Kilo manage routes within a location.")
  75. logLevel := flag.String("log-level", logLevelInfo, fmt.Sprintf("Log level to use. Possible values: %s", availableLogLevels))
  76. master := flag.String("master", "", "The address of the Kubernetes API server (overrides any value in kubeconfig).")
  77. port := flag.Int("port", 51820, "The port over which WireGuard peers should communicate.")
  78. subnet := flag.String("subnet", "10.4.0.0/16", "CIDR from which to allocate addressees to WireGuard interfaces.")
  79. printVersion := flag.Bool("version", false, "Print version and exit")
  80. flag.Parse()
  81. if *printVersion {
  82. fmt.Println(version.Version)
  83. return nil
  84. }
  85. _, s, err := net.ParseCIDR(*subnet)
  86. if err != nil {
  87. return fmt.Errorf("failed to parse %q as CIDR: %v", *subnet, err)
  88. }
  89. if *hostname == "" {
  90. var err error
  91. *hostname, err = os.Hostname()
  92. if *hostname == "" || err != nil {
  93. return errors.New("failed to determine hostname")
  94. }
  95. }
  96. logger := log.NewJSONLogger(log.NewSyncWriter(os.Stdout))
  97. switch *logLevel {
  98. case logLevelAll:
  99. logger = level.NewFilter(logger, level.AllowAll())
  100. case logLevelDebug:
  101. logger = level.NewFilter(logger, level.AllowDebug())
  102. case logLevelInfo:
  103. logger = level.NewFilter(logger, level.AllowInfo())
  104. case logLevelWarn:
  105. logger = level.NewFilter(logger, level.AllowWarn())
  106. case logLevelError:
  107. logger = level.NewFilter(logger, level.AllowError())
  108. case logLevelNone:
  109. logger = level.NewFilter(logger, level.AllowNone())
  110. default:
  111. return fmt.Errorf("log level %v unknown; posible values are: %s", *logLevel, availableLogLevels)
  112. }
  113. logger = log.With(logger, "ts", log.DefaultTimestampUTC)
  114. logger = log.With(logger, "caller", log.DefaultCaller)
  115. e := mesh.Encapsulate(*encapsulate)
  116. switch e {
  117. case mesh.NeverEncapsulate:
  118. case mesh.CrossSubnetEncapsulate:
  119. case mesh.AlwaysEncapsulate:
  120. default:
  121. return fmt.Errorf("encapsulation %v unknown; posible values are: %s", *encapsulate, availableEncapsulations)
  122. }
  123. gr := mesh.Granularity(*granularity)
  124. switch gr {
  125. case mesh.DataCenterGranularity:
  126. case mesh.NodeGranularity:
  127. default:
  128. return fmt.Errorf("mesh granularity %v unknown; posible values are: %s", *granularity, availableGranularities)
  129. }
  130. var b mesh.Backend
  131. switch *backend {
  132. case k8s.Backend:
  133. config, err := clientcmd.BuildConfigFromFlags(*master, *kubeconfig)
  134. if err != nil {
  135. return fmt.Errorf("failed to create Kubernetes config: %v", err)
  136. }
  137. client := kubernetes.NewForConfigOrDie(config)
  138. b = k8s.New(client)
  139. default:
  140. return fmt.Errorf("backend %v unknown; posible values are: %s", *backend, availableBackends)
  141. }
  142. m, err := mesh.New(b, e, gr, *hostname, *port, s, *local, log.With(logger, "component", "kilo"))
  143. if err != nil {
  144. return fmt.Errorf("failed to create Kilo mesh: %v", err)
  145. }
  146. r := prometheus.NewRegistry()
  147. r.MustRegister(
  148. prometheus.NewGoCollector(),
  149. prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),
  150. )
  151. m.RegisterMetrics(r)
  152. var g run.Group
  153. {
  154. // Run the HTTP server.
  155. mux := http.NewServeMux()
  156. mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
  157. w.WriteHeader(http.StatusOK)
  158. })
  159. mux.Handle("/metrics", promhttp.HandlerFor(r, promhttp.HandlerOpts{}))
  160. l, err := net.Listen("tcp", *listen)
  161. if err != nil {
  162. return fmt.Errorf("failed to listen on %s: %v", *listen, err)
  163. }
  164. g.Add(func() error {
  165. if err := http.Serve(l, mux); err != nil && err != http.ErrServerClosed {
  166. return fmt.Errorf("error: server exited unexpectedly: %v", err)
  167. }
  168. return nil
  169. }, func(error) {
  170. l.Close()
  171. })
  172. }
  173. {
  174. // Start the mesh.
  175. g.Add(func() error {
  176. logger.Log("msg", fmt.Sprintf("Starting Kilo network mesh '%v'.", version.Version))
  177. if err := m.Run(); err != nil {
  178. return fmt.Errorf("error: Kilo exited unexpectedly: %v", err)
  179. }
  180. return nil
  181. }, func(error) {
  182. m.Stop()
  183. })
  184. }
  185. {
  186. // Exit gracefully on SIGINT and SIGTERM.
  187. term := make(chan os.Signal, 1)
  188. signal.Notify(term, syscall.SIGINT, syscall.SIGTERM)
  189. cancel := make(chan struct{})
  190. g.Add(func() error {
  191. for {
  192. select {
  193. case <-term:
  194. logger.Log("msg", "caught interrupt; gracefully cleaning up; see you next time!")
  195. return nil
  196. case <-cancel:
  197. return nil
  198. }
  199. }
  200. }, func(error) {
  201. close(cancel)
  202. })
  203. }
  204. return g.Run()
  205. }
  206. func main() {
  207. if err := Main(); err != nil {
  208. fmt.Fprintf(os.Stderr, "%v\n", err)
  209. os.Exit(1)
  210. }
  211. }