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