main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Copyright 2015 flannel 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. "path/filepath"
  24. "strconv"
  25. "strings"
  26. "syscall"
  27. "github.com/coreos/pkg/flagutil"
  28. log "github.com/golang/glog"
  29. "golang.org/x/net/context"
  30. "github.com/coreos/flannel/network"
  31. "github.com/coreos/flannel/pkg/ip"
  32. "github.com/coreos/flannel/subnet"
  33. "github.com/coreos/flannel/subnet/etcdv2"
  34. "github.com/coreos/flannel/subnet/kube"
  35. "github.com/coreos/flannel/version"
  36. "time"
  37. // Backends need to be imported for their init() to get executed and them to register
  38. "github.com/coreos/flannel/backend"
  39. _ "github.com/coreos/flannel/backend/alivpc"
  40. _ "github.com/coreos/flannel/backend/alloc"
  41. _ "github.com/coreos/flannel/backend/awsvpc"
  42. _ "github.com/coreos/flannel/backend/extension"
  43. _ "github.com/coreos/flannel/backend/gce"
  44. _ "github.com/coreos/flannel/backend/hostgw"
  45. _ "github.com/coreos/flannel/backend/udp"
  46. _ "github.com/coreos/flannel/backend/vxlan"
  47. "github.com/coreos/go-systemd/daemon"
  48. )
  49. type CmdLineOpts struct {
  50. etcdEndpoints string
  51. etcdPrefix string
  52. etcdKeyfile string
  53. etcdCertfile string
  54. etcdCAFile string
  55. etcdUsername string
  56. etcdPassword string
  57. help bool
  58. version bool
  59. kubeSubnetMgr bool
  60. iface string
  61. ipMasq bool
  62. subnetFile string
  63. subnetDir string
  64. publicIP string
  65. subnetLeaseRenewMargin int
  66. healthzIP string
  67. healthzPort int
  68. }
  69. var (
  70. opts CmdLineOpts
  71. errInterrupted = errors.New("interrupted")
  72. errCanceled = errors.New("canceled")
  73. )
  74. func init() {
  75. flag.StringVar(&opts.etcdEndpoints, "etcd-endpoints", "http://127.0.0.1:4001,http://127.0.0.1:2379", "a comma-delimited list of etcd endpoints")
  76. flag.StringVar(&opts.etcdPrefix, "etcd-prefix", "/coreos.com/network", "etcd prefix")
  77. flag.StringVar(&opts.etcdKeyfile, "etcd-keyfile", "", "SSL key file used to secure etcd communication")
  78. flag.StringVar(&opts.etcdCertfile, "etcd-certfile", "", "SSL certification file used to secure etcd communication")
  79. flag.StringVar(&opts.etcdCAFile, "etcd-cafile", "", "SSL Certificate Authority file used to secure etcd communication")
  80. flag.StringVar(&opts.etcdUsername, "etcd-username", "", "Username for BasicAuth to etcd")
  81. flag.StringVar(&opts.etcdPassword, "etcd-password", "", "Password for BasicAuth to etcd")
  82. flag.StringVar(&opts.iface, "iface", "", "interface to use (IP or name) for inter-host communication")
  83. flag.StringVar(&opts.subnetFile, "subnet-file", "/run/flannel/subnet.env", "filename where env variables (subnet, MTU, ... ) will be written to")
  84. flag.StringVar(&opts.publicIP, "public-ip", "", "IP accessible by other nodes for inter-host communication")
  85. flag.IntVar(&opts.subnetLeaseRenewMargin, "subnet-lease-renew-margin", 60, "Subnet lease renewal margin, in minutes.")
  86. flag.BoolVar(&opts.ipMasq, "ip-masq", false, "setup IP masquerade rule for traffic destined outside of overlay network")
  87. flag.BoolVar(&opts.kubeSubnetMgr, "kube-subnet-mgr", false, "Contact the Kubernetes API for subnet assignement instead of etcd.")
  88. flag.BoolVar(&opts.help, "help", false, "print this message")
  89. flag.BoolVar(&opts.version, "version", false, "print version and exit")
  90. flag.StringVar(&opts.healthzIP, "healthz-ip", "0.0.0.0", "The IP address for healthz server to listen")
  91. flag.IntVar(&opts.healthzPort, "healthz-port", 0, "The port for healthz server to listen(0 to disable)")
  92. }
  93. func newSubnetManager() (subnet.Manager, error) {
  94. if opts.kubeSubnetMgr {
  95. return kube.NewSubnetManager()
  96. }
  97. cfg := &etcdv2.EtcdConfig{
  98. Endpoints: strings.Split(opts.etcdEndpoints, ","),
  99. Keyfile: opts.etcdKeyfile,
  100. Certfile: opts.etcdCertfile,
  101. CAFile: opts.etcdCAFile,
  102. Prefix: opts.etcdPrefix,
  103. Username: opts.etcdUsername,
  104. Password: opts.etcdPassword,
  105. }
  106. return etcdv2.NewLocalManager(cfg)
  107. }
  108. func main() {
  109. // glog will log to tmp files by default. override so all entries
  110. // can flow into journald (if running under systemd)
  111. flag.Set("logtostderr", "true")
  112. // now parse command line args
  113. flag.Parse()
  114. if flag.NArg() > 0 || opts.help {
  115. fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
  116. flag.PrintDefaults()
  117. os.Exit(0)
  118. }
  119. if opts.version {
  120. fmt.Fprintln(os.Stderr, version.Version)
  121. os.Exit(0)
  122. }
  123. flagutil.SetFlagsFromEnv(flag.CommandLine, "FLANNELD")
  124. // Work out which interface to use
  125. extIface, err := LookupExtIface(opts.iface)
  126. if err != nil {
  127. log.Error("Failed to find interface to use: ", err)
  128. os.Exit(1)
  129. }
  130. sm, err := newSubnetManager()
  131. if err != nil {
  132. log.Error("Failed to create SubnetManager: ", err)
  133. os.Exit(1)
  134. }
  135. log.Infof("Created subnet manager: %+v", sm)
  136. // Register for SIGINT and SIGTERM
  137. log.Info("Installing signal handlers")
  138. sigs := make(chan os.Signal, 1)
  139. signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
  140. ctx, cancel := context.WithCancel(context.Background())
  141. go shutdown(sigs, cancel)
  142. if opts.healthzPort > 0 {
  143. go mustRunHealthz()
  144. }
  145. // Fetch the network config (i.e. what backend to use etc..).
  146. config, err := getConfig(ctx, sm)
  147. if err == errCanceled {
  148. exit()
  149. }
  150. // Create a backend manager then use it to create the backend and register the network with it.
  151. bm := backend.NewManager(ctx, sm, extIface)
  152. be, err := bm.GetBackend(config.BackendType)
  153. if err != nil {
  154. log.Errorf("Error fetching backend: %s", err)
  155. exit()
  156. }
  157. bn, err := be.RegisterNetwork(ctx, config)
  158. if err != nil {
  159. log.Errorf("Error registering network: %s", err)
  160. exit()
  161. }
  162. // Set up ipMasq if needed
  163. if opts.ipMasq {
  164. err = network.SetupIPMasq(config.Network, bn.Lease())
  165. if err != nil {
  166. // Continue, even though it failed.
  167. log.Errorf("Failed to set up IP Masquerade: %v", err)
  168. }
  169. defer func() {
  170. if err := network.TeardownIPMasq(config.Network, bn.Lease()); err != nil {
  171. log.Errorf("Failed to tear down IP Masquerade: %v", err)
  172. }
  173. }()
  174. }
  175. if err := WriteSubnetFile(opts.subnetFile, config.Network, opts.ipMasq, bn); err != nil {
  176. // Continue, even though it failed.
  177. log.Warningf("Failed to write subnet file: %s", err)
  178. } else {
  179. log.Infof("Wrote subnet file to %s", opts.subnetFile)
  180. }
  181. // Start "Running" the backend network. This will block until the context is done so run in another goroutine.
  182. go bn.Run(ctx)
  183. log.Infof("Finished starting backend.")
  184. daemon.SdNotify(false, "READY=1")
  185. // Kube subnet mgr doesn't lease the subnet for this node - it just uses the podCidr that's already assigned.
  186. if opts.kubeSubnetMgr {
  187. // Wait for the shutdown to be signalled
  188. <-ctx.Done()
  189. } else {
  190. // Block waiting to renew the lease
  191. _ = MonitorLease(ctx, sm, bn)
  192. }
  193. // To get to here, the Cancel signal must have been received or the lease has been revoked.
  194. exit()
  195. }
  196. func exit() {
  197. // Wait just a second for the cancel signal to propagate everywhere, then just exit cleanly.
  198. log.Info("Waiting for cancel to propagate...")
  199. time.Sleep(time.Second)
  200. log.Info("Exiting...")
  201. os.Exit(0)
  202. }
  203. func shutdown(sigs chan os.Signal, cancel context.CancelFunc) {
  204. // Wait for the shutdown signal.
  205. <-sigs
  206. // Unregister to get default OS nuke behaviour in case we don't exit cleanly
  207. signal.Stop(sigs)
  208. log.Info("Starting shutdown...")
  209. // Call cancel on the context to close everything down.
  210. cancel()
  211. log.Info("Sent cancel signal...")
  212. }
  213. func getConfig(ctx context.Context, sm subnet.Manager) (*subnet.Config, error) {
  214. // Retry every second until it succeeds
  215. for {
  216. config, err := sm.GetNetworkConfig(ctx)
  217. if err != nil {
  218. log.Errorf("Couldn't fetch network config: %s", err)
  219. } else if config == nil {
  220. log.Warningf("Couldn't find network config: %s", err)
  221. } else {
  222. log.Infof("Found network config - Backend type: %s", config.BackendType)
  223. return config, nil
  224. }
  225. select {
  226. case <-ctx.Done():
  227. return nil, errCanceled
  228. case <-time.After(1 * time.Second):
  229. fmt.Println("timed out")
  230. }
  231. }
  232. }
  233. func MonitorLease(ctx context.Context, sm subnet.Manager, bn backend.Network) error {
  234. // Use the subnet manager to start watching leases.
  235. evts := make(chan subnet.Event)
  236. go subnet.WatchLease(ctx, sm, bn.Lease().Subnet, evts)
  237. renewMargin := time.Duration(opts.subnetLeaseRenewMargin) * time.Minute
  238. dur := bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  239. for {
  240. select {
  241. case <-time.After(dur):
  242. err := sm.RenewLease(ctx, bn.Lease())
  243. if err != nil {
  244. log.Error("Error renewing lease (trying again in 1 min): ", err)
  245. dur = time.Minute
  246. continue
  247. }
  248. log.Info("Lease renewed, new expiration: ", bn.Lease().Expiration)
  249. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  250. case e := <-evts:
  251. switch e.Type {
  252. case subnet.EventAdded:
  253. bn.Lease().Expiration = e.Lease.Expiration
  254. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  255. log.Infof("Waiting for %s to renew lease", dur)
  256. case subnet.EventRemoved:
  257. log.Error("Lease has been revoked. Shutting down daemon.")
  258. return errInterrupted
  259. }
  260. case <-ctx.Done():
  261. log.Infof("Stopped monitoring lease")
  262. return errCanceled
  263. }
  264. }
  265. }
  266. func LookupExtIface(ifname string) (*backend.ExternalInterface, error) {
  267. var iface *net.Interface
  268. var ifaceAddr net.IP
  269. var err error
  270. if len(ifname) > 0 {
  271. if ifaceAddr = net.ParseIP(ifname); ifaceAddr != nil {
  272. log.Infof("Searching for interface using %s", ifaceAddr)
  273. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  274. if err != nil {
  275. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  276. }
  277. } else {
  278. iface, err = net.InterfaceByName(ifname)
  279. if err != nil {
  280. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  281. }
  282. }
  283. } else {
  284. log.Info("Determining IP address of default interface")
  285. if iface, err = ip.GetDefaultGatewayIface(); err != nil {
  286. return nil, fmt.Errorf("failed to get default interface: %s", err)
  287. }
  288. }
  289. if ifaceAddr == nil {
  290. ifaceAddr, err = ip.GetIfaceIP4Addr(iface)
  291. if err != nil {
  292. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  293. }
  294. }
  295. log.Infof("Using interface with name %s and address %s", iface.Name, ifaceAddr)
  296. if iface.MTU == 0 {
  297. return nil, fmt.Errorf("failed to determine MTU for %s interface", ifaceAddr)
  298. }
  299. var extAddr net.IP
  300. if len(opts.publicIP) > 0 {
  301. extAddr = net.ParseIP(opts.publicIP)
  302. if extAddr == nil {
  303. return nil, fmt.Errorf("invalid public IP address: %s", opts.publicIP)
  304. }
  305. log.Infof("Using %s as external address", extAddr)
  306. }
  307. if extAddr == nil {
  308. log.Infof("Defaulting external address to interface address (%s)", ifaceAddr)
  309. extAddr = ifaceAddr
  310. }
  311. return &backend.ExternalInterface{
  312. Iface: iface,
  313. IfaceAddr: ifaceAddr,
  314. ExtAddr: extAddr,
  315. }, nil
  316. }
  317. func WriteSubnetFile(path string, nw ip.IP4Net, ipMasq bool, bn backend.Network) error {
  318. dir, name := filepath.Split(path)
  319. os.MkdirAll(dir, 0755)
  320. tempFile := filepath.Join(dir, "."+name)
  321. f, err := os.Create(tempFile)
  322. if err != nil {
  323. return err
  324. }
  325. // Write out the first usable IP by incrementing
  326. // sn.IP by one
  327. sn := bn.Lease().Subnet
  328. sn.IP += 1
  329. fmt.Fprintf(f, "FLANNEL_NETWORK=%s\n", nw)
  330. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn)
  331. fmt.Fprintf(f, "FLANNEL_MTU=%d\n", bn.MTU())
  332. _, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", ipMasq)
  333. f.Close()
  334. if err != nil {
  335. return err
  336. }
  337. // rename(2) the temporary file to the desired location so that it becomes
  338. // atomically visible with the contents
  339. return os.Rename(tempFile, path)
  340. //TODO - is this safe? What if it's not on the same FS?
  341. }
  342. func mustRunHealthz() {
  343. address := net.JoinHostPort(opts.healthzIP, strconv.Itoa(opts.healthzPort))
  344. log.Infof("Start healthz server on %s", address)
  345. http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  346. w.WriteHeader(http.StatusOK)
  347. w.Write([]byte("flanneld is running"))
  348. })
  349. if err := http.ListenAndServe(address, nil); err != nil {
  350. log.Errorf("Start healthz server error. %v", err)
  351. panic(err)
  352. }
  353. }