main.go 8.8 KB

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