main.go 18 KB

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