main.go 12 KB

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