main.go 17 KB

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