func main() { ignoreIfaceNames := make(stringList) mflag.Var(&ignoreIfaceNames, []string{"-ignore-iface"}, "name of interface to ignore)") mflag.Parse() if len(mflag.Args()) < 1 { fmt.Fprintln(os.Stderr, "usage: netcheck [--ignore-iface <iface-name>] network-cidr") os.Exit(1) } cidrStr := mflag.Args()[0] addr, ipnet, err := net.ParseCIDR(cidrStr) if err != nil { fatal(err) } if ipnet.IP.Equal(addr) { err = weavenet.CheckNetworkFree(ipnet, ignoreIfaceNames) } else { err = weavenet.CheckAddressOverlap(addr, ignoreIfaceNames) } if err != nil { fatal(err) } os.Exit(0) }
func main() { flag.Parse() if flLogLevel != "" { lvl, err := logrus.ParseLevel(flLogLevel) if err != nil { fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", flLogLevel) os.Exit(1) } logrus.SetLevel(lvl) } else { logrus.SetLevel(logrus.InfoLevel) } if flDebug { logrus.SetLevel(logrus.DebugLevel) } d, err := rbd.NewRbdDriver(root, graphOptions) if err != nil { logrus.Errorf("Create rbd driver failed: %v", err) os.Exit(1) } h := degraph.NewHandler(d) logrus.Infof("listening on %s\n", socketAddress) fmt.Println(h.ServeUnix("root", socketAddress)) }
func readConfig() { var ( configFile string showHelp, showVersion bool ) logFilter = &logutils.LevelFilter{ Levels: logLevels, MinLevel: logMinLevel, Writer: os.Stderr, } log.SetOutput(logFilter) flag.StringVar(&configFile, []string{"c", "-config"}, "/etc/logear/logear.conf", "config file") flag.StringVar(&logFile, []string{"l", "-log"}, "", "log file") flag.BoolVar(&showHelp, []string{"h", "-help"}, false, "display the help") flag.BoolVar(&showVersion, []string{"v", "-version"}, false, "display version info") flag.Parse() if showHelp { flag.Usage() os.Exit(0) } if showVersion { println(versionstring) println("OS: " + runtime.GOOS) println("Architecture: " + runtime.GOARCH) os.Exit(0) } parseTomlFile(configFile) startLogging() log.Printf("%s started with pid %d", versionstring, os.Getpid()) }
func init() { // Check https://github.com/docker/docker/blob/master/pkg/mflag/example/example.go flag.StringVar(&path, []string{"p", "#pathhidden", "-path"}, "", "path to traverse") flag.StringVar(&path, []string{"n", "#namehidden", "-name"}, "", "name to traverse") flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help") flag.Parse() }
func main() { var ( justVersion bool logLevel = "info" c proxy.Config withDNS bool ) c.Version = version mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") mflagext.ListVar(&c.ListenAddrs, []string{"H"}, nil, "addresses on which to listen") mflag.StringVar(&c.HostnameFromLabel, []string{"-hostname-from-label"}, "", "Key of container label from which to obtain the container's hostname") mflag.StringVar(&c.HostnameMatch, []string{"-hostname-match"}, "(.*)", "Regexp pattern to apply on container names (e.g. '^aws-[0-9]+-(.*)$')") mflag.StringVar(&c.HostnameReplacement, []string{"-hostname-replacement"}, "$1", "Expression to generate hostnames based on matches from --hostname-match (e.g. 'my-app-$1')") mflag.BoolVar(&c.RewriteInspect, []string{"-rewrite-inspect"}, false, "Rewrite 'inspect' calls to return the weave network settings (if attached)") mflag.BoolVar(&c.NoDefaultIPAM, []string{"#-no-default-ipam", "-no-default-ipalloc"}, false, "do not automatically allocate addresses for containers without a WEAVE_CIDR") mflag.BoolVar(&c.NoRewriteHosts, []string{"-no-rewrite-hosts"}, false, "do not automatically rewrite /etc/hosts. Use if you need the docker IP to remain in /etc/hosts") mflag.StringVar(&c.TLSConfig.CACert, []string{"#tlscacert", "-tlscacert"}, "", "Trust certs signed only by this CA") mflag.StringVar(&c.TLSConfig.Cert, []string{"#tlscert", "-tlscert"}, "", "Path to TLS certificate file") mflag.BoolVar(&c.TLSConfig.Enabled, []string{"#tls", "-tls"}, false, "Use TLS; implied by --tlsverify") mflag.StringVar(&c.TLSConfig.Key, []string{"#tlskey", "-tlskey"}, "", "Path to TLS key file") mflag.BoolVar(&c.TLSConfig.Verify, []string{"#tlsverify", "-tlsverify"}, false, "Use TLS and verify the remote") mflag.BoolVar(&withDNS, []string{"#-with-dns", "#w"}, false, "option removed") mflag.BoolVar(&c.WithoutDNS, []string{"-without-dns"}, false, "instruct created containers to never use weaveDNS as their nameserver") mflag.BoolVar(&c.NoMulticastRoute, []string{"-no-multicast-route"}, false, "do not add a multicast route via the weave interface when attaching containers") mflag.Parse() if justVersion { fmt.Printf("weave proxy %s\n", version) os.Exit(0) } SetLogLevel(logLevel) Log.Infoln("weave proxy", version) Log.Infoln("Command line arguments:", strings.Join(os.Args[1:], " ")) if withDNS { Log.Warning("--with-dns option has been removed; DNS is on by default") } c.Image = getenv("EXEC_IMAGE", "weaveworks/weaveexec") c.DockerBridge = getenv("DOCKER_BRIDGE", "docker0") c.DockerHost = getenv("DOCKER_HOST", "unix:///var/run/docker.sock") c.ProcPath = getenv("PROCFS", "/proc") p, err := proxy.NewProxy(c) if err != nil { Log.Fatalf("Could not start proxy: %s", err) } defer p.Stop() listeners := p.Listen() p.AttachExistingContainers() go p.Serve(listeners) go p.ListenAndServeStatus("/home/weave/status.sock") SignalHandlerLoop() }
func main() { var ( as []string hostMatch string ) mflagext.ListVar(&as, []string{"a", "-alias"}, []string{}, "Specify hostname aliases in the form alias:hostname. Can be repeated.") mflag.StringVar(&hostMatch, []string{"h", "-host-match"}, "*.weave.local", "Specify main host shExpMatch expression in pacfile") mflag.Parse() var aliases = map[string]string{} for _, a := range as { parts := strings.SplitN(a, ":", 2) if len(parts) != 2 { fmt.Printf("'%s' is not a valid alias.\n", a) mflag.Usage() os.Exit(1) } aliases[parts[0]] = parts[1] } go socksProxy(aliases) t := template.Must(template.New("pacfile").Parse(pacfile)) http.HandleFunc("/proxy.pac", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/x-ns-proxy-autoconfig") t.Execute(w, pacFileParameters{hostMatch, aliases}) }) if err := http.ListenAndServe(":8080", nil); err != nil { panic(err) } }
// parse conf from env and args func parseConf() { // let mflag parse first mflag.Parse() // using gconf parse env gconf, err := globalconf.NewWithOptions(&globalconf.Options{ EnvPrefix: "WICKET_", }) if err != nil { log.Fatalf("error parsing config file: %v", err) } fs := flag.NewFlagSet("", flag.ContinueOnError) mflag.VisitAll(func(f *mflag.Flag) { for _, n := range f.Names { if len(n) < 2 { continue } n = strings.TrimPrefix(n, "-") fs.Var(f.Value, n, f.Usage) } }) gconf.ParseSet("", fs) }
func main() { mflag.BoolVar(&useScheduler, []string{"scheduler"}, false, "Use scheduler to distribute tests across shards") mflag.BoolVar(&runParallel, []string{"parallel"}, false, "Run tests in parallel on hosts where possible") mflag.Parse() tests, err := getTests(mflag.Args()) if err != nil { fmt.Printf("Error parsing tests: %v\n", err) os.Exit(1) } hosts := strings.Fields(os.Getenv("HOSTS")) maxHosts := len(hosts) if maxHosts == 0 { fmt.Print("No HOSTS specified.\n") os.Exit(1) } var errored bool if runParallel { errored = parallel(tests, hosts) } else { errored = sequential(tests, hosts) } if errored { os.Exit(1) } }
func main() { mflag.BoolVar(&useScheduler, []string{"scheduler"}, false, "Use scheduler to distribute tests across shards") mflag.BoolVar(&runParallel, []string{"parallel"}, false, "Run tests in parallel on hosts where possible") mflag.BoolVar(&verbose, []string{"v"}, false, "Print output from all tests (Also enabled via DEBUG=1)") mflag.StringVar(&schedulerHost, []string{"scheduler-host"}, defaultSchedulerHost, "Hostname of scheduler.") mflag.Parse() if len(os.Getenv("DEBUG")) > 0 { verbose = true } tests, err := getTests(mflag.Args()) if err != nil { fmt.Printf("Error parsing tests: %v\n", err) os.Exit(1) } hosts := strings.Fields(os.Getenv("HOSTS")) maxHosts := len(hosts) if maxHosts == 0 { fmt.Print("No HOSTS specified.\n") os.Exit(1) } var errored bool if runParallel { errored = parallel(tests, hosts) } else { errored = sequential(tests, hosts) } if errored { os.Exit(1) } }
func main() { if reexec.Init() { return } // Set terminal emulation based on platform as required. stdin, stdout, stderr := term.StdStreams() logrus.SetOutput(stderr) flag.Merge(flag.CommandLine, clientFlags.FlagSet, commonFlags.FlagSet) flag.Usage = func() { fmt.Fprint(os.Stdout, "Usage: docker [OPTIONS] COMMAND [arg...]\n"+daemonUsage+" docker [ -h | --help | -v | --version ]\n\n") fmt.Fprint(os.Stdout, "A self-sufficient runtime for containers.\n\nOptions:\n") flag.CommandLine.SetOutput(os.Stdout) flag.PrintDefaults() help := "\nCommands:\n" for _, cmd := range dockerCommands { help += fmt.Sprintf(" %-10.10s%s\n", cmd.name, cmd.description) } help += "\nRun 'docker COMMAND --help' for more information on a command." fmt.Fprintf(os.Stdout, "%s\n", help) } flag.Parse() if *flVersion { showVersion() return } clientCli := client.NewDockerCli(stdin, stdout, stderr, clientFlags) // TODO: remove once `-d` is retired handleGlobalDaemonFlag() if *flHelp { // if global flag --help is present, regardless of what other options and commands there are, // just print the usage. flag.Usage() return } c := cli.New(clientCli, daemonCli) if err := c.Run(flag.Args()...); err != nil { if sterr, ok := err.(cli.StatusError); ok { if sterr.Status != "" { fmt.Fprintln(os.Stderr, sterr.Status) os.Exit(1) } os.Exit(sterr.StatusCode) } fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
func init() { flag.Bool([]string{"h", "-help"}, false, "Display help") flag.BoolVar(&verbose, []string{"v", "-verbose"}, false, "Switch to verbose output") flag.BoolVar(&print_digest, []string{"d", "-digest"}, false, "Print also digest of manifest") flag.StringVar(&key, []string{"k", "-key-file"}, "", "Private key with which to sign") flag.Parse() }
func init() { // Arguments for ssh server flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display this help message") flag.BoolVar(&server, []string{"s", "-server"}, false, "start the server") flag.StringVar(&listen, []string{"l", "-listen"}, "0.0.0.0", "start the server") flag.IntVar(&port, []string{"p", "-port"}, 5566, "port to listen") flag.StringVar(&user, []string{"-user"}, "sshcam", "username for SSH login") flag.StringVar(&pass, []string{"-pass"}, "p@ssw0rd", "password for SSH login") // Arguments for img2xterm flag.BoolVar(&colorful, []string{"c", "-color"}, false, "turn on color") flag.BoolVar(&asciiOnly, []string{"-ascii-only"}, false, "fallback to use ASCII's full block characters") flag.StringVar(&distanceAlgorithm, []string{"-color-algorithm"}, "yiq", "algorithm use to compute colors. Available options are:\n"+ "'rgb': simple linear distance in RGB colorspace\n"+ "'yiq': simple linear distance in YIQ colorspace (the default)\n"+ "'cie94': use the CIE94 formula") flag.IntVar(&maxFPS, []string{"-max-fps"}, 4, "limit the maximum FPS") flag.StringVar(&device, []string{"-device"}, "/dev/video0", "the webcam device to open") flag.StringVar(&sizeFlag, []string{"-size"}, "640x480", "image dimension, must be supported by the device") flag.Parse() size = wxh2Size(sizeFlag) }
func init() { flag.StringVar(&tplfile, []string{"t", "-template"}, "", "Template file name for produce config file.") flag.StringVar(&appName, []string{"-app"}, "appname", "App name for upstream/logfile name/conf name/consul key.") flag.StringVar(&output, []string{"o", "-output"}, "appname.conf", "Config file name for save config file.") flag.BoolVar(&help, []string{"h", "-help"}, false, "Display the help") flag.Parse() }
func init() { flag.BoolVar(&help, []string{"h", "-help"}, false, "Display help") flag.BoolVar(&verbose, []string{"v", "-verbose"}, false, "Switch to verbose output") flag.Var(&keys, []string{"k", "-key-file"}, "Private key with which to sign") flag.Parse() if kk := flag.Lookup("-k"); kk != nil { keys = *kk.Value.(*opts.ListOpts) } }
func dnetCommand(stdout, stderr io.Writer) error { flag.Parse() if *flHelp { flag.Usage() return nil } if *flLogLevel != "" { lvl, err := logrus.ParseLevel(*flLogLevel) if err != nil { fmt.Fprintf(stderr, "Unable to parse logging level: %s\n", *flLogLevel) return err } logrus.SetLevel(lvl) } else { logrus.SetLevel(logrus.InfoLevel) } if *flDebug { logrus.SetLevel(logrus.DebugLevel) } if *flHost == "" { defaultHost := os.Getenv("DNET_HOST") if defaultHost == "" { // TODO : Add UDS support defaultHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort) } *flHost = defaultHost } dc, err := newDnetConnection(*flHost) if err != nil { if *flDaemon { logrus.Error(err) } else { fmt.Fprint(stderr, err) } return err } if *flDaemon { err := dc.dnetDaemon() if err != nil { logrus.Errorf("dnet Daemon exited with an error : %v", err) } return err } cli := client.NewNetworkCli(stdout, stderr, dc.httpCall) if err := cli.Cmd("dnet", flag.Args()...); err != nil { fmt.Fprintln(stderr, err) return err } return nil }
func init() { flag.StringVar(&tplfile, []string{"t", "-template"}, "server.conf.template", "Template file name for produce config file.") flag.StringVar(&appName, []string{"-app"}, "appname", "App name for upstream/logfile name/conf name/consul key.") flag.StringVar(&consulIp, []string{"c", "-consul"}, "10.10.10.10:8500", "Consul server 'url:port' for get upstream info.") flag.StringVar(&virtualIp, []string{"v", "-virtualip"}, "0.0.0.0:81,0.0.0.1", "Virtual IP/PORT list for this app.") flag.StringVar(&output, []string{"o", "-output"}, "appname.conf", "Config file name for save config file.") flag.BoolVar(&help, []string{"h", "-help"}, false, "Display the help") flag.Parse() }
func init() { logrus.SetOutput(os.Stdout) logrus.SetLevel(logrus.DebugLevel) mflag.BoolVar(&master, []string{"m", "-master", "#mt"}, false, "if the master server.") mflag.BoolVar(&help, []string{"h", "-help", "#hhhhelp"}, false, "show help.") mflag.StringVar(&env, []string{"e", "-env"}, "test", "which config env to run.") // mflag.BoolVar(&picture, []string{"i", "-image"}, false, "download the picture that go throuth.") mflag.StringVar(&conffile, []string{"f", "-config"}, "", "point a config file.default is config/config.json.") mflag.Parse() }
func init() { flag.Bool([]string{"#hp", "#-halp"}, false, "display the halp") flag.BoolVar(&b, []string{"b", "#bal", "#bol", "-bal"}, false, "a simple bool") flag.BoolVar(&b, []string{"g", "#gil"}, false, "a simple bool") flag.BoolVar(&b2, []string{"#-bool"}, false, "a simple bool") flag.IntVar(&i, []string{"-integer", "-number"}, -1, "a simple integer") flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help") flag.StringVar(&str, []string{"mode"}, "mode1", "set the mode\nmode1: use the mode1\nmode2: use the mode2\nmode3: use the mode3") flag.Parse() }
func main() { fmt.Print("Hello, world\n") // Define global flag here // end global flag definition flag.Usage = func() { fmt.Fprint(os.Stdout, "Usage: docking [OPTIONS] COMMAND [arg...]\n docking [ --help | -v | --version ]\n\n") fmt.Fprint(os.Stdout, "A self-sufficient runtime for containers.\n\nOptions:\n") flag.CommandLine.SetOutput(os.Stdout) flag.PrintDefaults() help := "\nCommands:\n" for _, cmd := range dockingCommands { help += fmt.Sprintf(" %-10.10s%s\n", cmd.Name, cmd.Description) } help += "\nRun 'docking COMMAND --help' for more information on a command." fmt.Fprintf(os.Stdout, "%s\n", help) } flag.Parse() if *flVersion { showVersion() return } if *flHelp { // if global flag --help is present, regardless of what other options and commands there are, // just print the usage. flag.Usage() return } clientCli := client.NewDockingCli(os.Stdin, os.Stdout, os.Stderr, clientFlags) c := cli.New(clientCli) if err := c.Run(flag.Args()...); err != nil { if sterr, ok := err.(cli.StatusError); ok { if sterr.Status != "" { fmt.Fprintln(os.Stderr, sterr.Status) os.Exit(1) } os.Exit(sterr.StatusCode) } fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
func main() { var ( justVersion bool logLevel = "info" c = proxy.Config{ListenAddrs: []string{}} ) c.Version = version mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") mflagext.ListVar(&c.ListenAddrs, []string{"H"}, nil, "addresses on which to listen") mflag.StringVar(&c.HostnameFromLabel, []string{"-hostname-from-label"}, "", "Key of container label from which to obtain the container's hostname") mflag.StringVar(&c.HostnameMatch, []string{"-hostname-match"}, "(.*)", "Regexp pattern to apply on container names (e.g. '^aws-[0-9]+-(.*)$')") mflag.StringVar(&c.HostnameReplacement, []string{"-hostname-replacement"}, "$1", "Expression to generate hostnames based on matches from --hostname-match (e.g. 'my-app-$1')") mflag.BoolVar(&c.RewriteInspect, []string{"-rewrite-inspect"}, false, "Rewrite 'inspect' calls to return the weave network settings (if attached)") mflag.BoolVar(&c.NoDefaultIPAM, []string{"#-no-default-ipam", "-no-default-ipalloc"}, false, "do not automatically allocate addresses for containers without a WEAVE_CIDR") mflag.BoolVar(&c.NoRewriteHosts, []string{"-no-rewrite-hosts"}, false, "do not automatically rewrite /etc/hosts. Use if you need the docker IP to remain in /etc/hosts") mflag.StringVar(&c.TLSConfig.CACert, []string{"#tlscacert", "-tlscacert"}, "", "Trust certs signed only by this CA") mflag.StringVar(&c.TLSConfig.Cert, []string{"#tlscert", "-tlscert"}, "", "Path to TLS certificate file") mflag.BoolVar(&c.TLSConfig.Enabled, []string{"#tls", "-tls"}, false, "Use TLS; implied by --tls-verify") mflag.StringVar(&c.TLSConfig.Key, []string{"#tlskey", "-tlskey"}, "", "Path to TLS key file") mflag.BoolVar(&c.TLSConfig.Verify, []string{"#tlsverify", "-tlsverify"}, false, "Use TLS and verify the remote") mflag.BoolVar(&c.WithDNS, []string{"-with-dns", "w"}, false, "instruct created containers to always use weaveDNS as their nameserver") mflag.BoolVar(&c.WithoutDNS, []string{"-without-dns"}, false, "instruct created containers to never use weaveDNS as their nameserver") mflag.Parse() if justVersion { fmt.Printf("weave proxy %s\n", version) os.Exit(0) } if c.WithDNS && c.WithoutDNS { Log.Fatalf("Cannot use both '--with-dns' and '--without-dns' flags") } SetLogLevel(logLevel) Log.Infoln("weave proxy", version) Log.Infoln("Command line arguments:", strings.Join(os.Args[1:], " ")) p, err := proxy.NewProxy(c) if err != nil { Log.Fatalf("Could not start proxy: %s", err) } listeners := p.Listen() p.AttachExistingContainers() go p.Serve(listeners) go p.ListenAndServeStatus("/home/weave/status.sock") SignalHandlerLoop() }
func init() { flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display this help message") flag.StringVar( &logFile, []string{"f"}, "/var/log/gitlab/gitlab-shell/gitlab-shell.log", "path to gitlab-shell.log") flag.Parse() }
// doFlags defines the cmdline Usage string and parses flag options. func doFlags() { flag.Usage = func() { fmt.Fprintf(os.Stderr, " Usage: %s [OPTIONS] REGISTRY REPO [REPO...]\n", os.Args[0]) fmt.Fprintf(os.Stderr, "\n REGISTRY:\n") fmt.Fprintf(os.Stderr, "\tURL of your Docker registry; use index.docker.io for Docker Hub, use local.host to collect images from local Docker host\n") fmt.Fprintf(os.Stderr, "\n REPO:\n") fmt.Fprintf(os.Stderr, "\tOne or more repos to gather info about; if no repo is specified Collector will gather info on *all* repos in the Registry\n") fmt.Fprintf(os.Stderr, "\n Environment variables:\n") fmt.Fprintf(os.Stderr, "\tCOLLECTOR_DIR: (Required) Directory that contains the \"data\" folder with Collector default scripts, e.g., $GOPATH/src/github.com/banyanops/collector\n") fmt.Fprintf(os.Stderr, "\tCOLLECTOR_ID: ID provided by Banyan web interface to register Collector with the Banyan service\n") fmt.Fprintf(os.Stderr, "\tBANYAN_HOST_DIR: Host directory mounted into Collector/Target containers where results are stored (default: $HOME/.banyan)\n") fmt.Fprintf(os.Stderr, "\tBANYAN_DIR: (Specify only in Dockerfile) Directory in the Collector container where host directory BANYAN_HOST_DIR is mounted\n") fmt.Fprintf(os.Stderr, "\tDOCKER_{HOST,CERT_PATH,TLS_VERIFY}: If set, e.g., by docker-machine, then they take precedence over --dockerProto and --dockerAddr\n") printExampleUsage() fmt.Fprintf(os.Stderr, " Options:\n") flag.PrintDefaults() } flag.Parse() if config.COLLECTORDIR() == "" { flag.Usage() os.Exit(except.ErrorExitStatus) } if len(flag.Args()) < 1 { flag.Usage() os.Exit(except.ErrorExitStatus) } if *dockerProto != "unix" && *dockerProto != "tcp" { flag.Usage() os.Exit(except.ErrorExitStatus) } requiredDirs := []string{config.BANYANDIR(), filepath.Dir(*imageList), filepath.Dir(*repoList), *config.BanyanOutDir, collector.DefaultScriptsDir, collector.UserScriptsDir, collector.BinDir} for _, dir := range requiredDirs { blog.Debug("Creating directory: " + dir) err := fsutil.CreateDirIfNotExist(dir) if err != nil { except.Fail(err, ": Error in creating a required directory: ", dir) } } collector.RegistrySpec = flag.Arg(0) // EqualFold: case insensitive comparison if strings.EqualFold(flag.Arg(0), "local.host") { collector.LocalHost = true } //nextMaxImages = *maxImages }
func main() { var ( justVersion bool logLevel = "info" c = proxy.Config{ListenAddrs: []string{}} ) c.Version = version mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") ListVar(&c.ListenAddrs, []string{"H"}, defaultListenAddrs, "addresses on which to listen") mflag.BoolVar(&c.NoDefaultIPAM, []string{"#-no-default-ipam", "-no-default-ipalloc"}, false, "do not automatically allocate addresses for containers without a WEAVE_CIDR") mflag.BoolVar(&c.NoRewriteHosts, []string{"no-rewrite-hosts"}, false, "do not automatically rewrite /etc/hosts. Use if you need the docker IP to remain in /etc/hosts") mflag.StringVar(&c.TLSConfig.CACert, []string{"#tlscacert", "-tlscacert"}, "", "Trust certs signed only by this CA") mflag.StringVar(&c.TLSConfig.Cert, []string{"#tlscert", "-tlscert"}, "", "Path to TLS certificate file") mflag.BoolVar(&c.TLSConfig.Enabled, []string{"#tls", "-tls"}, false, "Use TLS; implied by --tls-verify") mflag.StringVar(&c.TLSConfig.Key, []string{"#tlskey", "-tlskey"}, "", "Path to TLS key file") mflag.BoolVar(&c.TLSConfig.Verify, []string{"#tlsverify", "-tlsverify"}, false, "Use TLS and verify the remote") mflag.BoolVar(&c.WithDNS, []string{"-with-dns", "w"}, false, "instruct created containers to always use weaveDNS as their nameserver") mflag.BoolVar(&c.WithoutDNS, []string{"-without-dns"}, false, "instruct created containers to never use weaveDNS as their nameserver") mflag.Parse() if justVersion { fmt.Printf("weave proxy %s\n", version) os.Exit(0) } if c.WithDNS && c.WithoutDNS { Log.Fatalf("Cannot use both '--with-dns' and '--without-dns' flags") } SetLogLevel(logLevel) Log.Infoln("weave proxy", version) Log.Infoln("Command line arguments:", strings.Join(os.Args[1:], " ")) p, err := proxy.NewProxy(c) if err != nil { Log.Fatalf("Could not start proxy: %s", err) } p.ListenAndServe() }
func main() { if reexec.Init() { return } flag.Parse() // FIXME: validate daemon flags here if *flVersion { showVersion() return } if *flDebug { os.Setenv("DEBUG", "1") } if len(flHosts) == 0 { defaultHost := os.Getenv("DOCKER_HOST") if defaultHost == "" || *flDaemon { // If we do not have a host, default to unix socket defaultHost = fmt.Sprintf("unix://%s", api.DEFAULTUNIXSOCKET) } defaultHost, err := api.ValidateHost(defaultHost) if err != nil { log.Fatal(err) } flHosts = append(flHosts, defaultHost) } if *flDaemon { mainDaemon() return } if len(flHosts) > 1 { log.Fatal("Please specify only one -H") } protoAddrParts := strings.SplitN(flHosts[0], "://", 2) var ( cli *client.DockerCli tlsConfig tls.Config ) tlsConfig.InsecureSkipVerify = true // If we should verify the server, we need to load a trusted ca if *flTlsVerify { *flTls = true certPool := x509.NewCertPool() file, err := ioutil.ReadFile(*flCa) if err != nil { log.Fatalf("Couldn't read ca cert %s: %s", *flCa, err) } certPool.AppendCertsFromPEM(file) tlsConfig.RootCAs = certPool tlsConfig.InsecureSkipVerify = false } // If tls is enabled, try to load and send client certificates if *flTls || *flTlsVerify { _, errCert := os.Stat(*flCert) _, errKey := os.Stat(*flKey) if errCert == nil && errKey == nil { *flTls = true cert, err := tls.LoadX509KeyPair(*flCert, *flKey) if err != nil { log.Fatalf("Couldn't load X509 key pair: %s. Key encrypted?", err) } tlsConfig.Certificates = []tls.Certificate{cert} } } if *flTls || *flTlsVerify { cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, nil, protoAddrParts[0], protoAddrParts[1], &tlsConfig) } else { cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, nil, protoAddrParts[0], protoAddrParts[1], nil) } if err := cli.Cmd(flag.Args()...); err != nil { if sterr, ok := err.(*utils.StatusError); ok { if sterr.Status != "" { log.Infof("%s", sterr.Status) } os.Exit(sterr.StatusCode) } log.Fatal(err) } }
func main() { flag.Usage = func() { flag.PrintDefaults() } flag.Parse() if debug { os.Setenv("DEBUG", "1") logrus.SetLevel(logrus.DebugLevel) } if flag.NArg() == 0 { flag.Usage() logrus.Fatal("no image names provided") } // make temporary working directory tempFetchRoot, err := ioutil.TempDir("", "docker-fetch-") if err != nil { logrus.Fatal(err) } refs := []*fetch.ImageRef{} for _, arg := range flag.Args() { ref := fetch.NewImageRef(arg) fmt.Fprintf(os.Stderr, "Pulling %s\n", ref) r := fetch.NewRegistry(ref.Host()) layersFetched, err := r.FetchLayers(ref, tempFetchRoot) if err != nil { logrus.Errorf("failed pulling %s, skipping: %s", ref, err) continue } logrus.Debugf("fetched %d layers for %s", len(layersFetched), ref) refs = append(refs, ref) } // marshal the "repositories" file for writing out buf, err := fetch.FormatRepositories(refs...) if err != nil { logrus.Fatal(err) } fh, err := os.Create(filepath.Join(tempFetchRoot, "repositories")) if err != nil { logrus.Fatal(err) } if _, err = fh.Write(buf); err != nil { logrus.Fatal(err) } fh.Close() logrus.Debugf("%s", fh.Name()) var output io.WriteCloser if outputStream == "-" { output = os.Stdout } else { output, err = os.Create(outputStream) if err != nil { logrus.Fatal(err) } } defer output.Close() if err = os.Chdir(tempFetchRoot); err != nil { logrus.Fatal(err) } tarStream, err := archive.Tar(".", archive.Uncompressed) if err != nil { logrus.Fatal(err) } if _, err = io.Copy(output, tarStream); err != nil { logrus.Fatal(err) } }
func main() { procs := runtime.NumCPU() // packet sniffing can block an OS thread, so we need one thread // for that plus at least one more. if procs < 2 { procs = 2 } runtime.GOMAXPROCS(procs) var ( config weave.Config justVersion bool protocolMinVersion int ifaceName string routerName string nickName string password string pktdebug bool logLevel string prof string bufSzMB int noDiscovery bool httpAddr string iprangeCIDR string ipsubnetCIDR string peerCount int dockerAPI string peers []string noDNS bool dnsDomain string dnsListenAddress string dnsTTL int dnsClientTimeout time.Duration dnsEffectiveListenAddress string iface *net.Interface ) mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.IntVar(&config.Port, []string{"#port", "-port"}, weave.Port, "router port") mflag.IntVar(&protocolMinVersion, []string{"-min-protocol-version"}, weave.ProtocolMinVersion, "minimum weave protocol version") mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to capture/inject from (disabled if blank)") mflag.StringVar(&routerName, []string{"#name", "-name"}, "", "name of router (defaults to MAC of interface)") mflag.StringVar(&nickName, []string{"#nickname", "-nickname"}, "", "nickname of peer (defaults to hostname)") mflag.StringVar(&password, []string{"#password", "-password"}, "", "network password") mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") mflag.BoolVar(&pktdebug, []string{"#pktdebug", "#-pktdebug", "-pkt-debug"}, false, "enable per-packet debug logging") mflag.StringVar(&prof, []string{"#profile", "-profile"}, "", "enable profiling and write profiles to given path") mflag.IntVar(&config.ConnLimit, []string{"#connlimit", "#-connlimit", "-conn-limit"}, 30, "connection limit (0 for unlimited)") mflag.BoolVar(&noDiscovery, []string{"#nodiscovery", "#-nodiscovery", "-no-discovery"}, false, "disable peer discovery") mflag.IntVar(&bufSzMB, []string{"#bufsz", "-bufsz"}, 8, "capture buffer size in MB") mflag.StringVar(&httpAddr, []string{"#httpaddr", "#-httpaddr", "-http-addr"}, fmt.Sprintf(":%d", weave.HTTPPort), "address to bind HTTP interface to (disabled if blank, absolute path indicates unix domain socket)") mflag.StringVar(&iprangeCIDR, []string{"#iprange", "#-iprange", "-ipalloc-range"}, "", "IP address range reserved for automatic allocation, in CIDR notation") mflag.StringVar(&ipsubnetCIDR, []string{"#ipsubnet", "#-ipsubnet", "-ipalloc-default-subnet"}, "", "subnet to allocate within by default, in CIDR notation") mflag.IntVar(&peerCount, []string{"#initpeercount", "#-initpeercount", "-init-peer-count"}, 0, "number of peers in network (for IP address allocation)") mflag.StringVar(&dockerAPI, []string{"#api", "#-api", "-docker-api"}, "", "Docker API endpoint, e.g. unix:///var/run/docker.sock") mflag.BoolVar(&noDNS, []string{"-no-dns"}, false, "disable DNS server") mflag.StringVar(&dnsDomain, []string{"-dns-domain"}, nameserver.DefaultDomain, "local domain to server requests for") mflag.StringVar(&dnsListenAddress, []string{"-dns-listen-address"}, nameserver.DefaultListenAddress, "address to listen on for DNS requests") mflag.IntVar(&dnsTTL, []string{"-dns-ttl"}, nameserver.DefaultTTL, "TTL for DNS request from our domain") mflag.DurationVar(&dnsClientTimeout, []string{"-dns-fallback-timeout"}, nameserver.DefaultClientTimeout, "timeout for fallback DNS requests") mflag.StringVar(&dnsEffectiveListenAddress, []string{"-dns-effective-listen-address"}, "", "address DNS will actually be listening, after Docker port mapping") // crude way of detecting that we probably have been started in a // container, with `weave launch` --> suppress misleading paths in // mflags error messages. if os.Args[0] == "/home/weave/weaver" { // matches the Dockerfile ENTRYPOINT os.Args[0] = "weave" mflag.CommandLine.Init("weave", mflag.ExitOnError) } mflag.Parse() peers = mflag.Args() SetLogLevel(logLevel) if justVersion { fmt.Printf("weave router %s\n", version) os.Exit(0) } Log.Println("Command line options:", options()) Log.Println("Command line peers:", peers) if protocolMinVersion < weave.ProtocolMinVersion || protocolMinVersion > weave.ProtocolMaxVersion { Log.Fatalf("--min-protocol-version must be in range [%d,%d]", weave.ProtocolMinVersion, weave.ProtocolMaxVersion) } config.ProtocolMinVersion = byte(protocolMinVersion) var err error if ifaceName != "" { iface, err := weavenet.EnsureInterface(ifaceName) if err != nil { Log.Fatal(err) } // bufsz flag is in MB config.Bridge, err = weave.NewPcap(iface, bufSzMB*1024*1024) if err != nil { Log.Fatal(err) } } if routerName == "" { if iface == nil { Log.Fatal("Either an interface must be specified with --iface or a name with -name") } routerName = iface.HardwareAddr.String() } name, err := weave.PeerNameFromUserInput(routerName) if err != nil { Log.Fatal(err) } if nickName == "" { nickName, err = os.Hostname() if err != nil { Log.Fatal(err) } } if password == "" { password = os.Getenv("WEAVE_PASSWORD") } if password == "" { Log.Println("Communication between peers is unencrypted.") } else { config.Password = []byte(password) Log.Println("Communication between peers is encrypted.") } if prof != "" { p := *profile.CPUProfile p.ProfilePath = prof p.NoShutdownHook = true defer profile.Start(&p).Stop() } config.PeerDiscovery = !noDiscovery config.Overlay = weave.NewSleeveOverlay(config.Port) if pktdebug { config.PacketLogging = packetLogging{} } else { config.PacketLogging = nopPacketLogging{} } router := weave.NewRouter(config, name, nickName) Log.Println("Our name is", router.Ourself) var dockerCli *docker.Client if dockerAPI != "" { dc, err := docker.NewClient(dockerAPI) if err != nil { Log.Fatal("Unable to start docker client: ", err) } dockerCli = dc } observeContainers := func(o docker.ContainerObserver) { if dockerCli != nil { if err = dockerCli.AddObserver(o); err != nil { Log.Fatal("Unable to start watcher", err) } } } var allocator *ipam.Allocator var defaultSubnet address.CIDR if iprangeCIDR != "" { allocator, defaultSubnet = createAllocator(router, iprangeCIDR, ipsubnetCIDR, determineQuorum(peerCount, peers)) observeContainers(allocator) } else if peerCount > 0 { Log.Fatal("--init-peer-count flag specified without --ipalloc-range") } var ( ns *nameserver.Nameserver dnsserver *nameserver.DNSServer ) if !noDNS { ns = nameserver.New(router.Ourself.Peer.Name, router.Peers, dnsDomain) ns.SetGossip(router.NewGossip("nameserver", ns)) observeContainers(ns) ns.Start() defer ns.Stop() dnsserver, err = nameserver.NewDNSServer(ns, dnsDomain, dnsListenAddress, dnsEffectiveListenAddress, uint32(dnsTTL), dnsClientTimeout) if err != nil { Log.Fatal("Unable to start dns server: ", err) } dnsserver.ActivateAndServe() defer dnsserver.Stop() } router.Start() if errors := router.ConnectionMaker.InitiateConnections(peers, false); len(errors) > 0 { Log.Fatal(ErrorMessages(errors)) } // The weave script always waits for a status call to succeed, // so there is no point in doing "weave launch --http-addr ''". // This is here to support stand-alone use of weaver. if httpAddr != "" { muxRouter := mux.NewRouter() if allocator != nil { allocator.HandleHTTP(muxRouter, defaultSubnet, dockerCli) } if ns != nil { ns.HandleHTTP(muxRouter, dockerCli) } router.HandleHTTP(muxRouter) HandleHTTP(muxRouter, version, router, allocator, defaultSubnet, ns, dnsserver) http.Handle("/", muxRouter) go listenAndServeHTTP(httpAddr, muxRouter) } SignalHandlerLoop(router) }
func main() { if reexec.Init() { return } flag.Parse() // FIXME: validate daemon flags here if *flVersion { showVersion() return } if *flLogLevel != "" { lvl, err := log.ParseLevel(*flLogLevel) if err != nil { log.Fatalf("Unable to parse logging level: %s", *flLogLevel) } initLogging(lvl) } else { initLogging(log.InfoLevel) } // -D, --debug, -l/--log-level=debug processing // When/if -D is removed this block can be deleted if *flDebug { os.Setenv("DEBUG", "1") initLogging(log.DebugLevel) } if len(flHosts) == 0 { defaultHost := os.Getenv("DOCKER_HOST") if defaultHost == "" || *flDaemon { // If we do not have a host, default to unix socket defaultHost = fmt.Sprintf("unix://%s", api.DEFAULTUNIXSOCKET) } defaultHost, err := api.ValidateHost(defaultHost) if err != nil { log.Fatal(err) } flHosts = append(flHosts, defaultHost) } setDefaultConfFlag(flTrustKey, defaultTrustKeyFile) if *flDaemon { mainDaemon() return } if len(flHosts) > 1 { log.Fatal("Please specify only one -H") } protoAddrParts := strings.SplitN(flHosts[0], "://", 2) var ( cli *client.DockerCli tlsConfig tls.Config ) tlsConfig.InsecureSkipVerify = true // Regardless of whether the user sets it to true or false, if they // specify --tlsverify at all then we need to turn on tls if flag.IsSet("-tlsverify") { *flTls = true } // If we should verify the server, we need to load a trusted ca if *flTlsVerify { certPool := x509.NewCertPool() file, err := ioutil.ReadFile(*flCa) if err != nil { log.Fatalf("Couldn't read ca cert %s: %s", *flCa, err) } certPool.AppendCertsFromPEM(file) tlsConfig.RootCAs = certPool tlsConfig.InsecureSkipVerify = false } // If tls is enabled, try to load and send client certificates if *flTls || *flTlsVerify { _, errCert := os.Stat(*flCert) _, errKey := os.Stat(*flKey) if errCert == nil && errKey == nil { *flTls = true cert, err := tls.LoadX509KeyPair(*flCert, *flKey) if err != nil { log.Fatalf("Couldn't load X509 key pair: %s. Key encrypted?", err) } tlsConfig.Certificates = []tls.Certificate{cert} } // Avoid fallback to SSL protocols < TLS1.0 tlsConfig.MinVersion = tls.VersionTLS10 } if *flTls || *flTlsVerify { cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, *flTrustKey, protoAddrParts[0], protoAddrParts[1], &tlsConfig) } else { cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, *flTrustKey, protoAddrParts[0], protoAddrParts[1], nil) } if err := cli.Cmd(flag.Args()...); err != nil { if sterr, ok := err.(*utils.StatusError); ok { if sterr.Status != "" { log.Println(sterr.Status) } os.Exit(sterr.StatusCode) } log.Fatal(err) } }
func main() { if reexec.Init() { return } // Set terminal emulation based on platform as required. stdin, stdout, stderr := term.StdStreams() initLogging(stderr) flag.Parse() // FIXME: validate daemon flags here if *flVersion { showVersion() return } if *flConfigDir != "" { cliconfig.SetConfigDir(*flConfigDir) } if *flLogLevel != "" { lvl, err := logrus.ParseLevel(*flLogLevel) if err != nil { fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", *flLogLevel) os.Exit(1) } setLogLevel(lvl) } else { setLogLevel(logrus.InfoLevel) } if *flDebug { os.Setenv("DEBUG", "1") setLogLevel(logrus.DebugLevel) } if len(flHosts) == 0 { defaultHost := os.Getenv("DOCKER_HOST") if defaultHost == "" || *flDaemon { if runtime.GOOS != "windows" { // If we do not have a host, default to unix socket defaultHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket) } else { // If we do not have a host, default to TCP socket on Windows defaultHost = fmt.Sprintf("tcp://%s:%d", opts.DefaultHTTPHost, opts.DefaultHTTPPort) } } defaultHost, err := opts.ValidateHost(defaultHost) if err != nil { if *flDaemon { logrus.Fatal(err) } else { fmt.Fprint(os.Stderr, err) } os.Exit(1) } flHosts = append(flHosts, defaultHost) } setDefaultConfFlag(flTrustKey, defaultTrustKeyFile) // Regardless of whether the user sets it to true or false, if they // specify --tlsverify at all then we need to turn on tls // *flTlsVerify can be true even if not set due to DOCKER_TLS_VERIFY env var, so we need to check that here as well if flag.IsSet("-tlsverify") || *flTlsVerify { *flTls = true } if *flDaemon { if *flHelp { flag.Usage() return } mainDaemon() return } // From here on, we assume we're a client, not a server. if len(flHosts) > 1 { fmt.Fprintf(os.Stderr, "Please specify only one -H") os.Exit(0) } protoAddrParts := strings.SplitN(flHosts[0], "://", 2) var tlsConfig *tls.Config if *flTls { tlsOptions.InsecureSkipVerify = !*flTlsVerify if !flag.IsSet("-tlscert") { if _, err := os.Stat(tlsOptions.CertFile); os.IsNotExist(err) { tlsOptions.CertFile = "" } } if !flag.IsSet("-tlskey") { if _, err := os.Stat(tlsOptions.KeyFile); os.IsNotExist(err) { tlsOptions.KeyFile = "" } } var err error tlsConfig, err = tlsconfig.Client(tlsOptions) if err != nil { fmt.Fprintln(stderr, err) os.Exit(1) } } cli := client.NewDockerCli(stdin, stdout, stderr, *flTrustKey, protoAddrParts[0], protoAddrParts[1], tlsConfig) if err := cli.Cmd(flag.Args()...); err != nil { if sterr, ok := err.(client.StatusError); ok { if sterr.Status != "" { fmt.Fprintln(cli.Err(), sterr.Status) os.Exit(1) } os.Exit(sterr.StatusCode) } fmt.Fprintln(cli.Err(), err) os.Exit(1) } }
func main() { procs := runtime.NumCPU() // packet sniffing can block an OS thread, so we need one thread // for that plus at least one more. if procs < 2 { procs = 2 } runtime.GOMAXPROCS(procs) var ( config weave.Config justVersion bool protocolMinVersion int ifaceName string routerName string nickName string password string wait int pktdebug bool logLevel string prof string bufSzMB int noDiscovery bool httpAddr string iprangeCIDR string ipsubnetCIDR string peerCount int apiPath string peers []string noDNS bool dnsDomain string dnsPort int dnsTTL int dnsClientTimeout time.Duration ) mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.IntVar(&config.Port, []string{"#port", "-port"}, weave.Port, "router port") mflag.IntVar(&protocolMinVersion, []string{"-min-protocol-version"}, weave.ProtocolMinVersion, "minimum weave protocol version") mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to capture/inject from (disabled if blank)") mflag.StringVar(&routerName, []string{"#name", "-name"}, "", "name of router (defaults to MAC of interface)") mflag.StringVar(&nickName, []string{"#nickname", "-nickname"}, "", "nickname of peer (defaults to hostname)") mflag.StringVar(&password, []string{"#password", "-password"}, "", "network password") mflag.IntVar(&wait, []string{"#wait", "-wait"}, -1, "number of seconds to wait for interface to come up (0=don't wait, -1=wait forever)") mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") mflag.BoolVar(&pktdebug, []string{"#pktdebug", "#-pktdebug", "-pkt-debug"}, false, "enable per-packet debug logging") mflag.StringVar(&prof, []string{"#profile", "-profile"}, "", "enable profiling and write profiles to given path") mflag.IntVar(&config.ConnLimit, []string{"#connlimit", "#-connlimit", "-conn-limit"}, 30, "connection limit (0 for unlimited)") mflag.BoolVar(&noDiscovery, []string{"#nodiscovery", "#-nodiscovery", "-no-discovery"}, false, "disable peer discovery") mflag.IntVar(&bufSzMB, []string{"#bufsz", "-bufsz"}, 8, "capture buffer size in MB") mflag.StringVar(&httpAddr, []string{"#httpaddr", "#-httpaddr", "-http-addr"}, fmt.Sprintf(":%d", weave.HTTPPort), "address to bind HTTP interface to (disabled if blank, absolute path indicates unix domain socket)") mflag.StringVar(&iprangeCIDR, []string{"#iprange", "#-iprange", "-ipalloc-range"}, "", "IP address range reserved for automatic allocation, in CIDR notation") mflag.StringVar(&ipsubnetCIDR, []string{"#ipsubnet", "#-ipsubnet", "-ipalloc-default-subnet"}, "", "subnet to allocate within by default, in CIDR notation") mflag.IntVar(&peerCount, []string{"#initpeercount", "#-initpeercount", "-init-peer-count"}, 0, "number of peers in network (for IP address allocation)") mflag.StringVar(&apiPath, []string{"#api", "-api"}, "unix:///var/run/docker.sock", "Path to Docker API socket") mflag.BoolVar(&noDNS, []string{"-no-dns"}, false, "disable DNS server") mflag.StringVar(&dnsDomain, []string{"-dns-domain"}, nameserver.DefaultDomain, "local domain to server requests for") mflag.IntVar(&dnsPort, []string{"-dns-port"}, nameserver.DefaultPort, "port to listen on for DNS requests") mflag.IntVar(&dnsTTL, []string{"-dns-ttl"}, nameserver.DefaultTTL, "TTL for DNS request from our domain") mflag.DurationVar(&dnsClientTimeout, []string{"-dns-fallback-timeout"}, nameserver.DefaultClientTimeout, "timeout for fallback DNS requests") mflag.Parse() peers = mflag.Args() SetLogLevel(logLevel) if justVersion { fmt.Printf("weave router %s\n", version) os.Exit(0) } Log.Println("Command line options:", options()) Log.Println("Command line peers:", peers) if protocolMinVersion < weave.ProtocolMinVersion || protocolMinVersion > weave.ProtocolMaxVersion { Log.Fatalf("--min-protocol-version must be in range [%d,%d]", weave.ProtocolMinVersion, weave.ProtocolMaxVersion) } config.ProtocolMinVersion = byte(protocolMinVersion) var err error if ifaceName != "" { config.Iface, err = weavenet.EnsureInterface(ifaceName, wait) if err != nil { Log.Fatal(err) } } if routerName == "" { if config.Iface == nil { Log.Fatal("Either an interface must be specified with --iface or a name with -name") } routerName = config.Iface.HardwareAddr.String() } name, err := weave.PeerNameFromUserInput(routerName) if err != nil { Log.Fatal(err) } if nickName == "" { nickName, err = os.Hostname() if err != nil { Log.Fatal(err) } } if password == "" { password = os.Getenv("WEAVE_PASSWORD") } if password == "" { Log.Println("Communication between peers is unencrypted.") } else { config.Password = []byte(password) Log.Println("Communication between peers is encrypted.") } if prof != "" { p := *profile.CPUProfile p.ProfilePath = prof p.NoShutdownHook = true defer profile.Start(&p).Stop() } config.BufSz = bufSzMB * 1024 * 1024 config.LogFrame = logFrameFunc(pktdebug) config.PeerDiscovery = !noDiscovery router := weave.NewRouter(config, name, nickName) Log.Println("Our name is", router.Ourself) dockerCli, err := docker.NewClient(apiPath) if err != nil { Log.Fatal("Unable to start docker client: ", err) } var allocator *ipam.Allocator var defaultSubnet address.CIDR if iprangeCIDR != "" { allocator, defaultSubnet = createAllocator(router, iprangeCIDR, ipsubnetCIDR, determineQuorum(peerCount, peers)) if err = dockerCli.AddObserver(allocator); err != nil { Log.Fatal("Unable to start watcher", err) } } else if peerCount > 0 { Log.Fatal("--init-peer-count flag specified without --ipalloc-range") } var ( ns *nameserver.Nameserver dnsserver *nameserver.DNSServer ) if !noDNS { ns = nameserver.New(router.Ourself.Peer.Name, router.Peers, dockerCli, dnsDomain) ns.SetGossip(router.NewGossip("nameserver", ns)) if err = dockerCli.AddObserver(ns); err != nil { Log.Fatal("Unable to start watcher", err) } ns.Start() defer ns.Stop() dnsserver, err = nameserver.NewDNSServer(ns, dnsDomain, dnsPort, uint32(dnsTTL), dnsClientTimeout) if err != nil { Log.Fatal("Unable to start dns server: ", err) } dnsserver.ActivateAndServe() defer dnsserver.Stop() } router.Start() if errors := router.ConnectionMaker.InitiateConnections(peers, false); len(errors) > 0 { Log.Fatal(errorMessages(errors)) } // The weave script always waits for a status call to succeed, // so there is no point in doing "weave launch --http-addr ''". // This is here to support stand-alone use of weaver. if httpAddr != "" { go handleHTTP(router, httpAddr, allocator, defaultSubnet, dockerCli, ns, dnsserver) } SignalHandlerLoop(router) }
func main() { var ( justVersion bool dockerCli *docker.Client ifaceName string apiPath string domain string dnsPort int httpIfaceName string httpPort int wait int ttl int negTTL int timeout int udpbuf int fallback string refreshInterval int relevantTime int maxAnswers int cacheLen int cacheDisabled bool watch bool logLevel string err error ) mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to use for multicast") mflag.StringVar(&apiPath, []string{"#api", "-api"}, "unix:///var/run/docker.sock", "path to Docker API socket") mflag.StringVar(&domain, []string{"#domain", "-domain"}, weavedns.DefaultLocalDomain, "local domain (ie, 'weave.local.')") mflag.IntVar(&wait, []string{"#wait", "-wait"}, -1, "number of seconds to wait for interfaces to come up (0=don't wait, -1=wait forever)") mflag.IntVar(&dnsPort, []string{"#dnsport", "#-dnsport", "-dns-port"}, weavedns.DefaultServerPort, "port to listen to DNS requests") mflag.StringVar(&httpIfaceName, []string{"#httpiface", "#-httpiface", "-http-iface"}, "", "interface on which to listen for HTTP requests (empty string means listen on all interfaces)") mflag.IntVar(&httpPort, []string{"#httpport", "#-httpport", "-http-port"}, weavedns.DefaultHTTPPort, "port to listen to HTTP requests") mflag.IntVar(&cacheLen, []string{"#cache", "-cache"}, weavedns.DefaultCacheLen, "cache length") mflag.IntVar(&ttl, []string{"#ttl", "-ttl"}, weavedns.DefaultLocalTTL, "TTL (in secs) for responses for local names") mflag.BoolVar(&watch, []string{"#watch", "-watch"}, true, "watch the docker socket for container events") mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") // advanced options mflag.IntVar(&negTTL, []string{"#neg-ttl", "-neg-ttl"}, 0, "negative TTL (in secs) for unanswered queries for local names (0=same value as --ttl") mflag.IntVar(&refreshInterval, []string{"#refresh", "-refresh"}, weavedns.DefaultRefreshInterval, "refresh interval (in secs) for local names (0=disable)") mflag.IntVar(&maxAnswers, []string{"#max-answers", "#-max-answers", "-dns-max-answers"}, weavedns.DefaultMaxAnswers, "maximum number of answers returned to clients (0=unlimited)") mflag.IntVar(&relevantTime, []string{"#relevant", "-relevant"}, weavedns.DefaultRelevantTime, "life time for info in the absence of queries (in secs)") mflag.IntVar(&udpbuf, []string{"#udpbuf", "#-udpbuf", "-dns-udpbuf"}, weavedns.DefaultUDPBuflen, "UDP buffer length for DNS") mflag.IntVar(&timeout, []string{"#timeout", "#-timeout", "-dns-timeout"}, weavedns.DefaultTimeout, "timeout for resolutions (in millisecs)") mflag.BoolVar(&cacheDisabled, []string{"#no-cache", "-no-cache"}, false, "disable the cache") mflag.StringVar(&fallback, []string{"#fallback", "#-fallback", "-dns-fallback"}, "", "force a fallback server (ie, '8.8.8.8:53') (instead of /etc/resolv.conf values)") mflag.Parse() if justVersion { fmt.Printf("weave DNS %s\n", version) os.Exit(0) } SetLogLevel(logLevel) Log.Infof("[main] WeaveDNS version %s", version) // first thing in log: the version var iface *net.Interface if ifaceName != "" { var err error Log.Infoln("[main] Waiting for mDNS interface", ifaceName, "to come up") iface, err = weavenet.EnsureInterface(ifaceName, wait) if err != nil { Log.Fatal(err) } else { Log.Infoln("[main] Interface", ifaceName, "is up") } } var httpIP string if httpIfaceName == "" { httpIP = "0.0.0.0" } else { Log.Infoln("[main] Waiting for HTTP interface", httpIfaceName, "to come up") httpIface, err := weavenet.EnsureInterface(httpIfaceName, wait) if err != nil { Log.Fatal(err) } Log.Infoln("[main] Interface", httpIfaceName, "is up") addrs, err := httpIface.Addrs() if err != nil { Log.Fatal(err) } if len(addrs) == 0 { Log.Fatal("[main] No addresses on HTTP interface") } ip, _, err := net.ParseCIDR(addrs[0].String()) if err != nil { Log.Fatal(err) } httpIP = ip.String() } httpAddr := net.JoinHostPort(httpIP, strconv.Itoa(httpPort)) zoneConfig := weavedns.ZoneConfig{ Domain: domain, Iface: iface, LocalTTL: ttl, RefreshInterval: refreshInterval, RelevantTime: relevantTime, } zone, err := weavedns.NewZoneDb(zoneConfig) if err != nil { Log.Fatal("[main] Unable to initialize the Zone database", err) } if err := zone.Start(); err != nil { Log.Fatal("[main] Unable to start the Zone database", err) } defer zone.Stop() dockerCli, err = docker.NewClient(apiPath) if err != nil { Log.Fatal("[main] Unable to start docker client: ", err) } if watch { err := dockerCli.AddObserver(zone) if err != nil { Log.Fatal("[main] Unable to start watcher", err) } } srvConfig := weavedns.DNSServerConfig{ Zone: zone, Port: dnsPort, CacheLen: cacheLen, LocalTTL: ttl, CacheNegLocalTTL: negTTL, MaxAnswers: maxAnswers, Timeout: timeout, UDPBufLen: udpbuf, CacheDisabled: cacheDisabled, } if len(fallback) > 0 { fallbackHost, fallbackPort, err := net.SplitHostPort(fallback) if err != nil { Log.Fatal("[main] Could not parse fallback host and port", err) } srvConfig.UpstreamCfg = &dns.ClientConfig{Servers: []string{fallbackHost}, Port: fallbackPort} Log.Debugf("[main] DNS fallback at %s:%s", fallbackHost, fallbackPort) } srv, err := weavedns.NewDNSServer(srvConfig) if err != nil { Log.Fatal("[main] Failed to initialize the WeaveDNS server", err) } httpListener, err := net.Listen("tcp", httpAddr) if err != nil { Log.Fatal("[main] Unable to create http listener: ", err) } Log.Infoln("[main] HTTP API listening on", httpAddr) go SignalHandlerLoop(srv) go weavedns.ServeHTTP(httpListener, version, srv, dockerCli) err = srv.Start() if err != nil { Log.Fatal("[main] Failed to start the WeaveDNS server: ", err) } srv.ActivateAndServe() }