main.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2015 CoreOS, Inc.
  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. "encoding/json"
  17. "flag"
  18. "fmt"
  19. "net"
  20. "os"
  21. "os/signal"
  22. "path/filepath"
  23. "strings"
  24. "syscall"
  25. "time"
  26. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/go-systemd/daemon"
  27. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  28. "github.com/coreos/flannel/backend"
  29. "github.com/coreos/flannel/backend/alloc"
  30. "github.com/coreos/flannel/backend/hostgw"
  31. "github.com/coreos/flannel/backend/udp"
  32. "github.com/coreos/flannel/backend/vxlan"
  33. "github.com/coreos/flannel/pkg/ip"
  34. "github.com/coreos/flannel/pkg/task"
  35. "github.com/coreos/flannel/subnet"
  36. )
  37. type CmdLineOpts struct {
  38. etcdEndpoints string
  39. etcdPrefix string
  40. etcdKeyfile string
  41. etcdCertfile string
  42. etcdCAFile string
  43. help bool
  44. version bool
  45. ipMasq bool
  46. subnetFile string
  47. iface string
  48. }
  49. var opts CmdLineOpts
  50. func init() {
  51. flag.StringVar(&opts.etcdEndpoints, "etcd-endpoints", "http://127.0.0.1:4001", "a comma-delimited list of etcd endpoints")
  52. flag.StringVar(&opts.etcdPrefix, "etcd-prefix", "/coreos.com/network", "etcd prefix")
  53. flag.StringVar(&opts.etcdKeyfile, "etcd-keyfile", "", "SSL key file used to secure etcd communication")
  54. flag.StringVar(&opts.etcdCertfile, "etcd-certfile", "", "SSL certification file used to secure etcd communication")
  55. flag.StringVar(&opts.etcdCAFile, "etcd-cafile", "", "SSL Certificate Authority file used to secure etcd communication")
  56. flag.StringVar(&opts.subnetFile, "subnet-file", "/run/flannel/subnet.env", "filename where env variables (subnet and MTU values) will be written to")
  57. flag.StringVar(&opts.iface, "iface", "", "interface to use (IP or name) for inter-host communication")
  58. flag.BoolVar(&opts.ipMasq, "ip-masq", false, "setup IP masquerade rule for traffic destined outside of overlay network")
  59. flag.BoolVar(&opts.help, "help", false, "print this message")
  60. flag.BoolVar(&opts.version, "version", false, "print version and exit")
  61. }
  62. // TODO: This is yet another copy (others found in etcd, fleet) -- Pull it out!
  63. // flagsFromEnv parses all registered flags in the given flagset,
  64. // and if they are not already set it attempts to set their values from
  65. // environment variables. Environment variables take the name of the flag but
  66. // are UPPERCASE, have the given prefix, and any dashes are replaced by
  67. // underscores - for example: some-flag => PREFIX_SOME_FLAG
  68. func flagsFromEnv(prefix string, fs *flag.FlagSet) {
  69. alreadySet := make(map[string]bool)
  70. fs.Visit(func(f *flag.Flag) {
  71. alreadySet[f.Name] = true
  72. })
  73. fs.VisitAll(func(f *flag.Flag) {
  74. if !alreadySet[f.Name] {
  75. key := strings.ToUpper(prefix + "_" + strings.Replace(f.Name, "-", "_", -1))
  76. val := os.Getenv(key)
  77. if val != "" {
  78. fs.Set(f.Name, val)
  79. }
  80. }
  81. })
  82. }
  83. func writeSubnetFile(sn *backend.SubnetDef) error {
  84. // Write out the first usable IP by incrementing
  85. // sn.IP by one
  86. sn.Net.IP += 1
  87. dir, name := filepath.Split(opts.subnetFile)
  88. os.MkdirAll(dir, 0755)
  89. tempFile := filepath.Join(dir, "."+name)
  90. f, err := os.Create(tempFile)
  91. if err != nil {
  92. return err
  93. }
  94. fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn.Net)
  95. fmt.Fprintf(f, "FLANNEL_MTU=%d\n", sn.MTU)
  96. _, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", opts.ipMasq)
  97. f.Close()
  98. if err != nil {
  99. return err
  100. }
  101. // rename(2) the temporary file to the desired location so that it becomes
  102. // atomically visible with the contents
  103. return os.Rename(tempFile, opts.subnetFile)
  104. }
  105. func lookupIface() (*net.Interface, net.IP, error) {
  106. var iface *net.Interface
  107. var ipaddr net.IP
  108. var err error
  109. if len(opts.iface) > 0 {
  110. if ipaddr = net.ParseIP(opts.iface); ipaddr != nil {
  111. iface, err = ip.GetInterfaceByIP(ipaddr)
  112. if err != nil {
  113. return nil, nil, fmt.Errorf("Error looking up interface %s: %s", opts.iface, err)
  114. }
  115. } else {
  116. iface, err = net.InterfaceByName(opts.iface)
  117. if err != nil {
  118. return nil, nil, fmt.Errorf("Error looking up interface %s: %s", opts.iface, err)
  119. }
  120. }
  121. } else {
  122. log.Info("Determining IP address of default interface")
  123. if iface, err = ip.GetDefaultGatewayIface(); err != nil {
  124. return nil, nil, fmt.Errorf("Failed to get default interface: %s", err)
  125. }
  126. }
  127. if ipaddr == nil {
  128. ipaddr, err = ip.GetIfaceIP4Addr(iface)
  129. if err != nil {
  130. return nil, nil, fmt.Errorf("Failed to find IPv4 address for interface %s", iface.Name)
  131. }
  132. }
  133. return iface, ipaddr, nil
  134. }
  135. func newSubnetManager() *subnet.SubnetManager {
  136. peers := strings.Split(opts.etcdEndpoints, ",")
  137. cfg := &subnet.EtcdConfig{
  138. Endpoints: peers,
  139. Keyfile: opts.etcdKeyfile,
  140. Certfile: opts.etcdCertfile,
  141. CAFile: opts.etcdCAFile,
  142. Prefix: opts.etcdPrefix,
  143. }
  144. for {
  145. sm, err := subnet.NewSubnetManager(cfg)
  146. if err == nil {
  147. return sm
  148. }
  149. log.Error("Failed to create SubnetManager: ", err)
  150. time.Sleep(time.Second)
  151. }
  152. }
  153. func newBackend(sm *subnet.SubnetManager) (backend.Backend, error) {
  154. config := sm.GetConfig()
  155. var bt struct {
  156. Type string
  157. }
  158. if len(config.Backend) == 0 {
  159. bt.Type = "udp"
  160. } else {
  161. if err := json.Unmarshal(config.Backend, &bt); err != nil {
  162. return nil, fmt.Errorf("Error decoding Backend property of config: %v", err)
  163. }
  164. }
  165. switch strings.ToLower(bt.Type) {
  166. case "udp":
  167. return udp.New(sm, config.Backend), nil
  168. case "alloc":
  169. return alloc.New(sm), nil
  170. case "host-gw":
  171. return hostgw.New(sm), nil
  172. case "vxlan":
  173. return vxlan.New(sm, config.Backend), nil
  174. default:
  175. return nil, fmt.Errorf("'%v': unknown backend type", bt.Type)
  176. }
  177. }
  178. func run(sm *subnet.SubnetManager, be backend.Backend, exit chan int) {
  179. var err error
  180. defer func() {
  181. if err == nil || err == task.ErrCanceled {
  182. exit <- 0
  183. } else {
  184. log.Error(err)
  185. exit <- 1
  186. }
  187. }()
  188. iface, ipaddr, err := lookupIface()
  189. if err != nil {
  190. return
  191. }
  192. if iface.MTU == 0 {
  193. err = fmt.Errorf("Failed to determine MTU for %s interface", ipaddr)
  194. return
  195. }
  196. log.Infof("Using %s as external interface", ipaddr)
  197. sn, err := be.Init(iface, ipaddr)
  198. if err != nil {
  199. return
  200. }
  201. if opts.ipMasq {
  202. flannelNet := sm.GetConfig().Network
  203. if err = setupIPMasq(flannelNet); err != nil {
  204. return
  205. }
  206. }
  207. writeSubnetFile(sn)
  208. daemon.SdNotify("READY=1")
  209. log.Infof("%s mode initialized", be.Name())
  210. be.Run()
  211. }
  212. func main() {
  213. // glog will log to tmp files by default. override so all entries
  214. // can flow into journald (if running under systemd)
  215. flag.Set("logtostderr", "true")
  216. // now parse command line args
  217. flag.Parse()
  218. if opts.help {
  219. fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
  220. flag.PrintDefaults()
  221. os.Exit(0)
  222. }
  223. if opts.version {
  224. fmt.Fprintln(os.Stderr, Version)
  225. os.Exit(0)
  226. }
  227. flagsFromEnv("FLANNELD", flag.CommandLine)
  228. sm := newSubnetManager()
  229. be, err := newBackend(sm)
  230. if err != nil {
  231. log.Info(err)
  232. os.Exit(1)
  233. }
  234. // Register for SIGINT and SIGTERM and wait for one of them to arrive
  235. log.Info("Installing signal handlers")
  236. sigs := make(chan os.Signal, 1)
  237. signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
  238. exit := make(chan int)
  239. go run(sm, be, exit)
  240. for {
  241. select {
  242. case <-sigs:
  243. // unregister to get default OS nuke behaviour in case we don't exit cleanly
  244. signal.Stop(sigs)
  245. log.Info("Exiting...")
  246. be.Stop()
  247. case code := <-exit:
  248. log.Infof("%s mode exited", be.Name())
  249. os.Exit(code)
  250. }
  251. }
  252. }