main.go 20 KB

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