main.go 27 KB

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