main.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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.kubeSubnetMgr, "kube-subnet-mgr", false, "contact the Kubernetes API for subnet assignment instead of etcd.")
  125. flannelFlags.StringVar(&opts.kubeApiUrl, "kube-api-url", "", "Kubernetes API server URL. Does not need to be specified if flannel is running in a pod.")
  126. 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.`)
  127. flannelFlags.StringVar(&opts.kubeConfigFile, "kubeconfig-file", "", "kubeconfig file location. Does not need to be specified if flannel is running in a pod.")
  128. flannelFlags.BoolVar(&opts.version, "version", false, "print version and exit")
  129. flannelFlags.StringVar(&opts.healthzIP, "healthz-ip", "0.0.0.0", "the IP address for healthz server to listen")
  130. flannelFlags.IntVar(&opts.healthzPort, "healthz-port", 0, "the port for healthz server to listen(0 to disable)")
  131. flannelFlags.IntVar(&opts.iptablesResyncSeconds, "iptables-resync", 5, "resync period for iptables rules, in seconds")
  132. flannelFlags.BoolVar(&opts.iptablesForwardRules, "iptables-forward-rules", true, "add default accept rules to FORWARD chain in iptables")
  133. flannelFlags.StringVar(&opts.netConfPath, "net-config-path", "/etc/kube-flannel/net-conf.json", "path to the network configuration file")
  134. flannelFlags.BoolVar(&opts.setNodeNetworkUnavailable, "set-node-network-unavailable", true, "set NodeNetworkUnavailable after ready")
  135. log.InitFlags(nil)
  136. // klog will log to tmp files by default. override so all entries
  137. // can flow into journald (if running under systemd)
  138. flag.Set("logtostderr", "true")
  139. // Only copy the non file logging options from klog
  140. copyFlag("v")
  141. copyFlag("vmodule")
  142. copyFlag("log_backtrace_at")
  143. // Define the usage function
  144. flannelFlags.Usage = usage
  145. // now parse command line args
  146. flannelFlags.Parse(os.Args[1:])
  147. }
  148. func copyFlag(name string) {
  149. flannelFlags.Var(flag.Lookup(name).Value, flag.Lookup(name).Name, flag.Lookup(name).Usage)
  150. }
  151. func usage() {
  152. fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
  153. flannelFlags.PrintDefaults()
  154. os.Exit(0)
  155. }
  156. func getIPFamily(autoDetectIPv4, autoDetectIPv6 bool) (int, error) {
  157. if autoDetectIPv4 && !autoDetectIPv6 {
  158. return ipv4Stack, nil
  159. } else if !autoDetectIPv4 && autoDetectIPv6 {
  160. return ipv6Stack, nil
  161. } else if autoDetectIPv4 && autoDetectIPv6 {
  162. return dualStack, nil
  163. }
  164. return noneStack, errors.New("none defined stack")
  165. }
  166. func newSubnetManager(ctx context.Context) (subnet.Manager, error) {
  167. if opts.kubeSubnetMgr {
  168. return kube.NewSubnetManager(ctx, opts.kubeApiUrl, opts.kubeConfigFile, opts.kubeAnnotationPrefix, opts.netConfPath, opts.setNodeNetworkUnavailable)
  169. }
  170. cfg := &etcdv2.EtcdConfig{
  171. Endpoints: strings.Split(opts.etcdEndpoints, ","),
  172. Keyfile: opts.etcdKeyfile,
  173. Certfile: opts.etcdCertfile,
  174. CAFile: opts.etcdCAFile,
  175. Prefix: opts.etcdPrefix,
  176. Username: opts.etcdUsername,
  177. Password: opts.etcdPassword,
  178. }
  179. // Attempt to renew the lease for the subnet specified in the subnetFile
  180. prevSubnet := ReadCIDRFromSubnetFile(opts.subnetFile, "FLANNEL_SUBNET")
  181. return etcdv2.NewLocalManager(cfg, prevSubnet)
  182. }
  183. func main() {
  184. if opts.version {
  185. fmt.Fprintln(os.Stderr, version.Version)
  186. os.Exit(0)
  187. }
  188. flagutil.SetFlagsFromEnv(flannelFlags, "FLANNELD")
  189. // Log the config set via CLI flags
  190. log.Infof("CLI flags config: %+v", opts)
  191. // Validate flags
  192. if opts.subnetLeaseRenewMargin >= 24*60 || opts.subnetLeaseRenewMargin <= 0 {
  193. log.Error("Invalid subnet-lease-renew-margin option, out of acceptable range")
  194. os.Exit(1)
  195. }
  196. // This is the main context that everything should run in.
  197. // All spawned goroutines should exit when cancel is called on this context.
  198. // Go routines spawned from main.go coordinate using a WaitGroup. This provides a mechanism to allow the shutdownHandler goroutine
  199. // to block until all the goroutines return . If those goroutines spawn other goroutines then they are responsible for
  200. // blocking and returning only when cancel() is called.
  201. ctx, cancel := context.WithCancel(context.Background())
  202. sm, err := newSubnetManager(ctx)
  203. if err != nil {
  204. log.Error("Failed to create SubnetManager: ", err)
  205. os.Exit(1)
  206. }
  207. log.Infof("Created subnet manager: %s", sm.Name())
  208. // Register for SIGINT and SIGTERM
  209. log.Info("Installing signal handlers")
  210. sigs := make(chan os.Signal, 1)
  211. signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
  212. wg := sync.WaitGroup{}
  213. wg.Add(1)
  214. go func() {
  215. shutdownHandler(ctx, sigs, cancel)
  216. wg.Done()
  217. }()
  218. if opts.healthzPort > 0 {
  219. // It's not super easy to shutdown the HTTP server so don't attempt to stop it cleanly
  220. go mustRunHealthz()
  221. }
  222. // Fetch the network config (i.e. what backend to use etc..).
  223. config, err := getConfig(ctx, sm)
  224. if err == errCanceled {
  225. wg.Wait()
  226. os.Exit(0)
  227. }
  228. // Get ip family stack
  229. ipStack, stackErr := getIPFamily(config.EnableIPv4, config.EnableIPv6)
  230. if stackErr != nil {
  231. log.Error(stackErr.Error())
  232. os.Exit(1)
  233. }
  234. // Work out which interface to use
  235. var extIface *backend.ExternalInterface
  236. // Check the default interface only if no interfaces are specified
  237. if len(opts.iface) == 0 && len(opts.ifaceRegex) == 0 {
  238. extIface, err = LookupExtIface(opts.publicIP, "", ipStack)
  239. if err != nil {
  240. log.Error("Failed to find any valid interface to use: ", err)
  241. os.Exit(1)
  242. }
  243. } else {
  244. // Check explicitly specified interfaces
  245. for _, iface := range opts.iface {
  246. extIface, err = LookupExtIface(iface, "", ipStack)
  247. if err != nil {
  248. log.Infof("Could not find valid interface matching %s: %s", iface, err)
  249. }
  250. if extIface != nil {
  251. break
  252. }
  253. }
  254. // Check interfaces that match any specified regexes
  255. if extIface == nil {
  256. for _, ifaceRegex := range opts.ifaceRegex {
  257. extIface, err = LookupExtIface("", ifaceRegex, ipStack)
  258. if err != nil {
  259. log.Infof("Could not find valid interface matching %s: %s", ifaceRegex, err)
  260. }
  261. if extIface != nil {
  262. break
  263. }
  264. }
  265. }
  266. if extIface == nil {
  267. // Exit if any of the specified interfaces do not match
  268. log.Error("Failed to find interface to use that matches the interfaces and/or regexes provided")
  269. os.Exit(1)
  270. }
  271. }
  272. // Create a backend manager then use it to create the backend and register the network with it.
  273. bm := backend.NewManager(ctx, sm, extIface)
  274. be, err := bm.GetBackend(config.BackendType)
  275. if err != nil {
  276. log.Errorf("Error fetching backend: %s", err)
  277. cancel()
  278. wg.Wait()
  279. os.Exit(1)
  280. }
  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. // Write out the first usable IP by incrementing
  673. // sn.IP by one
  674. sn := bn.Lease().Subnet
  675. sn.IP += 1
  676. fmt.Fprintf(f, "FLANNEL_NETWORK=%s\n", nw)
  677. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn)
  678. }
  679. if config.EnableIPv6 {
  680. ip6Nw := config.IPv6Network
  681. ip6Sn := bn.Lease().IPv6Subnet
  682. ip6Sn.IP = (*ip.IP6)(big.NewInt(0).Add((*big.Int)(ip6Sn.IP), big.NewInt(1)))
  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. }