main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. "github.com/joho/godotenv"
  39. "sync"
  40. // Backends need to be imported for their init() to get executed and them to register
  41. "github.com/coreos/flannel/backend"
  42. _ "github.com/coreos/flannel/backend/alivpc"
  43. _ "github.com/coreos/flannel/backend/alloc"
  44. _ "github.com/coreos/flannel/backend/awsvpc"
  45. _ "github.com/coreos/flannel/backend/extension"
  46. _ "github.com/coreos/flannel/backend/gce"
  47. _ "github.com/coreos/flannel/backend/hostgw"
  48. _ "github.com/coreos/flannel/backend/udp"
  49. _ "github.com/coreos/flannel/backend/vxlan"
  50. "github.com/coreos/go-systemd/daemon"
  51. )
  52. type flagSlice []string
  53. func (t *flagSlice) String() string {
  54. return fmt.Sprintf("%v", *t)
  55. }
  56. func (t *flagSlice) Set(val string) error {
  57. *t = append(*t, val)
  58. return nil
  59. }
  60. type CmdLineOpts struct {
  61. etcdEndpoints string
  62. etcdPrefix string
  63. etcdKeyfile string
  64. etcdCertfile string
  65. etcdCAFile string
  66. etcdUsername string
  67. etcdPassword string
  68. help bool
  69. version bool
  70. kubeSubnetMgr bool
  71. kubeApiUrl string
  72. kubeConfigFile string
  73. iface flagSlice
  74. ifaceRegex flagSlice
  75. ipMasq bool
  76. subnetFile string
  77. subnetDir string
  78. publicIP string
  79. subnetLeaseRenewMargin int
  80. healthzIP string
  81. healthzPort int
  82. }
  83. var (
  84. opts CmdLineOpts
  85. errInterrupted = errors.New("interrupted")
  86. errCanceled = errors.New("canceled")
  87. flannelFlags = flag.NewFlagSet("flannel", flag.ExitOnError)
  88. )
  89. func init() {
  90. flannelFlags.StringVar(&opts.etcdEndpoints, "etcd-endpoints", "http://127.0.0.1:4001,http://127.0.0.1:2379", "a comma-delimited list of etcd endpoints")
  91. flannelFlags.StringVar(&opts.etcdPrefix, "etcd-prefix", "/coreos.com/network", "etcd prefix")
  92. flannelFlags.StringVar(&opts.etcdKeyfile, "etcd-keyfile", "", "SSL key file used to secure etcd communication")
  93. flannelFlags.StringVar(&opts.etcdCertfile, "etcd-certfile", "", "SSL certification file used to secure etcd communication")
  94. flannelFlags.StringVar(&opts.etcdCAFile, "etcd-cafile", "", "SSL Certificate Authority file used to secure etcd communication")
  95. flannelFlags.StringVar(&opts.etcdUsername, "etcd-username", "", "username for BasicAuth to etcd")
  96. flannelFlags.StringVar(&opts.etcdPassword, "etcd-password", "", "password for BasicAuth to etcd")
  97. flannelFlags.Var(&opts.iface, "iface", "interface to use (IP or name) for inter-host communication. Can be specified multiple times to check each option in order. Returns the first match found.")
  98. flannelFlags.Var(&opts.ifaceRegex, "iface-regex", "regex expression to match the first interface to use (IP or name) for inter-host communication. Can be specified multiple times to check each regex in order. Returns the first match found. Regexes are checked after specific interfaces specified by the iface option have already been checked.")
  99. flannelFlags.StringVar(&opts.subnetFile, "subnet-file", "/run/flannel/subnet.env", "filename where env variables (subnet, MTU, ... ) will be written to")
  100. flannelFlags.StringVar(&opts.publicIP, "public-ip", "", "IP accessible by other nodes for inter-host communication")
  101. flannelFlags.IntVar(&opts.subnetLeaseRenewMargin, "subnet-lease-renew-margin", 60, "subnet lease renewal margin, in minutes.")
  102. flannelFlags.BoolVar(&opts.ipMasq, "ip-masq", false, "setup IP masquerade rule for traffic destined outside of overlay network")
  103. flannelFlags.BoolVar(&opts.kubeSubnetMgr, "kube-subnet-mgr", false, "contact the Kubernetes API for subnet assignment instead of etcd.")
  104. flannelFlags.StringVar(&opts.kubeApiUrl, "kube-api-url", "", "Kubernetes API server URL. Does not need to be specified if flannel is running in a pod.")
  105. flannelFlags.StringVar(&opts.kubeConfigFile, "kubeconfig-file", "", "kubeconfig file location. Does not need to be specified if flannel is running in a pod.")
  106. flannelFlags.BoolVar(&opts.version, "version", false, "print version and exit")
  107. flannelFlags.StringVar(&opts.healthzIP, "healthz-ip", "0.0.0.0", "the IP address for healthz server to listen")
  108. flannelFlags.IntVar(&opts.healthzPort, "healthz-port", 0, "the port for healthz server to listen(0 to disable)")
  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. // Only copy the non file logging options from glog
  113. copyFlag("v")
  114. copyFlag("vmodule")
  115. copyFlag("log_backtrace_at")
  116. // Define the usage function
  117. flannelFlags.Usage = usage
  118. // now parse command line args
  119. flannelFlags.Parse(os.Args[1:])
  120. }
  121. func copyFlag(name string) {
  122. flannelFlags.Var(flag.Lookup(name).Value, flag.Lookup(name).Name, flag.Lookup(name).Usage)
  123. }
  124. func usage() {
  125. fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
  126. flannelFlags.PrintDefaults()
  127. os.Exit(0)
  128. }
  129. func newSubnetManager() (subnet.Manager, error) {
  130. if opts.kubeSubnetMgr {
  131. return kube.NewSubnetManager(opts.kubeApiUrl, opts.kubeConfigFile)
  132. }
  133. cfg := &etcdv2.EtcdConfig{
  134. Endpoints: strings.Split(opts.etcdEndpoints, ","),
  135. Keyfile: opts.etcdKeyfile,
  136. Certfile: opts.etcdCertfile,
  137. CAFile: opts.etcdCAFile,
  138. Prefix: opts.etcdPrefix,
  139. Username: opts.etcdUsername,
  140. Password: opts.etcdPassword,
  141. }
  142. // Attempt to renew the lease for the subnet specified in the subnetFile
  143. prevSubnet := ReadSubnetFromSubnetFile(opts.subnetFile)
  144. return etcdv2.NewLocalManager(cfg, prevSubnet)
  145. }
  146. func main() {
  147. if opts.version {
  148. fmt.Fprintln(os.Stderr, version.Version)
  149. os.Exit(0)
  150. }
  151. flagutil.SetFlagsFromEnv(flannelFlags, "FLANNELD")
  152. // Work out which interface to use
  153. var extIface *backend.ExternalInterface
  154. var err error
  155. // Check the default interface only if no interfaces are specified
  156. if len(opts.iface) == 0 && len(opts.ifaceRegex) == 0 {
  157. extIface, err = LookupExtIface("", "")
  158. if err != nil {
  159. log.Error("Failed to find any valid interface to use: ", err)
  160. os.Exit(1)
  161. }
  162. } else {
  163. // Check explicitly specified interfaces
  164. for _, iface := range opts.iface {
  165. extIface, err = LookupExtIface(iface, "")
  166. if err != nil {
  167. log.Infof("Could not find valid interface matching %s: %s", iface, err)
  168. }
  169. if extIface != nil {
  170. break
  171. }
  172. }
  173. // Check interfaces that match any specified regexes
  174. if extIface == nil {
  175. for _, ifaceRegex := range opts.ifaceRegex {
  176. extIface, err = LookupExtIface("", ifaceRegex)
  177. if err != nil {
  178. log.Infof("Could not find valid interface matching %s: %s", ifaceRegex, err)
  179. }
  180. if extIface != nil {
  181. break
  182. }
  183. }
  184. }
  185. if extIface == nil {
  186. // Exit if any of the specified interfaces do not match
  187. log.Error("Failed to find interface to use that matches the interfaces and/or regexes provided")
  188. os.Exit(1)
  189. }
  190. }
  191. sm, err := newSubnetManager()
  192. if err != nil {
  193. log.Error("Failed to create SubnetManager: ", err)
  194. os.Exit(1)
  195. }
  196. log.Infof("Created subnet manager: %s", sm.Name())
  197. // Register for SIGINT and SIGTERM
  198. log.Info("Installing signal handlers")
  199. sigs := make(chan os.Signal, 1)
  200. signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
  201. // This is the main context that everything should run in.
  202. // All spawned goroutines should exit when cancel is called on this context.
  203. // Go routines spawned from main.go coordinate using a WaitGroup. This provides a mechanism to allow the shutdownHandler goroutine
  204. // to block until all the goroutines return . If those goroutines spawn other goroutines then they are responsible for
  205. // blocking and returning only when cancel() is called.
  206. ctx, cancel := context.WithCancel(context.Background())
  207. wg := sync.WaitGroup{}
  208. wg.Add(1)
  209. go func() {
  210. shutdownHandler(ctx, sigs, cancel)
  211. wg.Done()
  212. }()
  213. if opts.healthzPort > 0 {
  214. // It's not super easy to shutdown the HTTP server so don't attempt to stop it cleanly
  215. go mustRunHealthz()
  216. }
  217. // Fetch the network config (i.e. what backend to use etc..).
  218. config, err := getConfig(ctx, sm)
  219. if err == errCanceled {
  220. wg.Wait()
  221. os.Exit(0)
  222. }
  223. // Create a backend manager then use it to create the backend and register the network with it.
  224. bm := backend.NewManager(ctx, sm, extIface)
  225. be, err := bm.GetBackend(config.BackendType)
  226. if err != nil {
  227. log.Errorf("Error fetching backend: %s", err)
  228. cancel()
  229. wg.Wait()
  230. os.Exit(1)
  231. }
  232. bn, err := be.RegisterNetwork(ctx, config)
  233. if err != nil {
  234. log.Errorf("Error registering network: %s", err)
  235. cancel()
  236. wg.Wait()
  237. os.Exit(1)
  238. }
  239. // Set up ipMasq if needed
  240. if opts.ipMasq {
  241. err = network.SetupIPMasq(config.Network, bn.Lease())
  242. if err != nil {
  243. // Continue, even though it failed.
  244. log.Errorf("Failed to set up IP Masquerade: %v", err)
  245. }
  246. defer func() {
  247. if err := network.TeardownIPMasq(config.Network, bn.Lease()); err != nil {
  248. log.Errorf("Failed to tear down IP Masquerade: %v", err)
  249. }
  250. }()
  251. }
  252. if err := WriteSubnetFile(opts.subnetFile, config.Network, opts.ipMasq, bn); err != nil {
  253. // Continue, even though it failed.
  254. log.Warningf("Failed to write subnet file: %s", err)
  255. } else {
  256. log.Infof("Wrote subnet file to %s", opts.subnetFile)
  257. }
  258. // Start "Running" the backend network. This will block until the context is done so run in another goroutine.
  259. log.Info("Running backend.")
  260. wg.Add(1)
  261. go func() {
  262. bn.Run(ctx)
  263. wg.Done()
  264. }()
  265. daemon.SdNotify(false, "READY=1")
  266. // Kube subnet mgr doesn't lease the subnet for this node - it just uses the podCidr that's already assigned.
  267. if !opts.kubeSubnetMgr {
  268. err = MonitorLease(ctx, sm, bn, &wg)
  269. if err == errInterrupted {
  270. // The lease was "revoked" - shut everything down
  271. cancel()
  272. }
  273. }
  274. log.Info("Waiting for all goroutines to exit")
  275. // Block waiting for all the goroutines to finish.
  276. wg.Wait()
  277. log.Info("Exiting cleanly...")
  278. os.Exit(0)
  279. }
  280. func shutdownHandler(ctx context.Context, sigs chan os.Signal, cancel context.CancelFunc) {
  281. // Wait for the context do be Done or for the signal to come in to shutdown.
  282. select {
  283. case <-ctx.Done():
  284. log.Info("Stopping shutdownHandler...")
  285. case <-sigs:
  286. // Call cancel on the context to close everything down.
  287. cancel()
  288. log.Info("shutdownHandler sent cancel signal...")
  289. }
  290. // Unregister to get default OS nuke behaviour in case we don't exit cleanly
  291. signal.Stop(sigs)
  292. }
  293. func getConfig(ctx context.Context, sm subnet.Manager) (*subnet.Config, error) {
  294. // Retry every second until it succeeds
  295. for {
  296. config, err := sm.GetNetworkConfig(ctx)
  297. if err != nil {
  298. log.Errorf("Couldn't fetch network config: %s", err)
  299. } else if config == nil {
  300. log.Warningf("Couldn't find network config: %s", err)
  301. } else {
  302. log.Infof("Found network config - Backend type: %s", config.BackendType)
  303. return config, nil
  304. }
  305. select {
  306. case <-ctx.Done():
  307. return nil, errCanceled
  308. case <-time.After(1 * time.Second):
  309. fmt.Println("timed out")
  310. }
  311. }
  312. }
  313. func MonitorLease(ctx context.Context, sm subnet.Manager, bn backend.Network, wg *sync.WaitGroup) error {
  314. // Use the subnet manager to start watching leases.
  315. evts := make(chan subnet.Event)
  316. wg.Add(1)
  317. go func() {
  318. subnet.WatchLease(ctx, sm, bn.Lease().Subnet, evts)
  319. wg.Done()
  320. }()
  321. renewMargin := time.Duration(opts.subnetLeaseRenewMargin) * time.Minute
  322. dur := bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  323. for {
  324. select {
  325. case <-time.After(dur):
  326. err := sm.RenewLease(ctx, bn.Lease())
  327. if err != nil {
  328. log.Error("Error renewing lease (trying again in 1 min): ", err)
  329. dur = time.Minute
  330. continue
  331. }
  332. log.Info("Lease renewed, new expiration: ", bn.Lease().Expiration)
  333. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  334. case e := <-evts:
  335. switch e.Type {
  336. case subnet.EventAdded:
  337. bn.Lease().Expiration = e.Lease.Expiration
  338. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  339. log.Infof("Waiting for %s to renew lease", dur)
  340. case subnet.EventRemoved:
  341. log.Error("Lease has been revoked. Shutting down daemon.")
  342. return errInterrupted
  343. }
  344. case <-ctx.Done():
  345. log.Infof("Stopped monitoring lease")
  346. return errCanceled
  347. }
  348. }
  349. }
  350. func LookupExtIface(ifname string, ifregex string) (*backend.ExternalInterface, error) {
  351. var iface *net.Interface
  352. var ifaceAddr net.IP
  353. var err error
  354. if len(ifname) > 0 {
  355. if ifaceAddr = net.ParseIP(ifname); ifaceAddr != nil {
  356. log.Infof("Searching for interface using %s", ifaceAddr)
  357. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  358. if err != nil {
  359. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  360. }
  361. } else {
  362. iface, err = net.InterfaceByName(ifname)
  363. if err != nil {
  364. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  365. }
  366. }
  367. } else if len(ifregex) > 0 {
  368. // Use the regex if specified and the iface option for matching a specific ip or name is not used
  369. ifaces, err := net.Interfaces()
  370. if err != nil {
  371. return nil, fmt.Errorf("error listing all interfaces: %s", err)
  372. }
  373. // Check IP
  374. for _, ifaceToMatch := range ifaces {
  375. ifaceIP, err := ip.GetIfaceIP4Addr(&ifaceToMatch)
  376. if err != nil {
  377. // Skip if there is no IPv4 address
  378. continue
  379. }
  380. matched, err := regexp.MatchString(ifregex, ifaceIP.String())
  381. if err != nil {
  382. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregex, ifaceIP.String())
  383. }
  384. if matched {
  385. ifaceAddr = ifaceIP
  386. iface = &ifaceToMatch
  387. break
  388. }
  389. }
  390. // Check Name
  391. if iface == nil && ifaceAddr == nil {
  392. for _, ifaceToMatch := range ifaces {
  393. matched, err := regexp.MatchString(ifregex, ifaceToMatch.Name)
  394. if err != nil {
  395. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregex, ifaceToMatch.Name)
  396. }
  397. if matched {
  398. iface = &ifaceToMatch
  399. break
  400. }
  401. }
  402. }
  403. // Check that nothing was matched
  404. if iface == nil {
  405. return nil, fmt.Errorf("Could not match pattern %s to any of the available network interfaces", ifregex)
  406. }
  407. } else {
  408. log.Info("Determining IP address of default interface")
  409. if iface, err = ip.GetDefaultGatewayIface(); err != nil {
  410. return nil, fmt.Errorf("failed to get default interface: %s", err)
  411. }
  412. }
  413. if ifaceAddr == nil {
  414. ifaceAddr, err = ip.GetIfaceIP4Addr(iface)
  415. if err != nil {
  416. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  417. }
  418. }
  419. log.Infof("Using interface with name %s and address %s", iface.Name, ifaceAddr)
  420. if iface.MTU == 0 {
  421. return nil, fmt.Errorf("failed to determine MTU for %s interface", ifaceAddr)
  422. }
  423. var extAddr net.IP
  424. if len(opts.publicIP) > 0 {
  425. extAddr = net.ParseIP(opts.publicIP)
  426. if extAddr == nil {
  427. return nil, fmt.Errorf("invalid public IP address: %s", opts.publicIP)
  428. }
  429. log.Infof("Using %s as external address", extAddr)
  430. }
  431. if extAddr == nil {
  432. log.Infof("Defaulting external address to interface address (%s)", ifaceAddr)
  433. extAddr = ifaceAddr
  434. }
  435. return &backend.ExternalInterface{
  436. Iface: iface,
  437. IfaceAddr: ifaceAddr,
  438. ExtAddr: extAddr,
  439. }, nil
  440. }
  441. func WriteSubnetFile(path string, nw ip.IP4Net, ipMasq bool, bn backend.Network) error {
  442. dir, name := filepath.Split(path)
  443. os.MkdirAll(dir, 0755)
  444. tempFile := filepath.Join(dir, "."+name)
  445. f, err := os.Create(tempFile)
  446. if err != nil {
  447. return err
  448. }
  449. // Write out the first usable IP by incrementing
  450. // sn.IP by one
  451. sn := bn.Lease().Subnet
  452. sn.IP += 1
  453. fmt.Fprintf(f, "FLANNEL_NETWORK=%s\n", nw)
  454. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn)
  455. fmt.Fprintf(f, "FLANNEL_MTU=%d\n", bn.MTU())
  456. _, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", ipMasq)
  457. f.Close()
  458. if err != nil {
  459. return err
  460. }
  461. // rename(2) the temporary file to the desired location so that it becomes
  462. // atomically visible with the contents
  463. return os.Rename(tempFile, path)
  464. //TODO - is this safe? What if it's not on the same FS?
  465. }
  466. func mustRunHealthz() {
  467. address := net.JoinHostPort(opts.healthzIP, strconv.Itoa(opts.healthzPort))
  468. log.Infof("Start healthz server on %s", address)
  469. http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  470. w.WriteHeader(http.StatusOK)
  471. w.Write([]byte("flanneld is running"))
  472. })
  473. if err := http.ListenAndServe(address, nil); err != nil {
  474. log.Errorf("Start healthz server error. %v", err)
  475. panic(err)
  476. }
  477. }
  478. func ReadSubnetFromSubnetFile(path string) ip.IP4Net {
  479. var prevSubnet ip.IP4Net
  480. if _, err := os.Stat(path); !os.IsNotExist(err) {
  481. prevSubnetVals, err := godotenv.Read(path)
  482. if err != nil {
  483. log.Errorf("Couldn't fetch previous subnet from subnet file at %s: %s", path, err)
  484. } else if prevSubnetString, ok := prevSubnetVals["FLANNEL_SUBNET"]; ok {
  485. err = prevSubnet.UnmarshalJSON([]byte(prevSubnetString))
  486. if err != nil {
  487. log.Errorf("Couldn't parse previous subnet from subnet file at %s: %s", path, err)
  488. }
  489. }
  490. }
  491. return prevSubnet
  492. }