main.go 20 KB

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