main.go 7.8 KB

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