main.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. ifregex, err := regexp.Compile(ifregexS)
  459. if err != nil {
  460. return nil, fmt.Errorf("could not compile the IP address regex '%s': %w", ifregexS, err)
  461. }
  462. // Check ip family stack
  463. if ipStack == noneStack {
  464. return nil, fmt.Errorf("none matched ip stack")
  465. }
  466. if len(ifname) > 0 {
  467. if ifaceAddr = net.ParseIP(ifname); ifaceAddr != nil {
  468. log.Infof("Searching for interface using %s", ifaceAddr)
  469. switch ipStack {
  470. case ipv4Stack:
  471. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  472. if err != nil {
  473. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  474. }
  475. case ipv6Stack:
  476. iface, err = ip.GetInterfaceByIP6(ifaceAddr)
  477. if err != nil {
  478. return nil, fmt.Errorf("error looking up v6 interface %s: %s", ifname, err)
  479. }
  480. case dualStack:
  481. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  482. if err != nil {
  483. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  484. }
  485. v6Iface, err := ip.GetInterfaceByIP6(ifaceAddr)
  486. if err != nil {
  487. return nil, fmt.Errorf("error looking up v6 interface %s: %s", ifname, err)
  488. }
  489. if iface.Name != v6Iface.Name {
  490. return nil, fmt.Errorf("v6 interface %s must be the same with v4 interface %s", v6Iface.Name, iface.Name)
  491. }
  492. }
  493. } else {
  494. iface, err = net.InterfaceByName(ifname)
  495. if err != nil {
  496. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  497. }
  498. }
  499. } else if len(ifregex) > 0 {
  500. // Use the regex if specified and the iface option for matching a specific ip or name is not used
  501. ifaces, err := net.Interfaces()
  502. if err != nil {
  503. return nil, fmt.Errorf("error listing all interfaces: %s", err)
  504. }
  505. // Check IP
  506. for _, ifaceToMatch := range ifaces {
  507. switch ipStack {
  508. case ipv4Stack:
  509. ifaceIP, err := ip.GetInterfaceIP4Addr(&ifaceToMatch)
  510. if err != nil {
  511. // Skip if there is no IPv4 address
  512. continue
  513. }
  514. matched, err := ifregex.MatchString(ifaceIP.String())
  515. if err != nil {
  516. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregexS, ifaceIP.String())
  517. }
  518. if matched {
  519. ifaceAddr = ifaceIP
  520. iface = &ifaceToMatch
  521. break
  522. }
  523. case ipv6Stack:
  524. ifaceIP, err := ip.GetInterfaceIP6Addr(&ifaceToMatch)
  525. if err != nil {
  526. // Skip if there is no IPv6 address
  527. continue
  528. }
  529. matched, err := ifregex.MatchString(ifaceIP.String())
  530. if err != nil {
  531. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregexS, ifaceIP.String())
  532. }
  533. if matched {
  534. ifaceV6Addr = ifaceIP
  535. iface = &ifaceToMatch
  536. break
  537. }
  538. case dualStack:
  539. ifaceIP, err := ip.GetInterfaceIP4Addr(&ifaceToMatch)
  540. if err != nil {
  541. // Skip if there is no IPv4 address
  542. continue
  543. }
  544. matched, err := ifregex.MatchString(ifaceIP.String())
  545. if err != nil {
  546. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregexS, ifaceIP.String())
  547. }
  548. ifaceV6IP, err := ip.GetInterfaceIP6Addr(&ifaceToMatch)
  549. if err != nil {
  550. // Skip if there is no IPv6 address
  551. continue
  552. }
  553. v6Matched, err := ifregex.MatchString(ifaceV6IP.String())
  554. if err != nil {
  555. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregexS, ifaceIP.String())
  556. }
  557. if matched && v6Matched {
  558. ifaceAddr = ifaceIP
  559. ifaceV6Addr = ifaceV6IP
  560. iface = &ifaceToMatch
  561. break
  562. }
  563. }
  564. }
  565. // Check Name
  566. if iface == nil && (ifaceAddr == nil || ifaceV6Addr == nil) {
  567. for _, ifaceToMatch := range ifaces {
  568. matched, err := ifregex.MatchString(ifaceToMatch.Name)
  569. if err != nil {
  570. return nil, fmt.Errorf("regex error matching pattern %s to %s", ifregexS, ifaceToMatch.Name)
  571. }
  572. if matched {
  573. iface = &ifaceToMatch
  574. break
  575. }
  576. }
  577. }
  578. // Check that nothing was matched
  579. if iface == nil {
  580. var availableFaces []string
  581. for _, f := range ifaces {
  582. var ipaddr net.IP
  583. switch ipStack {
  584. case ipv4Stack, dualStack:
  585. ipaddr, _ = ip.GetInterfaceIP4Addr(&f) // We can safely ignore errors. We just won't log any ip
  586. case ipv6Stack:
  587. ipaddr, _ = ip.GetInterfaceIP6Addr(&f) // We can safely ignore errors. We just won't log any ip
  588. }
  589. availableFaces = append(availableFaces, fmt.Sprintf("%s:%s", f.Name, ipaddr))
  590. }
  591. return nil, fmt.Errorf("Could not match pattern %s to any of the available network interfaces (%s)", ifregexS, strings.Join(availableFaces, ", "))
  592. }
  593. } else {
  594. log.Info("Determining IP address of default interface")
  595. switch ipStack {
  596. case ipv4Stack:
  597. if iface, err = ip.GetDefaultGatewayInterface(); err != nil {
  598. return nil, fmt.Errorf("failed to get default interface: %w", err)
  599. }
  600. case ipv6Stack:
  601. if iface, err = ip.GetDefaultV6GatewayInterface(); err != nil {
  602. return nil, fmt.Errorf("failed to get default v6 interface: %w", err)
  603. }
  604. case dualStack:
  605. if iface, err = ip.GetDefaultGatewayInterface(); err != nil {
  606. return nil, fmt.Errorf("failed to get default interface: %w", err)
  607. }
  608. v6Iface, err := ip.GetDefaultV6GatewayInterface()
  609. if err != nil {
  610. return nil, fmt.Errorf("failed to get default v6 interface: %w", err)
  611. }
  612. if iface.Name != v6Iface.Name {
  613. return nil, fmt.Errorf("v6 default route interface %s "+
  614. "must be the same with v4 default route interface %s", v6Iface.Name, iface.Name)
  615. }
  616. }
  617. }
  618. if ipStack == ipv4Stack && ifaceAddr == nil {
  619. ifaceAddr, err = ip.GetInterfaceIP4Addr(iface)
  620. if err != nil {
  621. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  622. }
  623. } else if ipStack == ipv6Stack && ifaceV6Addr == nil {
  624. ifaceV6Addr, err = ip.GetInterfaceIP6Addr(iface)
  625. if err != nil {
  626. return nil, fmt.Errorf("failed to find IPv6 address for interface %s", iface.Name)
  627. }
  628. } else if ipStack == dualStack && ifaceAddr == nil && ifaceV6Addr == nil {
  629. ifaceAddr, err = ip.GetInterfaceIP4Addr(iface)
  630. if err != nil {
  631. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  632. }
  633. ifaceV6Addr, err = ip.GetInterfaceIP6Addr(iface)
  634. if err != nil {
  635. return nil, fmt.Errorf("failed to find IPv6 address for interface %s", iface.Name)
  636. }
  637. }
  638. if ifaceAddr != nil {
  639. log.Infof("Using interface with name %s and address %s", iface.Name, ifaceAddr)
  640. }
  641. if ifaceV6Addr != nil {
  642. log.Infof("Using interface with name %s and v6 address %s", iface.Name, ifaceV6Addr)
  643. }
  644. if iface.MTU == 0 {
  645. return nil, fmt.Errorf("failed to determine MTU for %s interface", ifaceAddr)
  646. }
  647. var extAddr net.IP
  648. var extV6Addr net.IP
  649. if len(opts.publicIP) > 0 {
  650. extAddr = net.ParseIP(opts.publicIP)
  651. if extAddr == nil {
  652. return nil, fmt.Errorf("invalid public IP address: %s", opts.publicIP)
  653. }
  654. log.Infof("Using %s as external address", extAddr)
  655. }
  656. if extAddr == nil {
  657. log.Infof("Defaulting external address to interface address (%s)", ifaceAddr)
  658. extAddr = ifaceAddr
  659. }
  660. if len(opts.publicIPv6) > 0 {
  661. extV6Addr = net.ParseIP(opts.publicIPv6)
  662. if extV6Addr == nil {
  663. return nil, fmt.Errorf("invalid public IPv6 address: %s", opts.publicIPv6)
  664. }
  665. log.Infof("Using %s as external address", extV6Addr)
  666. }
  667. if extV6Addr == nil {
  668. log.Infof("Defaulting external v6 address to interface address (%s)", ifaceV6Addr)
  669. extV6Addr = ifaceV6Addr
  670. }
  671. return &backend.ExternalInterface{
  672. Iface: iface,
  673. IfaceAddr: ifaceAddr,
  674. IfaceV6Addr: ifaceV6Addr,
  675. ExtAddr: extAddr,
  676. ExtV6Addr: extV6Addr,
  677. }, nil
  678. }
  679. func WriteSubnetFile(path string, config *subnet.Config, ipMasq bool, bn backend.Network) error {
  680. dir, name := filepath.Split(path)
  681. os.MkdirAll(dir, 0755)
  682. tempFile := filepath.Join(dir, "."+name)
  683. f, err := os.Create(tempFile)
  684. if err != nil {
  685. return err
  686. }
  687. if config.EnableIPv4 {
  688. nw := config.Network
  689. // Write out the first usable IP by incrementing
  690. // sn.IP by one
  691. sn := bn.Lease().Subnet
  692. sn.IP += 1
  693. fmt.Fprintf(f, "FLANNEL_NETWORK=%s\n", nw)
  694. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn)
  695. }
  696. if config.EnableIPv6 {
  697. ip6Nw := config.IPv6Network
  698. ip6Sn := bn.Lease().IPv6Subnet
  699. ip6Sn.IP = (*ip.IP6)(big.NewInt(0).Add((*big.Int)(ip6Sn.IP), big.NewInt(1)))
  700. fmt.Fprintf(f, "FLANNEL_IPV6_NETWORK=%s\n", ip6Nw)
  701. fmt.Fprintf(f, "FLANNEL_IPV6_SUBNET=%s\n", ip6Sn)
  702. }
  703. fmt.Fprintf(f, "FLANNEL_MTU=%d\n", bn.MTU())
  704. _, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", ipMasq)
  705. f.Close()
  706. if err != nil {
  707. return err
  708. }
  709. // rename(2) the temporary file to the desired location so that it becomes
  710. // atomically visible with the contents
  711. return os.Rename(tempFile, path)
  712. //TODO - is this safe? What if it's not on the same FS?
  713. }
  714. func mustRunHealthz() {
  715. address := net.JoinHostPort(opts.healthzIP, strconv.Itoa(opts.healthzPort))
  716. log.Infof("Start healthz server on %s", address)
  717. http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  718. w.WriteHeader(http.StatusOK)
  719. w.Write([]byte("flanneld is running"))
  720. })
  721. if err := http.ListenAndServe(address, nil); err != nil {
  722. log.Errorf("Start healthz server error. %v", err)
  723. panic(err)
  724. }
  725. }
  726. func ReadCIDRFromSubnetFile(path string, CIDRKey string) ip.IP4Net {
  727. var prevCIDR ip.IP4Net
  728. if _, err := os.Stat(path); !os.IsNotExist(err) {
  729. prevSubnetVals, err := godotenv.Read(path)
  730. if err != nil {
  731. log.Errorf("Couldn't fetch previous %s from subnet file at %s: %s", CIDRKey, path, err)
  732. } else if prevCIDRString, ok := prevSubnetVals[CIDRKey]; ok {
  733. err = prevCIDR.UnmarshalJSON([]byte(prevCIDRString))
  734. if err != nil {
  735. log.Errorf("Couldn't parse previous %s from subnet file at %s: %s", CIDRKey, path, err)
  736. }
  737. }
  738. }
  739. return prevCIDR
  740. }
  741. func ReadIP6CIDRFromSubnetFile(path string, CIDRKey string) ip.IP6Net {
  742. var prevCIDR ip.IP6Net
  743. if _, err := os.Stat(path); !os.IsNotExist(err) {
  744. prevSubnetVals, err := godotenv.Read(path)
  745. if err != nil {
  746. log.Errorf("Couldn't fetch previous %s from subnet file at %s: %s", CIDRKey, path, err)
  747. } else if prevCIDRString, ok := prevSubnetVals[CIDRKey]; ok {
  748. err = prevCIDR.UnmarshalJSON([]byte(prevCIDRString))
  749. if err != nil {
  750. log.Errorf("Couldn't parse previous %s from subnet file at %s: %s", CIDRKey, path, err)
  751. }
  752. }
  753. }
  754. return prevCIDR
  755. }