main.go 20 KB

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