main.go 14 KB

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