main.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. "math/big"
  20. "net"
  21. "net/http"
  22. "os"
  23. "os/signal"
  24. "path/filepath"
  25. "regexp"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "syscall"
  30. "time"
  31. "github.com/coreos/pkg/flagutil"
  32. "golang.org/x/net/context"
  33. "github.com/flannel-io/flannel/network"
  34. "github.com/flannel-io/flannel/pkg/ip"
  35. "github.com/flannel-io/flannel/subnet"
  36. "github.com/flannel-io/flannel/subnet/etcdv2"
  37. "github.com/flannel-io/flannel/subnet/kube"
  38. "github.com/flannel-io/flannel/version"
  39. log "k8s.io/klog"
  40. "github.com/joho/godotenv"
  41. // Backends need to be imported for their init() to get executed and them to register
  42. "github.com/coreos/go-systemd/daemon"
  43. "github.com/flannel-io/flannel/backend"
  44. _ "github.com/flannel-io/flannel/backend/alivpc"
  45. _ "github.com/flannel-io/flannel/backend/alloc"
  46. _ "github.com/flannel-io/flannel/backend/awsvpc"
  47. _ "github.com/flannel-io/flannel/backend/extension"
  48. _ "github.com/flannel-io/flannel/backend/gce"
  49. _ "github.com/flannel-io/flannel/backend/hostgw"
  50. _ "github.com/flannel-io/flannel/backend/ipip"
  51. _ "github.com/flannel-io/flannel/backend/ipsec"
  52. _ "github.com/flannel-io/flannel/backend/tencentvpc"
  53. _ "github.com/flannel-io/flannel/backend/udp"
  54. _ "github.com/flannel-io/flannel/backend/vxlan"
  55. )
  56. type flagSlice []string
  57. func (t *flagSlice) String() string {
  58. return fmt.Sprintf("%v", *t)
  59. }
  60. func (t *flagSlice) Set(val string) error {
  61. *t = append(*t, val)
  62. return nil
  63. }
  64. type CmdLineOpts struct {
  65. etcdEndpoints string
  66. etcdPrefix string
  67. etcdKeyfile string
  68. etcdCertfile string
  69. etcdCAFile string
  70. etcdUsername string
  71. etcdPassword string
  72. help bool
  73. version bool
  74. autoDetectIPv4 bool
  75. autoDetectIPv6 bool
  76. kubeSubnetMgr bool
  77. kubeApiUrl string
  78. kubeAnnotationPrefix string
  79. kubeConfigFile string
  80. iface flagSlice
  81. ifaceRegex flagSlice
  82. ipMasq bool
  83. subnetFile string
  84. subnetDir string
  85. publicIP string
  86. publicIPv6 string
  87. subnetLeaseRenewMargin int
  88. healthzIP string
  89. healthzPort int
  90. charonExecutablePath string
  91. charonViciUri string
  92. iptablesResyncSeconds int
  93. iptablesForwardRules bool
  94. netConfPath string
  95. setNodeNetworkUnavailable bool
  96. }
  97. var (
  98. opts CmdLineOpts
  99. errInterrupted = errors.New("interrupted")
  100. errCanceled = errors.New("canceled")
  101. flannelFlags = flag.NewFlagSet("flannel", flag.ExitOnError)
  102. )
  103. const (
  104. ipv4Stack int = iota
  105. ipv6Stack
  106. dualStack
  107. noneStack
  108. )
  109. func init() {
  110. 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")
  111. flannelFlags.StringVar(&opts.etcdPrefix, "etcd-prefix", "/coreos.com/network", "etcd prefix")
  112. flannelFlags.StringVar(&opts.etcdKeyfile, "etcd-keyfile", "", "SSL key file used to secure etcd communication")
  113. flannelFlags.StringVar(&opts.etcdCertfile, "etcd-certfile", "", "SSL certification file used to secure etcd communication")
  114. flannelFlags.StringVar(&opts.etcdCAFile, "etcd-cafile", "", "SSL Certificate Authority file used to secure etcd communication")
  115. flannelFlags.StringVar(&opts.etcdUsername, "etcd-username", "", "username for BasicAuth to etcd")
  116. flannelFlags.StringVar(&opts.etcdPassword, "etcd-password", "", "password for BasicAuth to etcd")
  117. 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.")
  118. 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.")
  119. flannelFlags.StringVar(&opts.subnetFile, "subnet-file", "/run/flannel/subnet.env", "filename where env variables (subnet, MTU, ... ) will be written to")
  120. flannelFlags.StringVar(&opts.publicIP, "public-ip", "", "IP accessible by other nodes for inter-host communication")
  121. flannelFlags.StringVar(&opts.publicIPv6, "public-ipv6", "", "IPv6 accessible by other nodes for inter-host communication")
  122. flannelFlags.IntVar(&opts.subnetLeaseRenewMargin, "subnet-lease-renew-margin", 60, "subnet lease renewal margin, in minutes, ranging from 1 to 1439")
  123. flannelFlags.BoolVar(&opts.ipMasq, "ip-masq", false, "setup IP masquerade rule for traffic destined outside of overlay network")
  124. flannelFlags.BoolVar(&opts.autoDetectIPv4, "auto-detect-ipv4", true, "auto detect ipv4 address of the iface")
  125. flannelFlags.BoolVar(&opts.autoDetectIPv6, "auto-detect-ipv6", false, "auto detect ipv6 address of the iface")
  126. flannelFlags.BoolVar(&opts.kubeSubnetMgr, "kube-subnet-mgr", false, "contact the Kubernetes API for subnet assignment instead of etcd.")
  127. flannelFlags.StringVar(&opts.kubeApiUrl, "kube-api-url", "", "Kubernetes API server URL. Does not need to be specified if flannel is running in a pod.")
  128. 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.`)
  129. flannelFlags.StringVar(&opts.kubeConfigFile, "kubeconfig-file", "", "kubeconfig file location. Does not need to be specified if flannel is running in a pod.")
  130. flannelFlags.BoolVar(&opts.version, "version", false, "print version and exit")
  131. flannelFlags.StringVar(&opts.healthzIP, "healthz-ip", "0.0.0.0", "the IP address for healthz server to listen")
  132. flannelFlags.IntVar(&opts.healthzPort, "healthz-port", 0, "the port for healthz server to listen(0 to disable)")
  133. flannelFlags.IntVar(&opts.iptablesResyncSeconds, "iptables-resync", 5, "resync period for iptables rules, in seconds")
  134. flannelFlags.BoolVar(&opts.iptablesForwardRules, "iptables-forward-rules", true, "add default accept rules to FORWARD chain in iptables")
  135. flannelFlags.StringVar(&opts.netConfPath, "net-config-path", "/etc/kube-flannel/net-conf.json", "path to the network configuration file")
  136. flannelFlags.BoolVar(&opts.setNodeNetworkUnavailable, "set-node-network-unavailable", true, "set NodeNetworkUnavailable after ready")
  137. log.InitFlags(nil)
  138. // klog will log to tmp files by default. override so all entries
  139. // can flow into journald (if running under systemd)
  140. flag.Set("logtostderr", "true")
  141. // Only copy the non file logging options from klog
  142. copyFlag("v")
  143. copyFlag("vmodule")
  144. copyFlag("log_backtrace_at")
  145. // Define the usage function
  146. flannelFlags.Usage = usage
  147. // now parse command line args
  148. flannelFlags.Parse(os.Args[1:])
  149. }
  150. func copyFlag(name string) {
  151. flannelFlags.Var(flag.Lookup(name).Value, flag.Lookup(name).Name, flag.Lookup(name).Usage)
  152. }
  153. func usage() {
  154. fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
  155. flannelFlags.PrintDefaults()
  156. os.Exit(0)
  157. }
  158. func getIPFamily(autoDetectIPv4, autoDetectIPv6 bool) (int, error) {
  159. if autoDetectIPv4 && !autoDetectIPv6 {
  160. return ipv4Stack, nil
  161. } else if !autoDetectIPv4 && autoDetectIPv6 {
  162. return ipv6Stack, nil
  163. } else if autoDetectIPv4 && autoDetectIPv6 {
  164. return dualStack, nil
  165. }
  166. return noneStack, errors.New("none defined stack")
  167. }
  168. func newSubnetManager(ctx context.Context) (subnet.Manager, error) {
  169. if opts.kubeSubnetMgr {
  170. return kube.NewSubnetManager(ctx, opts.kubeApiUrl, opts.kubeConfigFile, opts.kubeAnnotationPrefix, opts.netConfPath, opts.setNodeNetworkUnavailable)
  171. }
  172. cfg := &etcdv2.EtcdConfig{
  173. Endpoints: strings.Split(opts.etcdEndpoints, ","),
  174. Keyfile: opts.etcdKeyfile,
  175. Certfile: opts.etcdCertfile,
  176. CAFile: opts.etcdCAFile,
  177. Prefix: opts.etcdPrefix,
  178. Username: opts.etcdUsername,
  179. Password: opts.etcdPassword,
  180. }
  181. // Attempt to renew the lease for the subnet specified in the subnetFile
  182. prevSubnet := ReadCIDRFromSubnetFile(opts.subnetFile, "FLANNEL_SUBNET")
  183. return etcdv2.NewLocalManager(cfg, prevSubnet)
  184. }
  185. func main() {
  186. if opts.version {
  187. fmt.Fprintln(os.Stderr, version.Version)
  188. os.Exit(0)
  189. }
  190. flagutil.SetFlagsFromEnv(flannelFlags, "FLANNELD")
  191. // Log the config set via CLI flags
  192. log.Infof("CLI flags config: %+v", opts)
  193. // Validate flags
  194. if opts.subnetLeaseRenewMargin >= 24*60 || opts.subnetLeaseRenewMargin <= 0 {
  195. log.Error("Invalid subnet-lease-renew-margin option, out of acceptable range")
  196. os.Exit(1)
  197. }
  198. // Get ip family stack
  199. ipStack, stackErr := getIPFamily(opts.autoDetectIPv4, opts.autoDetectIPv6)
  200. if stackErr != nil {
  201. log.Error(stackErr.Error())
  202. os.Exit(1)
  203. }
  204. // Work out which interface to use
  205. var extIface *backend.ExternalInterface
  206. var err error
  207. // Check the default interface only if no interfaces are specified
  208. if len(opts.iface) == 0 && len(opts.ifaceRegex) == 0 {
  209. extIface, err = LookupExtIface(opts.publicIP, "", ipStack)
  210. if err != nil {
  211. log.Error("Failed to find any valid interface to use: ", err)
  212. os.Exit(1)
  213. }
  214. } else {
  215. // Check explicitly specified interfaces
  216. for _, iface := range opts.iface {
  217. extIface, err = LookupExtIface(iface, "", ipStack)
  218. if err != nil {
  219. log.Infof("Could not find valid interface matching %s: %s", iface, err)
  220. }
  221. if extIface != nil {
  222. break
  223. }
  224. }
  225. // Check interfaces that match any specified regexes
  226. if extIface == nil {
  227. for _, ifaceRegex := range opts.ifaceRegex {
  228. extIface, err = LookupExtIface("", ifaceRegex, ipStack)
  229. if err != nil {
  230. log.Infof("Could not find valid interface matching %s: %s", ifaceRegex, err)
  231. }
  232. if extIface != nil {
  233. break
  234. }
  235. }
  236. }
  237. if extIface == nil {
  238. // Exit if any of the specified interfaces do not match
  239. log.Error("Failed to find interface to use that matches the interfaces and/or regexes provided")
  240. os.Exit(1)
  241. }
  242. }
  243. // This is the main context that everything should run in.
  244. // All spawned goroutines should exit when cancel is called on this context.
  245. // Go routines spawned from main.go coordinate using a WaitGroup. This provides a mechanism to allow the shutdownHandler goroutine
  246. // to block until all the goroutines return . If those goroutines spawn other goroutines then they are responsible for
  247. // blocking and returning only when cancel() is called.
  248. ctx, cancel := context.WithCancel(context.Background())
  249. sm, err := newSubnetManager(ctx)
  250. if err != nil {
  251. log.Error("Failed to create SubnetManager: ", err)
  252. os.Exit(1)
  253. }
  254. log.Infof("Created subnet manager: %s", sm.Name())
  255. // Register for SIGINT and SIGTERM
  256. log.Info("Installing signal handlers")
  257. sigs := make(chan os.Signal, 1)
  258. signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
  259. wg := sync.WaitGroup{}
  260. wg.Add(1)
  261. go func() {
  262. shutdownHandler(ctx, sigs, cancel)
  263. wg.Done()
  264. }()
  265. if opts.healthzPort > 0 {
  266. // It's not super easy to shutdown the HTTP server so don't attempt to stop it cleanly
  267. go mustRunHealthz()
  268. }
  269. // Fetch the network config (i.e. what backend to use etc..).
  270. config, err := getConfig(ctx, sm)
  271. if err == errCanceled {
  272. wg.Wait()
  273. os.Exit(0)
  274. }
  275. // Create a backend manager then use it to create the backend and register the network with it.
  276. bm := backend.NewManager(ctx, sm, extIface)
  277. be, err := bm.GetBackend(config.BackendType)
  278. if err != nil {
  279. log.Errorf("Error fetching backend: %s", err)
  280. cancel()
  281. wg.Wait()
  282. os.Exit(1)
  283. }
  284. bn, err := be.RegisterNetwork(ctx, &wg, config)
  285. if err != nil {
  286. log.Errorf("Error registering network: %s", err)
  287. cancel()
  288. wg.Wait()
  289. os.Exit(1)
  290. }
  291. // Set up ipMasq if needed
  292. if opts.ipMasq {
  293. if config.EnableIPv4 {
  294. if err = recycleIPTables(config.Network, bn.Lease()); err != nil {
  295. log.Errorf("Failed to recycle IPTables rules, %v", err)
  296. cancel()
  297. wg.Wait()
  298. os.Exit(1)
  299. }
  300. log.Infof("Setting up masking rules")
  301. go network.SetupAndEnsureIPTables(network.MasqRules(config.Network, bn.Lease()), opts.iptablesResyncSeconds)
  302. }
  303. if config.EnableIPv6 {
  304. if err = recycleIP6Tables(config.IPv6Network, bn.Lease()); err != nil {
  305. log.Errorf("Failed to recycle IP6Tables rules, %v", err)
  306. cancel()
  307. wg.Wait()
  308. os.Exit(1)
  309. }
  310. log.Infof("Setting up masking ip6 rules")
  311. go network.SetupAndEnsureIP6Tables(network.MasqIP6Rules(config.IPv6Network, bn.Lease()), opts.iptablesResyncSeconds)
  312. }
  313. }
  314. // 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)
  315. // In Docker 1.12 and earlier, the default FORWARD chain policy was ACCEPT.
  316. // In Docker 1.13 and later, Docker sets the default policy of the FORWARD chain to DROP.
  317. if opts.iptablesForwardRules {
  318. if config.EnableIPv4 {
  319. log.Infof("Changing default FORWARD chain policy to ACCEPT")
  320. go network.SetupAndEnsureIPTables(network.ForwardRules(config.Network.String()), opts.iptablesResyncSeconds)
  321. }
  322. if config.EnableIPv6 {
  323. log.Infof("IPv6: Changing default FORWARD chain policy to ACCEPT")
  324. go network.SetupAndEnsureIP6Tables(network.ForwardRules(config.IPv6Network.String()), opts.iptablesResyncSeconds)
  325. }
  326. }
  327. if err := WriteSubnetFile(opts.subnetFile, config, opts.ipMasq, bn); err != nil {
  328. // Continue, even though it failed.
  329. log.Warningf("Failed to write subnet file: %s", err)
  330. } else {
  331. log.Infof("Wrote subnet file to %s", opts.subnetFile)
  332. }
  333. // Start "Running" the backend network. This will block until the context is done so run in another goroutine.
  334. log.Info("Running backend.")
  335. wg.Add(1)
  336. go func() {
  337. bn.Run(ctx)
  338. wg.Done()
  339. }()
  340. daemon.SdNotify(false, "READY=1")
  341. // Kube subnet mgr doesn't lease the subnet for this node - it just uses the podCidr that's already assigned.
  342. if !opts.kubeSubnetMgr {
  343. err = MonitorLease(ctx, sm, bn, &wg)
  344. if err == errInterrupted {
  345. // The lease was "revoked" - shut everything down
  346. cancel()
  347. }
  348. }
  349. log.Info("Waiting for all goroutines to exit")
  350. // Block waiting for all the goroutines to finish.
  351. wg.Wait()
  352. log.Info("Exiting cleanly...")
  353. os.Exit(0)
  354. }
  355. func recycleIPTables(nw ip.IP4Net, lease *subnet.Lease) error {
  356. prevNetwork := ReadCIDRFromSubnetFile(opts.subnetFile, "FLANNEL_NETWORK")
  357. prevSubnet := ReadCIDRFromSubnetFile(opts.subnetFile, "FLANNEL_SUBNET")
  358. // recycle iptables rules only when network configured or subnet leased is not equal to current one.
  359. if prevNetwork != nw && prevSubnet != lease.Subnet {
  360. 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)
  361. lease := &subnet.Lease{
  362. Subnet: prevSubnet,
  363. }
  364. if err := network.DeleteIPTables(network.MasqRules(prevNetwork, lease)); err != nil {
  365. return err
  366. }
  367. }
  368. return nil
  369. }
  370. func recycleIP6Tables(nw ip.IP6Net, lease *subnet.Lease) error {
  371. prevNetwork := ReadIP6CIDRFromSubnetFile(opts.subnetFile, "FLANNEL_IPV6_NETWORK")
  372. prevSubnet := ReadIP6CIDRFromSubnetFile(opts.subnetFile, "FLANNEL_IPV6_SUBNET")
  373. // recycle iptables rules only when network configured or subnet leased is not equal to current one.
  374. if prevNetwork.String() != nw.String() && prevSubnet.String() != lease.IPv6Subnet.String() {
  375. log.Infof("Current ipv6 network or subnet (%v, %v) is not equal to previous one (%v, %v), trying to recycle old ip6tables rules", nw, lease.IPv6Subnet, prevNetwork, prevSubnet)
  376. lease := &subnet.Lease{
  377. IPv6Subnet: prevSubnet,
  378. }
  379. if err := network.DeleteIP6Tables(network.MasqIP6Rules(prevNetwork, lease)); err != nil {
  380. return err
  381. }
  382. }
  383. return nil
  384. }
  385. func shutdownHandler(ctx context.Context, sigs chan os.Signal, cancel context.CancelFunc) {
  386. // Wait for the context do be Done or for the signal to come in to shutdown.
  387. select {
  388. case <-ctx.Done():
  389. log.Info("Stopping shutdownHandler...")
  390. case <-sigs:
  391. // Call cancel on the context to close everything down.
  392. cancel()
  393. log.Info("shutdownHandler sent cancel signal...")
  394. }
  395. // Unregister to get default OS nuke behaviour in case we don't exit cleanly
  396. signal.Stop(sigs)
  397. }
  398. func getConfig(ctx context.Context, sm subnet.Manager) (*subnet.Config, error) {
  399. // Retry every second until it succeeds
  400. for {
  401. config, err := sm.GetNetworkConfig(ctx)
  402. if err != nil {
  403. log.Errorf("Couldn't fetch network config: %s", err)
  404. } else if config == nil {
  405. log.Warningf("Couldn't find network config: %s", err)
  406. } else {
  407. log.Infof("Found network config - Backend type: %s", config.BackendType)
  408. return config, nil
  409. }
  410. select {
  411. case <-ctx.Done():
  412. return nil, errCanceled
  413. case <-time.After(1 * time.Second):
  414. fmt.Println("timed out")
  415. }
  416. }
  417. }
  418. func MonitorLease(ctx context.Context, sm subnet.Manager, bn backend.Network, wg *sync.WaitGroup) error {
  419. // Use the subnet manager to start watching leases.
  420. evts := make(chan subnet.Event)
  421. wg.Add(1)
  422. go func() {
  423. subnet.WatchLease(ctx, sm, bn.Lease().Subnet, evts)
  424. wg.Done()
  425. }()
  426. renewMargin := time.Duration(opts.subnetLeaseRenewMargin) * time.Minute
  427. dur := bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  428. for {
  429. select {
  430. case <-time.After(dur):
  431. err := sm.RenewLease(ctx, bn.Lease())
  432. if err != nil {
  433. log.Error("Error renewing lease (trying again in 1 min): ", err)
  434. dur = time.Minute
  435. continue
  436. }
  437. log.Info("Lease renewed, new expiration: ", bn.Lease().Expiration)
  438. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  439. case e, ok := <-evts:
  440. if !ok {
  441. log.Infof("Stopped monitoring lease")
  442. return errCanceled
  443. }
  444. switch e.Type {
  445. case subnet.EventAdded:
  446. bn.Lease().Expiration = e.Lease.Expiration
  447. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  448. log.Infof("Waiting for %s to renew lease", dur)
  449. case subnet.EventRemoved:
  450. log.Error("Lease has been revoked. Shutting down daemon.")
  451. return errInterrupted
  452. }
  453. }
  454. }
  455. }
  456. func LookupExtIface(ifname string, ifregex string, ipStack int) (*backend.ExternalInterface, error) {
  457. var iface *net.Interface
  458. var ifaceAddr net.IP
  459. var ifaceV6Addr net.IP
  460. var err error
  461. // Check ip family stack
  462. if ipStack == noneStack {
  463. return nil, fmt.Errorf("none matched ip stack")
  464. }
  465. if len(ifname) > 0 {
  466. if ifaceAddr = net.ParseIP(ifname); ifaceAddr != nil {
  467. log.Infof("Searching for interface using %s", ifaceAddr)
  468. switch ipStack {
  469. case ipv4Stack:
  470. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  471. if err != nil {
  472. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  473. }
  474. case ipv6Stack:
  475. iface, err = ip.GetInterfaceByIP6(ifaceAddr)
  476. if err != nil {
  477. return nil, fmt.Errorf("error looking up v6 interface %s: %s", ifname, err)
  478. }
  479. case dualStack:
  480. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  481. if err != nil {
  482. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  483. }
  484. v6Iface, err := ip.GetInterfaceByIP6(ifaceAddr)
  485. if err != nil {
  486. return nil, fmt.Errorf("error looking up v6 interface %s: %s", ifname, err)
  487. }
  488. if iface.Name != v6Iface.Name {
  489. return nil, fmt.Errorf("v6 interface %s must be the same with v4 interface %s", v6Iface.Name, iface.Name)
  490. }
  491. }
  492. } else {
  493. iface, err = net.InterfaceByName(ifname)
  494. if err != nil {
  495. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  496. }
  497. }
  498. } else if len(ifregex) > 0 {
  499. // Use the regex if specified and the iface option for matching a specific ip or name is not used
  500. ifaces, err := net.Interfaces()
  501. if err != nil {
  502. return nil, fmt.Errorf("error listing all interfaces: %s", err)
  503. }
  504. // Check IP
  505. for _, ifaceToMatch := range ifaces {
  506. switch ipStack {
  507. case ipv4Stack:
  508. ifaceIP, err := ip.GetInterfaceIP4Addr(&ifaceToMatch)
  509. if err != nil {
  510. // Skip if there is no IPv4 address
  511. continue
  512. }
  513. matched, err := regexp.MatchString(ifregex, ifaceIP.String())
  514. if err != nil {
  515. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregex, ifaceIP.String())
  516. }
  517. if matched {
  518. ifaceAddr = ifaceIP
  519. iface = &ifaceToMatch
  520. break
  521. }
  522. case ipv6Stack:
  523. ifaceIP, err := ip.GetInterfaceIP6Addr(&ifaceToMatch)
  524. if err != nil {
  525. // Skip if there is no IPv6 address
  526. continue
  527. }
  528. matched, err := regexp.MatchString(ifregex, ifaceIP.String())
  529. if err != nil {
  530. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregex, ifaceIP.String())
  531. }
  532. if matched {
  533. ifaceV6Addr = ifaceIP
  534. iface = &ifaceToMatch
  535. break
  536. }
  537. case dualStack:
  538. ifaceIP, err := ip.GetInterfaceIP4Addr(&ifaceToMatch)
  539. if err != nil {
  540. // Skip if there is no IPv4 address
  541. continue
  542. }
  543. matched, err := regexp.MatchString(ifregex, ifaceIP.String())
  544. if err != nil {
  545. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregex, ifaceIP.String())
  546. }
  547. ifaceV6IP, err := ip.GetInterfaceIP6Addr(&ifaceToMatch)
  548. if err != nil {
  549. // Skip if there is no IPv6 address
  550. continue
  551. }
  552. v6Matched, err := regexp.MatchString(ifregex, ifaceV6IP.String())
  553. if err != nil {
  554. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregex, ifaceIP.String())
  555. }
  556. if matched && v6Matched {
  557. ifaceAddr = ifaceIP
  558. ifaceV6Addr = ifaceV6IP
  559. iface = &ifaceToMatch
  560. break
  561. }
  562. }
  563. }
  564. // Check Name
  565. if iface == nil && (ifaceAddr == nil || ifaceV6Addr == nil) {
  566. for _, ifaceToMatch := range ifaces {
  567. matched, err := regexp.MatchString(ifregex, ifaceToMatch.Name)
  568. if err != nil {
  569. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregex, ifaceToMatch.Name)
  570. }
  571. if matched {
  572. iface = &ifaceToMatch
  573. break
  574. }
  575. }
  576. }
  577. // Check that nothing was matched
  578. if iface == nil {
  579. var availableFaces []string
  580. for _, f := range ifaces {
  581. var ipaddr net.IP
  582. switch ipStack {
  583. case ipv4Stack, dualStack:
  584. ipaddr, _ = ip.GetInterfaceIP4Addr(&f) // We can safely ignore errors. We just won't log any ip
  585. case ipv6Stack:
  586. ipaddr, _ = ip.GetInterfaceIP6Addr(&f) // We can safely ignore errors. We just won't log any ip
  587. }
  588. availableFaces = append(availableFaces, fmt.Sprintf("%s:%s", f.Name, ipaddr))
  589. }
  590. return nil, fmt.Errorf("Could not match pattern %s to any of the available network interfaces (%s)", ifregex, strings.Join(availableFaces, ", "))
  591. }
  592. } else {
  593. log.Info("Determining IP address of default interface")
  594. switch ipStack {
  595. case ipv4Stack:
  596. if iface, err = ip.GetDefaultGatewayInterface(); err != nil {
  597. return nil, fmt.Errorf("failed to get default interface: %s", err)
  598. }
  599. case ipv6Stack:
  600. if iface, err = ip.GetDefaultV6GatewayInterface(); err != nil {
  601. return nil, fmt.Errorf("failed to get default v6 interface: %s", err)
  602. }
  603. case dualStack:
  604. if iface, err = ip.GetDefaultGatewayInterface(); err != nil {
  605. return nil, fmt.Errorf("failed to get default interface: %s", err)
  606. }
  607. v6Iface, err := ip.GetDefaultV6GatewayInterface()
  608. if err != nil {
  609. return nil, fmt.Errorf("failed to get default v6 interface: %s", err)
  610. }
  611. if iface.Name != v6Iface.Name {
  612. return nil, fmt.Errorf("v6 default route interface %s "+
  613. "must be the same with v4 default route interface %s", v6Iface.Name, iface.Name)
  614. }
  615. }
  616. }
  617. if ipStack == ipv4Stack && ifaceAddr == nil {
  618. ifaceAddr, err = ip.GetInterfaceIP4Addr(iface)
  619. if err != nil {
  620. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  621. }
  622. } else if ipStack == ipv6Stack && ifaceV6Addr == nil {
  623. ifaceV6Addr, err = ip.GetInterfaceIP6Addr(iface)
  624. if err != nil {
  625. return nil, fmt.Errorf("failed to find IPv6 address for interface %s", iface.Name)
  626. }
  627. } else if ipStack == dualStack && ifaceAddr == nil && ifaceV6Addr == nil {
  628. ifaceAddr, err = ip.GetInterfaceIP4Addr(iface)
  629. if err != nil {
  630. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  631. }
  632. ifaceV6Addr, err = ip.GetInterfaceIP6Addr(iface)
  633. if err != nil {
  634. return nil, fmt.Errorf("failed to find IPv6 address for interface %s", iface.Name)
  635. }
  636. }
  637. if ifaceAddr != nil {
  638. log.Infof("Using interface with name %s and address %s", iface.Name, ifaceAddr)
  639. }
  640. if ifaceV6Addr != nil {
  641. log.Infof("Using interface with name %s and v6 address %s", iface.Name, ifaceV6Addr)
  642. }
  643. if iface.MTU == 0 {
  644. return nil, fmt.Errorf("failed to determine MTU for %s interface", ifaceAddr)
  645. }
  646. var extAddr net.IP
  647. var extV6Addr net.IP
  648. if len(opts.publicIP) > 0 {
  649. extAddr = net.ParseIP(opts.publicIP)
  650. if extAddr == nil {
  651. return nil, fmt.Errorf("invalid public IP address: %s", opts.publicIP)
  652. }
  653. log.Infof("Using %s as external address", extAddr)
  654. }
  655. if extAddr == nil {
  656. log.Infof("Defaulting external address to interface address (%s)", ifaceAddr)
  657. extAddr = ifaceAddr
  658. }
  659. if len(opts.publicIPv6) > 0 {
  660. extV6Addr = net.ParseIP(opts.publicIPv6)
  661. if extV6Addr == nil {
  662. return nil, fmt.Errorf("invalid public IPv6 address: %s", opts.publicIPv6)
  663. }
  664. log.Infof("Using %s as external address", extV6Addr)
  665. }
  666. if extV6Addr == nil {
  667. log.Infof("Defaulting external v6 address to interface address (%s)", ifaceV6Addr)
  668. extV6Addr = ifaceV6Addr
  669. }
  670. return &backend.ExternalInterface{
  671. Iface: iface,
  672. IfaceAddr: ifaceAddr,
  673. IfaceV6Addr: ifaceV6Addr,
  674. ExtAddr: extAddr,
  675. ExtV6Addr: extV6Addr,
  676. }, nil
  677. }
  678. func WriteSubnetFile(path string, config *subnet.Config, ipMasq bool, bn backend.Network) error {
  679. dir, name := filepath.Split(path)
  680. os.MkdirAll(dir, 0755)
  681. tempFile := filepath.Join(dir, "."+name)
  682. f, err := os.Create(tempFile)
  683. if err != nil {
  684. return err
  685. }
  686. if config.EnableIPv4 {
  687. nw := config.Network
  688. // Write out the first usable IP by incrementing
  689. // sn.IP by one
  690. sn := bn.Lease().Subnet
  691. sn.IP += 1
  692. fmt.Fprintf(f, "FLANNEL_NETWORK=%s\n", nw)
  693. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn)
  694. }
  695. if config.EnableIPv6 {
  696. ip6Nw := config.IPv6Network
  697. ip6Sn := bn.Lease().IPv6Subnet
  698. ip6Sn.IP = (*ip.IP6)(big.NewInt(0).Add((*big.Int)(ip6Sn.IP), big.NewInt(1)))
  699. fmt.Fprintf(f, "FLANNEL_IPV6_NETWORK=%s\n", ip6Nw)
  700. fmt.Fprintf(f, "FLANNEL_IPV6_SUBNET=%s\n", ip6Sn)
  701. }
  702. fmt.Fprintf(f, "FLANNEL_MTU=%d\n", bn.MTU())
  703. _, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", ipMasq)
  704. f.Close()
  705. if err != nil {
  706. return err
  707. }
  708. // rename(2) the temporary file to the desired location so that it becomes
  709. // atomically visible with the contents
  710. return os.Rename(tempFile, path)
  711. //TODO - is this safe? What if it's not on the same FS?
  712. }
  713. func mustRunHealthz() {
  714. address := net.JoinHostPort(opts.healthzIP, strconv.Itoa(opts.healthzPort))
  715. log.Infof("Start healthz server on %s", address)
  716. http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  717. w.WriteHeader(http.StatusOK)
  718. w.Write([]byte("flanneld is running"))
  719. })
  720. if err := http.ListenAndServe(address, nil); err != nil {
  721. log.Errorf("Start healthz server error. %v", err)
  722. panic(err)
  723. }
  724. }
  725. func ReadCIDRFromSubnetFile(path string, CIDRKey string) ip.IP4Net {
  726. var prevCIDR ip.IP4Net
  727. if _, err := os.Stat(path); !os.IsNotExist(err) {
  728. prevSubnetVals, err := godotenv.Read(path)
  729. if err != nil {
  730. log.Errorf("Couldn't fetch previous %s from subnet file at %s: %s", CIDRKey, path, err)
  731. } else if prevCIDRString, ok := prevSubnetVals[CIDRKey]; ok {
  732. err = prevCIDR.UnmarshalJSON([]byte(prevCIDRString))
  733. if err != nil {
  734. log.Errorf("Couldn't parse previous %s from subnet file at %s: %s", CIDRKey, path, err)
  735. }
  736. }
  737. }
  738. return prevCIDR
  739. }
  740. func ReadIP6CIDRFromSubnetFile(path string, CIDRKey string) ip.IP6Net {
  741. var prevCIDR ip.IP6Net
  742. if _, err := os.Stat(path); !os.IsNotExist(err) {
  743. prevSubnetVals, err := godotenv.Read(path)
  744. if err != nil {
  745. log.Errorf("Couldn't fetch previous %s from subnet file at %s: %s", CIDRKey, path, err)
  746. } else if prevCIDRString, ok := prevSubnetVals[CIDRKey]; ok {
  747. err = prevCIDR.UnmarshalJSON([]byte(prevCIDRString))
  748. if err != nil {
  749. log.Errorf("Couldn't parse previous %s from subnet file at %s: %s", CIDRKey, path, err)
  750. }
  751. }
  752. }
  753. return prevCIDR
  754. }