main.go 19 KB

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