main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. "os"
  21. "os/signal"
  22. "path/filepath"
  23. "strings"
  24. "syscall"
  25. "github.com/coreos/pkg/flagutil"
  26. log "github.com/golang/glog"
  27. "golang.org/x/net/context"
  28. "github.com/coreos/flannel/network"
  29. "github.com/coreos/flannel/pkg/ip"
  30. "github.com/coreos/flannel/subnet"
  31. "github.com/coreos/flannel/subnet/etcdv2"
  32. "github.com/coreos/flannel/subnet/kube"
  33. "github.com/coreos/flannel/version"
  34. "time"
  35. // Backends need to be imported for their init() to get executed and them to register
  36. "github.com/coreos/flannel/backend"
  37. _ "github.com/coreos/flannel/backend/alivpc"
  38. _ "github.com/coreos/flannel/backend/alloc"
  39. _ "github.com/coreos/flannel/backend/awsvpc"
  40. _ "github.com/coreos/flannel/backend/extension"
  41. _ "github.com/coreos/flannel/backend/gce"
  42. _ "github.com/coreos/flannel/backend/hostgw"
  43. _ "github.com/coreos/flannel/backend/udp"
  44. _ "github.com/coreos/flannel/backend/vxlan"
  45. "github.com/coreos/go-systemd/daemon"
  46. )
  47. type CmdLineOpts struct {
  48. etcdEndpoints string
  49. etcdPrefix string
  50. etcdKeyfile string
  51. etcdCertfile string
  52. etcdCAFile string
  53. etcdUsername string
  54. etcdPassword string
  55. help bool
  56. version bool
  57. kubeSubnetMgr bool
  58. iface string
  59. ipMasq bool
  60. subnetFile string
  61. subnetDir string
  62. publicIP string
  63. subnetLeaseRenewMargin int
  64. }
  65. var (
  66. opts CmdLineOpts
  67. errInterrupted = errors.New("interrupted")
  68. errCanceled = errors.New("canceled")
  69. )
  70. func init() {
  71. flag.StringVar(&opts.etcdEndpoints, "etcd-endpoints", "http://127.0.0.1:4001,http://127.0.0.1:2379", "a comma-delimited list of etcd endpoints")
  72. flag.StringVar(&opts.etcdPrefix, "etcd-prefix", "/coreos.com/network", "etcd prefix")
  73. flag.StringVar(&opts.etcdKeyfile, "etcd-keyfile", "", "SSL key file used to secure etcd communication")
  74. flag.StringVar(&opts.etcdCertfile, "etcd-certfile", "", "SSL certification file used to secure etcd communication")
  75. flag.StringVar(&opts.etcdCAFile, "etcd-cafile", "", "SSL Certificate Authority file used to secure etcd communication")
  76. flag.StringVar(&opts.etcdUsername, "etcd-username", "", "Username for BasicAuth to etcd")
  77. flag.StringVar(&opts.etcdPassword, "etcd-password", "", "Password for BasicAuth to etcd")
  78. flag.StringVar(&opts.iface, "iface", "", "interface to use (IP or name) for inter-host communication")
  79. flag.StringVar(&opts.subnetFile, "subnet-file", "/run/flannel/subnet.env", "filename where env variables (subnet, MTU, ... ) will be written to")
  80. flag.StringVar(&opts.publicIP, "public-ip", "", "IP accessible by other nodes for inter-host communication")
  81. flag.IntVar(&opts.subnetLeaseRenewMargin, "subnet-lease-renew-margin", 60, "Subnet lease renewal margin, in minutes.")
  82. flag.BoolVar(&opts.ipMasq, "ip-masq", false, "setup IP masquerade rule for traffic destined outside of overlay network")
  83. flag.BoolVar(&opts.kubeSubnetMgr, "kube-subnet-mgr", false, "Contact the Kubernetes API for subnet assignement instead of etcd.")
  84. flag.BoolVar(&opts.help, "help", false, "print this message")
  85. flag.BoolVar(&opts.version, "version", false, "print version and exit")
  86. }
  87. func newSubnetManager() (subnet.Manager, error) {
  88. if opts.kubeSubnetMgr {
  89. return kube.NewSubnetManager()
  90. }
  91. cfg := &etcdv2.EtcdConfig{
  92. Endpoints: strings.Split(opts.etcdEndpoints, ","),
  93. Keyfile: opts.etcdKeyfile,
  94. Certfile: opts.etcdCertfile,
  95. CAFile: opts.etcdCAFile,
  96. Prefix: opts.etcdPrefix,
  97. Username: opts.etcdUsername,
  98. Password: opts.etcdPassword,
  99. }
  100. return etcdv2.NewLocalManager(cfg)
  101. }
  102. func main() {
  103. // glog will log to tmp files by default. override so all entries
  104. // can flow into journald (if running under systemd)
  105. flag.Set("logtostderr", "true")
  106. // now parse command line args
  107. flag.Parse()
  108. if flag.NArg() > 0 || opts.help {
  109. fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
  110. flag.PrintDefaults()
  111. os.Exit(0)
  112. }
  113. if opts.version {
  114. fmt.Fprintln(os.Stderr, version.Version)
  115. os.Exit(0)
  116. }
  117. flagutil.SetFlagsFromEnv(flag.CommandLine, "FLANNELD")
  118. // Work out which interface to use
  119. extIface, err := LookupExtIface(opts.iface)
  120. if err != nil {
  121. log.Error("Failed to find interface to use: ", err)
  122. os.Exit(1)
  123. }
  124. sm, err := newSubnetManager()
  125. if err != nil {
  126. log.Error("Failed to create SubnetManager: ", err)
  127. os.Exit(1)
  128. }
  129. log.Infof("Created subnet manager: %+v", sm)
  130. // Register for SIGINT and SIGTERM
  131. log.Info("Installing signal handlers")
  132. sigs := make(chan os.Signal, 1)
  133. signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
  134. ctx, cancel := context.WithCancel(context.Background())
  135. go shutdown(sigs, cancel)
  136. // Fetch the network config (i.e. what backend to use etc..).
  137. config, err := getConfig(ctx, sm)
  138. if err == errCanceled {
  139. exit()
  140. }
  141. // Create a backend manager then use it to create the backend and register the network with it.
  142. bm := backend.NewManager(ctx, sm, extIface)
  143. be, err := bm.GetBackend(config.BackendType)
  144. if err != nil {
  145. log.Errorf("Error fetching backend: %s", err)
  146. exit()
  147. }
  148. bn, err := be.RegisterNetwork(ctx, config)
  149. if err != nil {
  150. log.Errorf("Error registering network: %s", err)
  151. exit()
  152. }
  153. // Set up ipMasq if needed
  154. if opts.ipMasq {
  155. err = network.SetupIPMasq(config.Network)
  156. if err != nil {
  157. // Continue, even though it failed.
  158. log.Errorf("Failed to set up IP Masquerade: %v", err)
  159. }
  160. defer func() {
  161. if err := network.TeardownIPMasq(config.Network); err != nil {
  162. log.Errorf("Failed to tear down IP Masquerade: %v", err)
  163. }
  164. }()
  165. }
  166. if err := WriteSubnetFile(opts.subnetFile, config.Network, opts.ipMasq, bn); err != nil {
  167. // Continue, even though it failed.
  168. log.Warningf("Failed to write subnet file: %s", err)
  169. } else {
  170. log.Infof("Wrote subnet file to %s", opts.subnetFile)
  171. }
  172. // Start "Running" the backend network. This will block until the context is done so run in another goroutine.
  173. go bn.Run(ctx)
  174. log.Infof("Finished starting backend.")
  175. daemon.SdNotify(false, "READY=1")
  176. // Block waiting to renew the lease
  177. _ = MonitorLease(ctx, sm, bn)
  178. // To get to here, the Cancel signal must have been received or the lease has been revoked.
  179. exit()
  180. }
  181. func exit() {
  182. // Wait just a second for the cancel signal to propagate everywhere, then just exit cleanly.
  183. log.Info("Waiting for cancel to propagate...")
  184. time.Sleep(time.Second)
  185. log.Info("Exiting...")
  186. os.Exit(0)
  187. }
  188. func shutdown(sigs chan os.Signal, cancel context.CancelFunc) {
  189. // Wait for the shutdown signal.
  190. <-sigs
  191. // Unregister to get default OS nuke behaviour in case we don't exit cleanly
  192. signal.Stop(sigs)
  193. log.Info("Starting shutdown...")
  194. // Call cancel on the context to close everything down.
  195. cancel()
  196. log.Info("Sent cancel signal...")
  197. }
  198. func getConfig(ctx context.Context, sm subnet.Manager) (*subnet.Config, error) {
  199. // Retry every second until it succeeds
  200. for {
  201. config, err := sm.GetNetworkConfig(ctx)
  202. if err != nil {
  203. log.Errorf("Couldn't fetch network config: %s", err)
  204. } else if config == nil {
  205. log.Warningf("Couldn't find network config: %s", err)
  206. } else {
  207. log.Infof("Found network config - Backend type: %s", config.BackendType)
  208. return config, nil
  209. }
  210. select {
  211. case <-ctx.Done():
  212. return nil, errCanceled
  213. case <-time.After(1 * time.Second):
  214. fmt.Println("timed out")
  215. }
  216. }
  217. }
  218. func MonitorLease(ctx context.Context, sm subnet.Manager, bn backend.Network) error {
  219. // Use the subnet manager to start watching leases.
  220. evts := make(chan subnet.Event)
  221. go subnet.WatchLease(ctx, sm, bn.Lease().Subnet, evts)
  222. renewMargin := time.Duration(opts.subnetLeaseRenewMargin) * time.Minute
  223. dur := bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  224. for {
  225. select {
  226. case <-time.After(dur):
  227. err := sm.RenewLease(ctx, bn.Lease())
  228. if err != nil {
  229. log.Error("Error renewing lease (trying again in 1 min): ", err)
  230. dur = time.Minute
  231. continue
  232. }
  233. log.Info("Lease renewed, new expiration: ", bn.Lease().Expiration)
  234. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  235. case e := <-evts:
  236. switch e.Type {
  237. case subnet.EventAdded:
  238. bn.Lease().Expiration = e.Lease.Expiration
  239. dur = bn.Lease().Expiration.Sub(time.Now()) - renewMargin
  240. log.Infof("Waiting for %s to renew lease", dur)
  241. case subnet.EventRemoved:
  242. log.Error("Lease has been revoked. Shutting down daemon.")
  243. return errInterrupted
  244. }
  245. case <-ctx.Done():
  246. log.Infof("Stopped monitoring lease")
  247. return errCanceled
  248. }
  249. }
  250. }
  251. func LookupExtIface(ifname string) (*backend.ExternalInterface, error) {
  252. var iface *net.Interface
  253. var ifaceAddr net.IP
  254. var err error
  255. if len(ifname) > 0 {
  256. if ifaceAddr = net.ParseIP(ifname); ifaceAddr != nil {
  257. log.Infof("Searching for interface using %s", ifaceAddr)
  258. iface, err = ip.GetInterfaceByIP(ifaceAddr)
  259. if err != nil {
  260. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  261. }
  262. } else {
  263. iface, err = net.InterfaceByName(ifname)
  264. if err != nil {
  265. return nil, fmt.Errorf("error looking up interface %s: %s", ifname, err)
  266. }
  267. }
  268. } else {
  269. log.Info("Determining IP address of default interface")
  270. if iface, err = ip.GetDefaultGatewayIface(); err != nil {
  271. return nil, fmt.Errorf("failed to get default interface: %s", err)
  272. }
  273. }
  274. if ifaceAddr == nil {
  275. ifaceAddr, err = ip.GetIfaceIP4Addr(iface)
  276. if err != nil {
  277. return nil, fmt.Errorf("failed to find IPv4 address for interface %s", iface.Name)
  278. }
  279. }
  280. log.Infof("Using interface with name %s and address %s", iface.Name, ifaceAddr)
  281. if iface.MTU == 0 {
  282. return nil, fmt.Errorf("failed to determine MTU for %s interface", ifaceAddr)
  283. }
  284. var extAddr net.IP
  285. if len(opts.publicIP) > 0 {
  286. extAddr = net.ParseIP(opts.publicIP)
  287. if extAddr == nil {
  288. return nil, fmt.Errorf("invalid public IP address: %s", opts.publicIP)
  289. }
  290. log.Infof("Using %s as external address", extAddr)
  291. }
  292. if extAddr == nil {
  293. log.Infof("Defaulting external address to interface address (%s)", ifaceAddr)
  294. extAddr = ifaceAddr
  295. }
  296. return &backend.ExternalInterface{
  297. Iface: iface,
  298. IfaceAddr: ifaceAddr,
  299. ExtAddr: extAddr,
  300. }, nil
  301. }
  302. func WriteSubnetFile(path string, nw ip.IP4Net, ipMasq bool, bn backend.Network) error {
  303. dir, name := filepath.Split(path)
  304. os.MkdirAll(dir, 0755)
  305. tempFile := filepath.Join(dir, "."+name)
  306. f, err := os.Create(tempFile)
  307. if err != nil {
  308. return err
  309. }
  310. // Write out the first usable IP by incrementing
  311. // sn.IP by one
  312. sn := bn.Lease().Subnet
  313. sn.IP += 1
  314. fmt.Fprintf(f, "FLANNEL_NETWORK=%s\n", nw)
  315. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn)
  316. fmt.Fprintf(f, "FLANNEL_MTU=%d\n", bn.MTU())
  317. _, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", ipMasq)
  318. f.Close()
  319. if err != nil {
  320. return err
  321. }
  322. // rename(2) the temporary file to the desired location so that it becomes
  323. // atomically visible with the contents
  324. return os.Rename(tempFile, path)
  325. //TODO - is this safe? What if it's not on the same FS?
  326. }