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. bn, err := be.RegisterNetwork(ctx, &wg, config)
  281. if err != nil {
  282. log.Errorf("Error registering network: %s", err)
  283. cancel()
  284. wg.Wait()
  285. os.Exit(1)
  286. }
  287. // Set up ipMasq if needed
  288. if opts.ipMasq {
  289. if config.EnableIPv4 {
  290. if err = recycleIPTables(config.Network, bn.Lease()); err != nil {
  291. log.Errorf("Failed to recycle IPTables rules, %v", err)
  292. cancel()
  293. wg.Wait()
  294. os.Exit(1)
  295. }
  296. log.Infof("Setting up masking rules")
  297. go network.SetupAndEnsureIPTables(network.MasqRules(config.Network, bn.Lease()), opts.iptablesResyncSeconds)
  298. }
  299. if config.EnableIPv6 {
  300. if err = recycleIP6Tables(config.IPv6Network, bn.Lease()); err != nil {
  301. log.Errorf("Failed to recycle IP6Tables rules, %v", err)
  302. cancel()
  303. wg.Wait()
  304. os.Exit(1)
  305. }
  306. log.Infof("Setting up masking ip6 rules")
  307. go network.SetupAndEnsureIP6Tables(network.MasqIP6Rules(config.IPv6Network, bn.Lease()), opts.iptablesResyncSeconds)
  308. }
  309. }
  310. // 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)
  311. // In Docker 1.12 and earlier, the default FORWARD chain policy was ACCEPT.
  312. // In Docker 1.13 and later, Docker sets the default policy of the FORWARD chain to DROP.
  313. if opts.iptablesForwardRules {
  314. if config.EnableIPv4 {
  315. log.Infof("Changing default FORWARD chain policy to ACCEPT")
  316. go network.SetupAndEnsureIPTables(network.ForwardRules(config.Network.String()), opts.iptablesResyncSeconds)
  317. }
  318. if config.EnableIPv6 {
  319. log.Infof("IPv6: Changing default FORWARD chain policy to ACCEPT")
  320. go network.SetupAndEnsureIP6Tables(network.ForwardRules(config.IPv6Network.String()), opts.iptablesResyncSeconds)
  321. }
  322. }
  323. if err := WriteSubnetFile(opts.subnetFile, config, opts.ipMasq, bn); err != nil {
  324. // Continue, even though it failed.
  325. log.Warningf("Failed to write subnet file: %s", err)
  326. } else {
  327. log.Infof("Wrote subnet file to %s", opts.subnetFile)
  328. }
  329. // Start "Running" the backend network. This will block until the context is done so run in another goroutine.
  330. log.Info("Running backend.")
  331. wg.Add(1)
  332. go func() {
  333. bn.Run(ctx)
  334. wg.Done()
  335. }()
  336. daemon.SdNotify(false, "READY=1")
  337. // Kube subnet mgr doesn't lease the subnet for this node - it just uses the podCidr that's already assigned.
  338. if !opts.kubeSubnetMgr {
  339. err = MonitorLease(ctx, sm, bn, &wg)
  340. if err == errInterrupted {
  341. // The lease was "revoked" - shut everything down
  342. cancel()
  343. }
  344. }
  345. log.Info("Waiting for all goroutines to exit")
  346. // Block waiting for all the goroutines to finish.
  347. wg.Wait()
  348. log.Info("Exiting cleanly...")
  349. os.Exit(0)
  350. }
  351. func recycleIPTables(nw ip.IP4Net, lease *subnet.Lease) error {
  352. prevNetwork := ReadCIDRFromSubnetFile(opts.subnetFile, "FLANNEL_NETWORK")
  353. prevSubnet := ReadCIDRFromSubnetFile(opts.subnetFile, "FLANNEL_SUBNET")
  354. // recycle iptables rules only when network configured or subnet leased is not equal to current one.
  355. if prevNetwork != nw && prevSubnet != lease.Subnet {
  356. 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)
  357. lease := &subnet.Lease{
  358. Subnet: prevSubnet,
  359. }
  360. if err := network.DeleteIPTables(network.MasqRules(prevNetwork, lease)); err != nil {
  361. return err
  362. }
  363. }
  364. return nil
  365. }
  366. func recycleIP6Tables(nw ip.IP6Net, lease *subnet.Lease) error {
  367. prevNetwork := ReadIP6CIDRFromSubnetFile(opts.subnetFile, "FLANNEL_IPV6_NETWORK")
  368. prevSubnet := ReadIP6CIDRFromSubnetFile(opts.subnetFile, "FLANNEL_IPV6_SUBNET")
  369. // recycle iptables rules only when network configured or subnet leased is not equal to current one.
  370. if prevNetwork.String() != nw.String() && prevSubnet.String() != lease.IPv6Subnet.String() {
  371. 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)
  372. lease := &subnet.Lease{
  373. IPv6Subnet: prevSubnet,
  374. }
  375. if err := network.DeleteIP6Tables(network.MasqIP6Rules(prevNetwork, lease)); err != nil {
  376. return err
  377. }
  378. }
  379. return nil
  380. }
  381. func shutdownHandler(ctx context.Context, sigs chan os.Signal, cancel context.CancelFunc) {
  382. // Wait for the context do be Done or for the signal to come in to shutdown.
  383. select {
  384. case <-ctx.Done():
  385. log.Info("Stopping shutdownHandler...")
  386. case <-sigs:
  387. // Call cancel on the context to close everything down.
  388. cancel()
  389. log.Info("shutdownHandler sent cancel signal...")
  390. }
  391. // Unregister to get default OS nuke behaviour in case we don't exit cleanly
  392. signal.Stop(sigs)
  393. }
  394. func getConfig(ctx context.Context, sm subnet.Manager) (*subnet.Config, error) {
  395. // Retry every second until it succeeds
  396. for {
  397. config, err := sm.GetNetworkConfig(ctx)
  398. if err != nil {
  399. log.Errorf("Couldn't fetch network config: %s", err)
  400. } else if config == nil {
  401. log.Warningf("Couldn't find network config: %s", err)
  402. } else {
  403. log.Infof("Found network config - Backend type: %s", config.BackendType)
  404. return config, nil
  405. }
  406. select {
  407. case <-ctx.Done():
  408. return nil, errCanceled
  409. case <-time.After(1 * time.Second):
  410. fmt.Println("timed out")
  411. }
  412. }
  413. }
  414. func MonitorLease(ctx context.Context, sm subnet.Manager, bn backend.Network, wg *sync.WaitGroup) error {
  415. // Use the subnet manager to start watching leases.
  416. evts := make(chan subnet.Event)
  417. wg.Add(1)
  418. go func() {
  419. subnet.WatchLease(ctx, sm, bn.Lease().Subnet, evts)
  420. wg.Done()
  421. }()
  422. renewMargin := time.Duration(opts.subnetLeaseRenewMargin) * time.Minute
  423. dur := bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  424. for {
  425. select {
  426. case <-time.After(dur):
  427. err := sm.RenewLease(ctx, bn.Lease())
  428. if err != nil {
  429. log.Error("Error renewing lease (trying again in 1 min): ", err)
  430. dur = time.Minute
  431. continue
  432. }
  433. log.Info("Lease renewed, new expiration: ", bn.Lease().Expiration)
  434. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  435. case e, ok := <-evts:
  436. if !ok {
  437. log.Infof("Stopped monitoring lease")
  438. return errCanceled
  439. }
  440. switch e.Type {
  441. case subnet.EventAdded:
  442. bn.Lease().Expiration = e.Lease.Expiration
  443. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  444. log.Infof("Waiting for %s to renew lease", dur)
  445. case subnet.EventRemoved:
  446. log.Error("Lease has been revoked. Shutting down daemon.")
  447. return errInterrupted
  448. }
  449. }
  450. }
  451. }
  452. func LookupExtIface(ifname string, ifregexS string, ipStack int) (*backend.ExternalInterface, error) {
  453. var iface *net.Interface
  454. var ifaceAddr net.IP
  455. var ifaceV6Addr net.IP
  456. var err error
  457. var ifregex *regexp.Regexp
  458. if ifregexS != "" {
  459. ifregex, err = regexp.Compile(ifregexS)
  460. if err != nil {
  461. return nil, fmt.Errorf("could not compile the IP address regex '%s': %w", ifregexS, err)
  462. }
  463. }
  464. // Check ip family stack
  465. if ipStack == noneStack {
  466. return nil, fmt.Errorf("none matched ip stack")
  467. }
  468. if len(ifname) > 0 {
  469. if ifaceAddr = net.ParseIP(ifname); ifaceAddr != nil {
  470. log.Infof("Searching for interface using %s", ifaceAddr)
  471. switch ipStack {
  472. case ipv4Stack:
  473. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  474. if err != nil {
  475. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  476. }
  477. case ipv6Stack:
  478. iface, err = ip.GetInterfaceByIP6(ifaceAddr)
  479. if err != nil {
  480. return nil, fmt.Errorf("error looking up v6 interface %s: %s", ifname, err)
  481. }
  482. case dualStack:
  483. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  484. if err != nil {
  485. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  486. }
  487. v6Iface, err := ip.GetInterfaceByIP6(ifaceAddr)
  488. if err != nil {
  489. return nil, fmt.Errorf("error looking up v6 interface %s: %s", ifname, err)
  490. }
  491. if iface.Name != v6Iface.Name {
  492. return nil, fmt.Errorf("v6 interface %s must be the same with v4 interface %s", v6Iface.Name, iface.Name)
  493. }
  494. }
  495. } else {
  496. iface, err = net.InterfaceByName(ifname)
  497. if err != nil {
  498. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  499. }
  500. }
  501. } else if ifregex != nil {
  502. // Use the regex if specified and the iface option for matching a specific ip or name is not used
  503. ifaces, err := net.Interfaces()
  504. if err != nil {
  505. return nil, fmt.Errorf("error listing all interfaces: %s", err)
  506. }
  507. // Check IP
  508. for _, ifaceToMatch := range ifaces {
  509. switch ipStack {
  510. case ipv4Stack:
  511. ifaceIP, err := ip.GetInterfaceIP4Addr(&ifaceToMatch)
  512. if err != nil {
  513. // Skip if there is no IPv4 address
  514. continue
  515. }
  516. if ifregex.MatchString(ifaceIP.String()) {
  517. ifaceAddr = ifaceIP
  518. iface = &ifaceToMatch
  519. break
  520. }
  521. case ipv6Stack:
  522. ifaceIP, err := ip.GetInterfaceIP6Addr(&ifaceToMatch)
  523. if err != nil {
  524. // Skip if there is no IPv6 address
  525. continue
  526. }
  527. if ifregex.MatchString(ifaceIP.String()) {
  528. ifaceV6Addr = ifaceIP
  529. iface = &ifaceToMatch
  530. break
  531. }
  532. case dualStack:
  533. ifaceIP, err := ip.GetInterfaceIP4Addr(&ifaceToMatch)
  534. if err != nil {
  535. // Skip if there is no IPv4 address
  536. continue
  537. }
  538. ifaceV6IP, err := ip.GetInterfaceIP6Addr(&ifaceToMatch)
  539. if err != nil {
  540. // Skip if there is no IPv6 address
  541. continue
  542. }
  543. if ifregex.MatchString(ifaceIP.String()) && ifregex.MatchString(ifaceV6IP.String()) {
  544. ifaceAddr = ifaceIP
  545. ifaceV6Addr = ifaceV6IP
  546. iface = &ifaceToMatch
  547. break
  548. }
  549. }
  550. }
  551. // Check Name
  552. if iface == nil && (ifaceAddr == nil || ifaceV6Addr == nil) {
  553. for _, ifaceToMatch := range ifaces {
  554. if ifregex.MatchString(ifaceToMatch.Name) {
  555. iface = &ifaceToMatch
  556. break
  557. }
  558. }
  559. }
  560. // Check that nothing was matched
  561. if iface == nil {
  562. var availableFaces []string
  563. for _, f := range ifaces {
  564. var ipaddr net.IP
  565. switch ipStack {
  566. case ipv4Stack, dualStack:
  567. ipaddr, _ = ip.GetInterfaceIP4Addr(&f) // We can safely ignore errors. We just won't log any ip
  568. case ipv6Stack:
  569. ipaddr, _ = ip.GetInterfaceIP6Addr(&f) // We can safely ignore errors. We just won't log any ip
  570. }
  571. availableFaces = append(availableFaces, fmt.Sprintf("%s:%s", f.Name, ipaddr))
  572. }
  573. return nil, fmt.Errorf("Could not match pattern %s to any of the available network interfaces (%s)", ifregexS, strings.Join(availableFaces, ", "))
  574. }
  575. } else {
  576. log.Info("Determining IP address of default interface")
  577. switch ipStack {
  578. case ipv4Stack:
  579. if iface, err = ip.GetDefaultGatewayInterface(); err != nil {
  580. return nil, fmt.Errorf("failed to get default interface: %w", err)
  581. }
  582. case ipv6Stack:
  583. if iface, err = ip.GetDefaultV6GatewayInterface(); err != nil {
  584. return nil, fmt.Errorf("failed to get default v6 interface: %w", err)
  585. }
  586. case dualStack:
  587. if iface, err = ip.GetDefaultGatewayInterface(); err != nil {
  588. return nil, fmt.Errorf("failed to get default interface: %w", err)
  589. }
  590. v6Iface, err := ip.GetDefaultV6GatewayInterface()
  591. if err != nil {
  592. return nil, fmt.Errorf("failed to get default v6 interface: %w", err)
  593. }
  594. if iface.Name != v6Iface.Name {
  595. return nil, fmt.Errorf("v6 default route interface %s "+
  596. "must be the same with v4 default route interface %s", v6Iface.Name, iface.Name)
  597. }
  598. }
  599. }
  600. if ipStack == ipv4Stack && ifaceAddr == nil {
  601. ifaceAddr, err = ip.GetInterfaceIP4Addr(iface)
  602. if err != nil {
  603. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  604. }
  605. } else if ipStack == ipv6Stack && ifaceV6Addr == nil {
  606. ifaceV6Addr, err = ip.GetInterfaceIP6Addr(iface)
  607. if err != nil {
  608. return nil, fmt.Errorf("failed to find IPv6 address for interface %s", iface.Name)
  609. }
  610. } else if ipStack == dualStack && ifaceAddr == nil && ifaceV6Addr == nil {
  611. ifaceAddr, err = ip.GetInterfaceIP4Addr(iface)
  612. if err != nil {
  613. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  614. }
  615. ifaceV6Addr, err = ip.GetInterfaceIP6Addr(iface)
  616. if err != nil {
  617. return nil, fmt.Errorf("failed to find IPv6 address for interface %s", iface.Name)
  618. }
  619. }
  620. if ifaceAddr != nil {
  621. log.Infof("Using interface with name %s and address %s", iface.Name, ifaceAddr)
  622. }
  623. if ifaceV6Addr != nil {
  624. log.Infof("Using interface with name %s and v6 address %s", iface.Name, ifaceV6Addr)
  625. }
  626. if iface.MTU == 0 {
  627. return nil, fmt.Errorf("failed to determine MTU for %s interface", ifaceAddr)
  628. }
  629. var extAddr net.IP
  630. var extV6Addr net.IP
  631. if len(opts.publicIP) > 0 {
  632. extAddr = net.ParseIP(opts.publicIP)
  633. if extAddr == nil {
  634. return nil, fmt.Errorf("invalid public IP address: %s", opts.publicIP)
  635. }
  636. log.Infof("Using %s as external address", extAddr)
  637. }
  638. if extAddr == nil {
  639. log.Infof("Defaulting external address to interface address (%s)", ifaceAddr)
  640. extAddr = ifaceAddr
  641. }
  642. if len(opts.publicIPv6) > 0 {
  643. extV6Addr = net.ParseIP(opts.publicIPv6)
  644. if extV6Addr == nil {
  645. return nil, fmt.Errorf("invalid public IPv6 address: %s", opts.publicIPv6)
  646. }
  647. log.Infof("Using %s as external address", extV6Addr)
  648. }
  649. if extV6Addr == nil {
  650. log.Infof("Defaulting external v6 address to interface address (%s)", ifaceV6Addr)
  651. extV6Addr = ifaceV6Addr
  652. }
  653. return &backend.ExternalInterface{
  654. Iface: iface,
  655. IfaceAddr: ifaceAddr,
  656. IfaceV6Addr: ifaceV6Addr,
  657. ExtAddr: extAddr,
  658. ExtV6Addr: extV6Addr,
  659. }, nil
  660. }
  661. func WriteSubnetFile(path string, config *subnet.Config, ipMasq bool, bn backend.Network) error {
  662. dir, name := filepath.Split(path)
  663. os.MkdirAll(dir, 0755)
  664. tempFile := filepath.Join(dir, "."+name)
  665. f, err := os.Create(tempFile)
  666. if err != nil {
  667. return err
  668. }
  669. if config.EnableIPv4 {
  670. nw := config.Network
  671. sn := bn.Lease().Subnet
  672. // Write out the first usable IP by incrementing sn.IP by one
  673. sn.IncrementIP()
  674. fmt.Fprintf(f, "FLANNEL_NETWORK=%s\n", nw)
  675. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn)
  676. }
  677. if config.EnableIPv6 {
  678. ip6Nw := config.IPv6Network
  679. ip6Sn := bn.Lease().IPv6Subnet
  680. // Write out the first usable IP by incrementing ip6Sn.IP by one
  681. ip6Sn.IncrementIP()
  682. fmt.Fprintf(f, "FLANNEL_IPV6_NETWORK=%s\n", ip6Nw)
  683. fmt.Fprintf(f, "FLANNEL_IPV6_SUBNET=%s\n", ip6Sn)
  684. }
  685. fmt.Fprintf(f, "FLANNEL_MTU=%d\n", bn.MTU())
  686. _, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", ipMasq)
  687. f.Close()
  688. if err != nil {
  689. return err
  690. }
  691. // rename(2) the temporary file to the desired location so that it becomes
  692. // atomically visible with the contents
  693. return os.Rename(tempFile, path)
  694. //TODO - is this safe? What if it's not on the same FS?
  695. }
  696. func mustRunHealthz() {
  697. address := net.JoinHostPort(opts.healthzIP, strconv.Itoa(opts.healthzPort))
  698. log.Infof("Start healthz server on %s", address)
  699. http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  700. w.WriteHeader(http.StatusOK)
  701. w.Write([]byte("flanneld is running"))
  702. })
  703. if err := http.ListenAndServe(address, nil); err != nil {
  704. log.Errorf("Start healthz server error. %v", err)
  705. panic(err)
  706. }
  707. }
  708. func ReadCIDRFromSubnetFile(path string, CIDRKey string) ip.IP4Net {
  709. var prevCIDR ip.IP4Net
  710. if _, err := os.Stat(path); !os.IsNotExist(err) {
  711. prevSubnetVals, err := godotenv.Read(path)
  712. if err != nil {
  713. log.Errorf("Couldn't fetch previous %s from subnet file at %s: %s", CIDRKey, path, err)
  714. } else if prevCIDRString, ok := prevSubnetVals[CIDRKey]; ok {
  715. err = prevCIDR.UnmarshalJSON([]byte(prevCIDRString))
  716. if err != nil {
  717. log.Errorf("Couldn't parse previous %s from subnet file at %s: %s", CIDRKey, path, err)
  718. }
  719. }
  720. }
  721. return prevCIDR
  722. }
  723. func ReadIP6CIDRFromSubnetFile(path string, CIDRKey string) ip.IP6Net {
  724. var prevCIDR ip.IP6Net
  725. if _, err := os.Stat(path); !os.IsNotExist(err) {
  726. prevSubnetVals, err := godotenv.Read(path)
  727. if err != nil {
  728. log.Errorf("Couldn't fetch previous %s from subnet file at %s: %s", CIDRKey, path, err)
  729. } else if prevCIDRString, ok := prevSubnetVals[CIDRKey]; ok {
  730. err = prevCIDR.UnmarshalJSON([]byte(prevCIDRString))
  731. if err != nil {
  732. log.Errorf("Couldn't parse previous %s from subnet file at %s: %s", CIDRKey, path, err)
  733. }
  734. }
  735. }
  736. return prevCIDR
  737. }