コード例 #1
0
ファイル: flags.go プロジェクト: colebrumley/docker
func init() {
	var placeholderTrustKey string
	// TODO use flag flag.String([]string{"i", "-identity"}, "", "Path to libtrust key file")
	flTrustKey = &placeholderTrustKey

	flCa = flag.String([]string{"-tlscacert"}, filepath.Join(dockerCertPath, defaultCaFile), "Trust certs signed only by this CA")
	flCert = flag.String([]string{"-tlscert"}, filepath.Join(dockerCertPath, defaultCertFile), "Path to TLS certificate file")
	flKey = flag.String([]string{"-tlskey"}, filepath.Join(dockerCertPath, defaultKeyFile), "Path to TLS key file")
	opts.HostListVar(&flHosts, []string{"H", "-host"}, "Daemon socket(s) to connect to")

	flag.Usage = func() {
		fmt.Fprint(os.Stdout, "Usage: docker [OPTIONS] COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nOptions:\n")

		flag.CommandLine.SetOutput(os.Stdout)
		flag.PrintDefaults()

		help := "\nCommands:\n"

		sort.Sort(byName(dockerCommands))

		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)
	}
}
コード例 #2
0
ファイル: flags.go プロジェクト: bbinet/docker
func init() {
	flCa = flag.String([]string{"-tlscacert"}, filepath.Join(dockerCertPath, defaultCaFile), "Trust only remotes providing a certificate signed by the CA given here")
	flCert = flag.String([]string{"-tlscert"}, filepath.Join(dockerCertPath, defaultCertFile), "Path to TLS certificate file")
	flKey = flag.String([]string{"-tlskey"}, filepath.Join(dockerCertPath, defaultKeyFile), "Path to TLS key file")
	opts.HostListVar(&flHosts, []string{"H", "-host"}, "The socket(s) to bind to in daemon mode or connect to in client mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.")

	flag.Usage = func() {
		fmt.Fprint(os.Stderr, "Usage: docker [OPTIONS] COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nOptions:\n")

		flag.PrintDefaults()

		help := "\nCommands:\n"

		for _, command := range [][]string{
			{"attach", "Attach to a running container"},
			{"build", "Build an image from a Dockerfile"},
			{"commit", "Create a new image from a container's changes"},
			{"cp", "Copy files/folders from a container's filesystem to the host path"},
			{"create", "Create a new container"},
			{"diff", "Inspect changes on a container's filesystem"},
			{"events", "Get real time events from the server"},
			{"exec", "Run a command in an existing container"},
			{"export", "Stream the contents of a container as a tar archive"},
			{"history", "Show the history of an image"},
			{"images", "List images"},
			{"import", "Create a new filesystem image from the contents of a tarball"},
			{"info", "Display system-wide information"},
			{"inspect", "Return low-level information on a container"},
			{"kill", "Kill a running container"},
			{"load", "Load an image from a tar archive"},
			{"login", "Register or log in to a Docker registry server"},
			{"logout", "Log out from a Docker registry server"},
			{"logs", "Fetch the logs of a container"},
			{"port", "Lookup the public-facing port that is NAT-ed to PRIVATE_PORT"},
			{"pause", "Pause all processes within a container"},
			{"ps", "List containers"},
			{"pull", "Pull an image or a repository from a Docker registry server"},
			{"push", "Push an image or a repository to a Docker registry server"},
			{"restart", "Restart a running container"},
			{"rm", "Remove one or more containers"},
			{"rmi", "Remove one or more images"},
			{"run", "Run a command in a new container"},
			{"save", "Save an image to a tar archive"},
			{"search", "Search for an image on the Docker Hub"},
			{"start", "Start a stopped container"},
			{"stop", "Stop a running container"},
			{"tag", "Tag an image into a repository"},
			{"top", "Lookup the running processes of a container"},
			{"unpause", "Unpause a paused container"},
			{"version", "Show the Docker version information"},
			{"wait", "Block until a container stops, then print its exit code"},
		} {
			help += fmt.Sprintf("    %-10.10s%s\n", command[0], command[1])
		}
		help += "\nRun 'docker COMMAND --help' for more information on a command."
		fmt.Fprintf(os.Stderr, "%s\n", help)
	}
}
コード例 #3
0
ファイル: flags.go プロジェクト: rhopman/docker
func init() {
	flCa = flag.String([]string{"-tlscacert"}, filepath.Join(dockerConfDir, defaultCaFile), "Trust only remotes providing a certificate signed by the CA given here")
	flCert = flag.String([]string{"-tlscert"}, filepath.Join(dockerConfDir, defaultCertFile), "Path to TLS certificate file")
	flKey = flag.String([]string{"-tlskey"}, filepath.Join(dockerConfDir, defaultKeyFile), "Path to TLS key file")

	flag.Var(&flDns, []string{"#dns", "-dns"}, "Force Docker to use specific DNS servers")
	flag.Var(&flDnsSearch, []string{"-dns-search"}, "Force Docker to use specific DNS search domains")
	flag.Var(&flHosts, []string{"H", "-host"}, "The socket(s) to bind to in daemon mode\nspecified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.")
	flag.Var(&flGraphOpts, []string{"-storage-opt"}, "Set storage driver options")
}
コード例 #4
0
ファイル: flags.go プロジェクト: bkeyoumarsi/docker
func init() {
	if dockerCertPath == "" {
		dockerCertPath = cliconfig.ConfigDir()
	}
}

func getDaemonConfDir() string {
	// TODO: update for Windows daemon
	if runtime.GOOS == "windows" {
		return cliconfig.ConfigDir()
	}
	return "/etc/docker"
}

var (
	flConfigDir = flag.String([]string{"-config"}, cliconfig.ConfigDir(), "Location of client config files")
	flVersion   = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
	flDaemon    = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
	flDebug     = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flLogLevel  = flag.String([]string{"l", "-log-level"}, "info", "Set the logging level")
	flTls       = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by --tlsverify")
	flHelp      = flag.Bool([]string{"h", "-help"}, false, "Print usage")
	flTlsVerify = flag.Bool([]string{"-tlsverify"}, dockerTlsVerify, "Use TLS and verify the remote")

	// these are initialized in init() below since their default values depend on dockerCertPath which isn't fully initialized until init() runs
	tlsOptions tlsconfig.Options
	flTrustKey *string
	flHosts    []string
)

func setDefaultConfFlag(flag *string, def string) {
コード例 #5
0
ファイル: runscripts.go プロジェクト: hopkings2008/collector
package collector

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"strings"

	config "github.com/banyanops/collector/config"
	blog "github.com/ccpaging/log4go"
	flag "github.com/docker/docker/pkg/mflag"
)

var (
	//userScriptsDir    = flag.String([]string{"userscriptsdir"}, config.BANYANDIR()+"/hosttarget/userscripts", "Directory with all user-specified scripts")
	UserScriptStore   = flag.String([]string{"u", "-userscriptstore"}, config.COLLECTORDIR()+"/data/userscripts", "Directory with all user-specified scripts")
	UserScriptsDir    = config.BANYANDIR() + "/hosttarget/userscripts"
	DefaultScriptsDir = config.BANYANDIR() + "/hosttarget/defaultscripts"
	BinDir            = config.BANYANDIR() + "/hosttarget/bin"
)

const (
	PKGEXTRACTSCRIPT = "pkgextractscript.sh"
)

func parsePkgExtractOutput(output []byte, imageID ImageIDType) (imageDataInfo []ImageDataInfo, err error) {
	type PkgInfo struct {
		Pkg, Version, Architecture string
	}

	var outInfo struct {
		DistroName string
コード例 #6
0
ファイル: flags.go プロジェクト: rhopman/docker
	dockerConfDir = os.Getenv("DOCKER_CONFIG")
)

func init() {
	if dockerConfDir == "" {
		dockerConfDir = filepath.Join(os.Getenv("HOME"), ".docker")
	}
}

var (
	flVersion            = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
	flDaemon             = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
	flGraphOpts          opts.ListOpts
	flDebug              = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flAutoRestart        = flag.Bool([]string{"r", "-restart"}, true, "Restart previously running containers")
	bridgeName           = flag.String([]string{"b", "-bridge"}, "", "Attach containers to a pre-existing network bridge\nuse 'none' to disable container networking")
	bridgeIp             = flag.String([]string{"#bip", "-bip"}, "", "Use this CIDR notation address for the network bridge's IP, not compatible with -b")
	pidfile              = flag.String([]string{"p", "-pidfile"}, "/var/run/docker.pid", "Path to use for daemon PID file")
	flRoot               = flag.String([]string{"g", "-graph"}, "/var/lib/docker", "Path to use as the root of the Docker runtime")
	flSocketGroup        = flag.String([]string{"G", "-group"}, "docker", "Group to assign the unix socket specified by -H when running in daemon mode\nuse '' (the empty string) to disable setting of a group")
	flEnableCors         = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
	flDns                = opts.NewListOpts(opts.ValidateIPAddress)
	flDnsSearch          = opts.NewListOpts(opts.ValidateDnsSearch)
	flEnableIptables     = flag.Bool([]string{"#iptables", "-iptables"}, true, "Enable Docker's addition of iptables rules")
	flEnableIpForward    = flag.Bool([]string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
	flDefaultIp          = flag.String([]string{"#ip", "-ip"}, "0.0.0.0", "Default IP address to use when binding container ports")
	flInterContainerComm = flag.Bool([]string{"#icc", "-icc"}, true, "Enable inter-container communication")
	flGraphDriver        = flag.String([]string{"s", "-storage-driver"}, "", "Force the Docker runtime to use a specific storage driver")
	flExecDriver         = flag.String([]string{"e", "-exec-driver"}, "native", "Force the Docker runtime to use a specific exec driver")
	flHosts              = opts.NewListOpts(api.ValidateHost)
	flMtu                = flag.Int([]string{"#mtu", "-mtu"}, 0, "Set the containers network MTU\nif no value is provided: default to the default route MTU or 1500 if no default route is available")
コード例 #7
0
ファイル: flags.go プロジェクト: choldrim/docker
	"fmt"
	"os"

	flag "github.com/docker/docker/pkg/mflag"
)

type command struct {
	name        string
	description string
}

type byName []command

var (
	flDaemon   = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
	flHost     = flag.String([]string{"H", "-Host"}, "", "Daemon socket to connect to")
	flLogLevel = flag.String([]string{"l", "-log-level"}, "info", "Set the logging level")
	flDebug    = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flHelp     = flag.Bool([]string{"h", "-help"}, false, "Print usage")

	dnetCommands = []command{
		{"network", "Network management commands"},
	}
)

func init() {
	flag.Usage = func() {
		fmt.Fprint(os.Stdout, "Usage: dnet [OPTIONS] COMMAND [arg...]\n\nA self-sufficient runtime for container networking.\n\nOptions:\n")

		flag.CommandLine.SetOutput(os.Stdout)
		flag.PrintDefaults()
コード例 #8
0
ファイル: flags.go プロジェクト: baoruxing/docker
var (
	dockerCertPath  = os.Getenv("DOCKER_CERT_PATH")
	dockerTlsVerify = os.Getenv("DOCKER_TLS_VERIFY") != ""
)

func init() {
	if dockerCertPath == "" {
		dockerCertPath = filepath.Join(os.Getenv("HOME"), ".docker")
	}
}

var (
	flVersion     = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
	flDaemon      = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
	flDebug       = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flSocketGroup = flag.String([]string{"G", "-group"}, "docker", "Group to assign the unix socket specified by -H when running in daemon mode\nuse '' (the empty string) to disable setting of a group")
	flEnableCors  = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
	flTls         = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by tls-verify flags")
	flTlsVerify   = flag.Bool([]string{"-tlsverify"}, dockerTlsVerify, "Use TLS and verify the remote (daemon: verify client, client: verify daemon)")

	// these are initialized in init() below since their default values depend on dockerCertPath which isn't fully initialized until init() runs
	flTrustKey *string
	flCa       *string
	flCert     *string
	flKey      *string
	flHosts    []string
)

func init() {
	// placeholder for trust key flag
	trustKeyDefault := filepath.Join(dockerCertPath, defaultTrustKeyFile)
コード例 #9
0
	gcr "github.com/banyanops/collector/gcr"
	flag "github.com/docker/docker/pkg/mflag"
)

const ()

var (
	// HubAPI indicates whether to use the Docker Hub API.
	HubAPI bool
	// LocalHost indicates whether to collect images from local host
	LocalHost     bool
	HTTPSRegistry = flag.Bool([]string{"-registryhttps"}, true,
		"Set to false if registry does not need HTTPS (SSL/TLS)")
	AuthRegistry = flag.Bool([]string{"-registryauth"}, true,
		"Set to false if registry does not need authentication")
	RegistryProto = flag.String([]string{"-registryproto"}, "v1",
		"Select the registry protocol to use: v1, v2, quay")
	RegistryTokenAuth = flag.Bool([]string{"-registrytokenauth"}, false,
		"Registry uses v1 Token Auth, e.g., Docker Hub, Google Container Registry")
	RegistryTLSNoVerify = flag.Bool([]string{"-registrytlsnoverify"}, false,
		"True to trust the registry without verifying certificate")
	GCEMetadata = flag.Bool([]string{"-gce-metadata"}, false,
		"True to query GCE instance metadata for Docker credentials")
	GCEKeyFile = flag.String([]string{"-gce-key-file"}, "",
		"Set to the pathname of the GCE service account JSON key")
	// registryspec is the host.domainname of the registry
	RegistrySpec string
	// registryAPIURL is the http(s)://[user:password@]host.domainname of the registry
	RegistryAPIURL string
	// XRegistryAuth is the base64-encoded AuthConfig object (for X-Registry-Auth HTTP request header)
	XRegistryAuth string
	// BasicAuth is the base64-encoded Auth field read from $HOME/.dockercfg
コード例 #10
0
ファイル: main.go プロジェクト: TheRemoteLab/collector
	flag "github.com/docker/docker/pkg/mflag"
)

const (
	// Console logging level
	CONSOLELOGLEVEL = blog.INFO
	// File logging level
	FILELOGLEVEL = blog.FINEST
	// Number of docker images to process in a single batch.
	IMAGEBATCH = 5
)

var (
	LOGFILENAME = config.BANYANDIR() + "/hostcollector/collector.log"
	fileLog     = flag.Bool([]string{"-filelog"}, false, "Log output to "+LOGFILENAME)
	imageList   = flag.String([]string{"#-imagelist"}, config.BANYANDIR()+"/hostcollector/imagelist",
		"List of previously collected images (file)")
	repoList = flag.String([]string{"r", "-repolist"}, config.BANYANDIR()+"/hostcollector/repolist",
		"File containing list of repos to process")

	// Configuration parameters for speed/efficiency
	removeThresh = flag.Int([]string{"-removethresh"}, 5,
		"Number of images that get pulled before removal")
	maxImages = flag.Int([]string{"-maximages"}, 0, "Maximum number of new images to process per repository (0=unlimited)")
	//nextMaxImages int
	poll = flag.Int64([]string{"p", "-poll"}, 60, "Polling interval in seconds")

	// Docker remote API related parameters
	dockerProto = flag.String([]string{"-dockerproto"}, "unix",
		"Socket protocol for Docker Remote API (\"unix\" or \"tcp\")")
	dockerAddr = flag.String([]string{"-dockeraddr"}, "/var/run/docker.sock",
		"Address of Docker remote API socket (filepath or IP:port)")
コード例 #11
0
ファイル: flags.go プロジェクト: NERSC/docker
		dockerCertPath = filepath.Join(getHomeDir(), ".docker")
	}
}

func getHomeDir() string {
	if runtime.GOOS == "windows" {
		return os.Getenv("USERPROFILE")
	}
	return os.Getenv("HOME")
}

var (
	flVersion     = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
	flDaemon      = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
	flDebug       = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flSocketGroup = flag.String([]string{"G", "-group"}, "docker", "Group to assign the unix socket specified by -H when running in daemon mode\nuse '' (the empty string) to disable setting of a group")
	flLogLevel    = flag.String([]string{"l", "-log-level"}, "info", "Set the logging level")
	flEnableCors  = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
	flTls         = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by --tlsverify flag")
	flTlsVerify   = flag.Bool([]string{"-tlsverify"}, dockerTlsVerify, "Use TLS and verify the remote (daemon: verify client, client: verify daemon)")

	// these are initialized in init() below since their default values depend on dockerCertPath which isn't fully initialized until init() runs
	flTrustKey *string
	flCa       *string
	flCert     *string
	flKey      *string
	flHosts    []string
)

func init() {
	// placeholder for trust key flag
コード例 #12
0
ファイル: main.go プロジェクト: pkgr/scaleway-cli
func main() {
	config, cfgErr := getConfig()
	if cfgErr != nil && !os.IsNotExist(cfgErr) {
		log.Fatalf("Unable to open .scwrc config file: %v", cfgErr)
	}

	if config != nil {
		flAPIEndPoint = flag.String([]string{"-api-endpoint"}, config.APIEndPoint, "Set the API endpoint")
	}
	flag.Parse()

	if *flVersion {
		showVersion()
		return
	}

	if flAPIEndPoint != nil {
		os.Setenv("scaleway_api_endpoint", *flAPIEndPoint)
	}

	if *flSensitive {
		os.Setenv("SCW_SENSITIVE", "1")
	}

	if *flDebug {
		os.Setenv("DEBUG", "1")
	}

	initLogging(os.Getenv("DEBUG") != "")

	args := flag.Args()
	if len(args) < 1 {
		usage()
	}
	name := args[0]

	args = args[1:]

	for _, cmd := range cmds.Commands {
		if cmd.Name() == name {
			cmd.Flag.SetOutput(ioutil.Discard)
			err := cmd.Flag.Parse(args)
			if err != nil {
				log.Fatalf("usage: scw %s", cmd.UsageLine)
			}
			if cmd.Name() != "login" && cmd.Name() != "help" && cmd.Name() != "version" {
				if cfgErr != nil {
					if name != "login" && config == nil {
						fmt.Fprintf(os.Stderr, "You need to login first: 'scw login'\n")
						os.Exit(1)
					}
				}
				api, err := getScalewayAPI()
				if err != nil {
					log.Fatalf("unable to initialize scw api: %s", err)
				}
				cmd.API = api
			}
			cmd.Exec(cmd, cmd.Flag.Args())
			if cmd.API != nil {
				cmd.API.Sync()
			}
			os.Exit(0)
		}
	}

	log.Fatalf("scw: unknown subcommand %s\nRun 'scw help' for usage.", name)
}
コード例 #13
0
ファイル: config.go プロジェクト: xmountainx/sshpiper
func initConfig() {
	configfile := mflag.String([]string{"-config"}, "/etc/sshpiperd.conf", "Config file path. Note: any option will be overwrite if it is set by commandline")

	mflag.StringVar(&config.ListenAddr, []string{"l", "-listen_addr"}, "0.0.0.0", "Listening Address")
	mflag.UintVar(&config.Port, []string{"p", "-port"}, 2222, "Listening Port")
	mflag.StringVar(&config.WorkingDir, []string{"w", "-working_dir"}, "/var/sshpiper", "Working Dir")
	mflag.StringVar(&config.PiperKeyFile, []string{"i", "-server_key"}, "/etc/ssh/ssh_host_rsa_key", "Key file for SSH Piper")
	mflag.StringVar(&config.Challenger, []string{"c", "-challenger"}, "", "Additional challenger name, e.g. pam, emtpy for no additional challenge")
	mflag.StringVar(&config.Logfile, []string{"-log"}, "", "Logfile path. Leave emtpy or any error occurs will fall back to stdout")
	mflag.BoolVar(&config.AllowBadUsername, []string{"-allow_bad_username"}, false, "disable username check while search the working dir")
	mflag.BoolVar(&config.ShowHelp, []string{"h", "-help"}, false, "Print help and exit")
	mflag.BoolVar(&config.ShowVersion, []string{"-version"}, false, "Print version and exit")

	mflag.Parse()

	if _, err := os.Stat(*configfile); os.IsNotExist(err) {
		if !mflag.IsSet("-config") {
			*configfile = ""
		} else {
			logger.Fatalf("config file %v not found", *configfile)
		}
	}

	gconf, err := globalconf.NewWithOptions(&globalconf.Options{
		Filename:  *configfile,
		EnvPrefix: "SSHPIPERD_",
	})

	if err != nil { // this error will happen only if file error
		logger.Fatalln("load config file error %v: %v", *configfile, err)
	}

	// build a dummy flag set for globalconf to parse
	fs := flag.NewFlagSet("", flag.ContinueOnError)

	ignoreSet := make(map[string]bool)
	mflag.Visit(func(f *mflag.Flag) {
		for _, n := range f.Names {
			ignoreSet[n] = true
		}
	})

	// should be ignored
	ignoreSet["-help"] = true
	ignoreSet["-version"] = true

	mflag.VisitAll(func(f *mflag.Flag) {
		for _, n := range f.Names {
			if len(n) < 2 {
				continue
			}

			if !ignoreSet[n] {
				n = strings.TrimPrefix(n, "-")
				fs.Var(f.Value, n, f.Usage)
			}
		}
	})

	gconf.ParseSet("", fs)
}
コード例 #14
0
ファイル: config.go プロジェクト: hopkings2008/collector
			return os.Getenv("BANYAN_DIR")
		}
		return BANYANHOSTDIR()
	}
	COLLECTORDIR = func() string {
		if os.Getenv("COLLECTOR_DIR") == "" {
			fmt.Fprintf(os.Stderr, "Please set the environment variable COLLECTOR_DIR to the parent")
			fmt.Fprintf(os.Stderr, " of the \"data\" scripts directory...\n\n")
			//printExampleUsage()
			//fmt.Fprintf(os.Stderr, "  e.g.,\tcd COLLECTOR_SOURCE_DIRECTORY\n")
			//fmt.Fprintf(os.Stderr, "\tsudo COLLECTOR_DIR=$PWD collector [options] REGISTRY [REPO1 REPO2 ...]\n\n")
			return ""
		}
		return os.Getenv("COLLECTOR_DIR")
	}
	BanyanOutDir = flag.String([]string{"#-banyanoutdir"}, BANYANDIR()+"/hostcollector/banyanout",
		"Output directory for collected data")
	// Dests is setup as a flag when main calls DefineDestsFlag().
	Dests *string

	// BanyanUpdate is a function to log interesting updates as collector execution proceeds.
	BanyanUpdate BanyanUpdateFunc = func(status ...string) {}
)

type BanyanUpdateFunc func(status ...string)

// DefineDestsFlag is called by the importing package, e.g., main, to create the dests flag.
func DefineDestsFlag(def string) {
	Dests = flag.String([]string{"d", "-dests"}, def,
		"One or more ',' separated destinations for output generated by scripts. e.g., file or file,custom")
}
コード例 #15
0
ファイル: main.go プロジェクト: awesome-docker/scaleway-cli
// Start is the entrypoint
func Start(rawArgs []string, streams *commands.Streams) (int, error) {
	checkVersion()
	if streams == nil {
		streams = &commands.Streams{
			Stdin:  os.Stdin,
			Stdout: os.Stdout,
			Stderr: os.Stderr,
		}
	}
	flag.CommandLine.Parse(rawArgs)

	config, cfgErr := config.GetConfig()
	if cfgErr != nil && !os.IsNotExist(cfgErr) {
		return 1, fmt.Errorf("unable to open .scwrc config file: %v", cfgErr)
	}

	if config != nil {
		defaultComputeAPI := os.Getenv("scaleway_api_endpoint")
		if defaultComputeAPI == "" {
			defaultComputeAPI = config.ComputeAPI
		}
		if flAPIEndPoint == nil {
			flAPIEndPoint = flag.String([]string{"-api-endpoint"}, defaultComputeAPI, "Set the API endpoint")
		}
	}

	if *flVersion {
		fmt.Fprintf(streams.Stderr, "scw version %s, build %s\n", scwversion.VERSION, scwversion.GITCOMMIT)
		return 0, nil
	}

	if flAPIEndPoint != nil {
		os.Setenv("scaleway_api_endpoint", *flAPIEndPoint)
	}

	if *flSensitive {
		os.Setenv("SCW_SENSITIVE", "1")
	}

	if *flDebug {
		os.Setenv("DEBUG", "1")
	}

	utils.Quiet(*flQuiet)
	initLogging(os.Getenv("DEBUG") != "", *flVerbose, streams)

	args := flag.Args()
	if len(args) < 1 {
		CmdHelp.Exec(CmdHelp, []string{})
		return 1, nil
	}
	name := args[0]

	args = args[1:]

	// Apply default values
	for _, cmd := range Commands {
		cmd.streams = streams
	}

	for _, cmd := range Commands {
		if cmd.Name() == name {
			cmd.Flag.SetOutput(ioutil.Discard)
			err := cmd.Flag.Parse(args)
			if err != nil {
				return 1, fmt.Errorf("usage: scw %s", cmd.UsageLine)
			}
			switch cmd.Name() {
			case "login", "help", "version":
				// commands that don't need API
			case "_userdata":
				// commands that may need API
				api, _ := getScalewayAPI()
				cmd.API = api
			default:
				// commands that do need API
				if cfgErr != nil {
					if name != "login" && config == nil {
						logrus.Debugf("cfgErr: %v", cfgErr)
						fmt.Fprintf(streams.Stderr, "You need to login first: 'scw login'\n")
						return 1, nil
					}
				}
				api, err := getScalewayAPI()
				if err != nil {
					return 1, fmt.Errorf("unable to initialize scw api: %s", err)
				}
				cmd.API = api
			}
			err = cmd.Exec(cmd, cmd.Flag.Args())
			switch err {
			case nil:
			case ErrExitFailure:
				return 1, nil
			case ErrExitSuccess:
				return 0, nil
			default:
				return 1, fmt.Errorf("cannot execute '%s': %v", cmd.Name(), err)
			}
			if cmd.API != nil {
				cmd.API.Sync()
			}
			return 0, nil
		}
	}

	return 1, fmt.Errorf("scw: unknown subcommand %s\nRun 'scw help' for usage", name)
}
コード例 #16
0
ファイル: service_windows.go プロジェクト: RAMESHBABUK/docker
	"os"
	"os/exec"
	"path/filepath"
	"syscall"

	"github.com/Sirupsen/logrus"
	flag "github.com/docker/docker/pkg/mflag"
	"golang.org/x/sys/windows"
	"golang.org/x/sys/windows/svc"
	"golang.org/x/sys/windows/svc/debug"
	"golang.org/x/sys/windows/svc/eventlog"
	"golang.org/x/sys/windows/svc/mgr"
)

var (
	flServiceName       = flag.String([]string{"-service-name"}, "docker", "Set the Windows service name")
	flRegisterService   = flag.Bool([]string{"-register-service"}, false, "Register the service and exit")
	flUnregisterService = flag.Bool([]string{"-unregister-service"}, false, "Unregister the service and exit")
	flRunService        = flag.Bool([]string{"-run-service"}, false, "")

	setStdHandle = syscall.NewLazyDLL("kernel32.dll").NewProc("SetStdHandle")
	oldStderr    syscall.Handle
	panicFile    *os.File

	service *handler
)

const (
	// These should match the values in event_messages.mc.
	eventInfo  = 1
	eventWarn  = 1
コード例 #17
0
ファイル: main.go プロジェクト: QuentinPerez/scaleway-cli
	"github.com/scaleway/scaleway-cli/pkg/api"
	"github.com/scaleway/scaleway-cli/pkg/clilogger"
	"github.com/scaleway/scaleway-cli/pkg/commands"
	"github.com/scaleway/scaleway-cli/pkg/config"
	"github.com/scaleway/scaleway-cli/pkg/scwversion"
	"github.com/scaleway/scaleway-cli/pkg/utils"
)

// global options
var (
	flDebug     = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flVerbose   = flag.Bool([]string{"V", "-verbose"}, false, "Enable verbose mode")
	flVersion   = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
	flQuiet     = flag.Bool([]string{"q", "-quiet"}, false, "Enable quiet mode")
	flSensitive = flag.Bool([]string{"-sensitive"}, false, "Show sensitive data in outputs, i.e. API Token/Organization")
	flRegion    = flag.String([]string{"-region"}, "par1", "Change the default region (e.g. ams1)")
)

// Start is the entrypoint
func Start(rawArgs []string, streams *commands.Streams) (int, error) {
	checkVersion()
	if streams == nil {
		streams = &commands.Streams{
			Stdin:  os.Stdin,
			Stdout: os.Stdout,
			Stderr: os.Stderr,
		}
	}
	flag.CommandLine.Parse(rawArgs)

	config, cfgErr := config.GetConfig()
コード例 #18
0
ファイル: cmd_container.go プロジェクト: jiangshengwu/dockerf
	"github.com/docker/docker/opts"
	flag "github.com/docker/docker/pkg/mflag"
	"github.com/docker/docker/pkg/term"
	dmachine "github.com/weibocom/dockerf/machine"
)

const (
	defaultTrustKeyFile = "key.json"
	defaultCaFile       = "ca.pem"
	defaultKeyFile      = "key.pem"
	defaultCertFile     = "cert.pem"
)

var (
	// all docker command except help must give '--machine' flag
	flMachine = flag.String([]string{"-machine"}, "", "Machine name where docker run. 'dockerf machine ls' to display all machines. ")
	flSwarm   = flag.Bool([]string{"-swarm"}, false, "Manage container by swarm")
)

func init() {

}

func (dcli *DockerfCli) CmdContainer(args ...string) error {

	flag.CommandLine.Parse(args)

	if *flVersion {
		showVersion()
		os.Exit(1)
	}
コード例 #19
0
ファイル: flags.go プロジェクト: Gandi/docker
func init() {
	flCa = flag.String([]string{"-tlscacert"}, filepath.Join(dockerCertPath, defaultCaFile), "Trust only remotes providing a certificate signed by the CA given here")
	flCert = flag.String([]string{"-tlscert"}, filepath.Join(dockerCertPath, defaultCertFile), "Path to TLS certificate file")
	flKey = flag.String([]string{"-tlskey"}, filepath.Join(dockerCertPath, defaultKeyFile), "Path to TLS key file")
	opts.HostListVar(&flHosts, []string{"H", "-host"}, "The socket(s) to bind to in daemon mode\nspecified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.")
}
コード例 #20
0
ファイル: config.go プロジェクト: hopkings2008/collector
// DefineDestsFlag is called by the importing package, e.g., main, to create the dests flag.
func DefineDestsFlag(def string) {
	Dests = flag.String([]string{"d", "-dests"}, def,
		"One or more ',' separated destinations for output generated by scripts. e.g., file or file,custom")
}
コード例 #21
0
ファイル: flags.go プロジェクト: hariharan16s/libnetwork
	"fmt"
	"os"

	flag "github.com/docker/docker/pkg/mflag"
)

type command struct {
	name        string
	description string
}

type byName []command

var (
	flDaemon   = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
	flHost     = flag.String([]string{"H", "-host"}, "", "Daemon socket to connect to")
	flLogLevel = flag.String([]string{"l", "-log-level"}, "info", "Set the logging level")
	flDebug    = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flCfgFile  = flag.String([]string{"c", "-cfg-file"}, "/etc/default/libnetwork.toml", "Configuration file")
	flHelp     = flag.Bool([]string{"h", "-help"}, false, "Print usage")

	dnetCommands = []command{
		{"network", "Network management commands"},
		{"service", "Service management commands"},
	}
)

func init() {
	flag.Usage = func() {
		fmt.Fprint(os.Stdout, "Usage: dnet [OPTIONS] COMMAND [arg...]\n\nA self-sufficient runtime for container networking.\n\nOptions:\n")
コード例 #22
0
ファイル: flags.go プロジェクト: hgschmie/docker
	}
}

func getDaemonConfDir() string {
	// TODO: update for Windows daemon
	if runtime.GOOS == "windows" {
		return filepath.Join(homedir.Get(), ".docker")
	}
	return "/etc/docker"
}

var (
	flVersion   = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
	flDaemon    = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
	flDebug     = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
	flLogLevel  = flag.String([]string{"l", "-log-level"}, "info", "Set the logging level")
	flTls       = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by --tlsverify flag")
	flHelp      = flag.Bool([]string{"h", "-help"}, false, "Print usage")
	flTlsVerify = flag.Bool([]string{"-tlsverify"}, dockerTlsVerify, "Use TLS and verify the remote")

	// these are initialized in init() below since their default values depend on dockerCertPath which isn't fully initialized until init() runs
	flTrustKey *string
	flCa       *string
	flCert     *string
	flKey      *string
	flHosts    []string
)

func setDefaultConfFlag(flag *string, def string) {
	if *flag == "" {
		if *flDaemon {
コード例 #23
0
ファイル: docker.go プロジェクト: hsrd/docker
func main() {
	if len(dockerConfDir) == 0 {
		dockerConfDir = filepath.Join(os.Getenv("HOME"), ".docker")
	}
	if selfPath := utils.SelfPath(); strings.Contains(selfPath, ".dockerinit") {
		// Running in init mode
		sysinit.SysInit()
		return
	}

	var (
		flVersion            = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
		flDaemon             = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
		flGraphOpts          opts.ListOpts
		flDebug              = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
		flAutoRestart        = flag.Bool([]string{"r", "-restart"}, true, "Restart previously running containers")
		bridgeName           = flag.String([]string{"b", "-bridge"}, "", "Attach containers to a pre-existing network bridge\nuse 'none' to disable container networking")
		bridgeIp             = flag.String([]string{"#bip", "-bip"}, "", "Use this CIDR notation address for the network bridge's IP, not compatible with -b")
		pidfile              = flag.String([]string{"p", "-pidfile"}, "/var/run/docker.pid", "Path to use for daemon PID file")
		flRoot               = flag.String([]string{"g", "-graph"}, "/var/lib/docker", "Path to use as the root of the Docker runtime")
		flSocketGroup        = flag.String([]string{"G", "-group"}, "docker", "Group to assign the unix socket specified by -H when running in daemon mode\nuse '' (the empty string) to disable setting of a group")
		flEnableCors         = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
		flDns                = opts.NewListOpts(opts.ValidateIPAddress)
		flDnsSearch          = opts.NewListOpts(opts.ValidateDnsSearch)
		flEnableIptables     = flag.Bool([]string{"#iptables", "-iptables"}, true, "Enable Docker's addition of iptables rules")
		flEnableIpForward    = flag.Bool([]string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
		flDefaultIp          = flag.String([]string{"#ip", "-ip"}, "0.0.0.0", "Default IP address to use when binding container ports")
		flInterContainerComm = flag.Bool([]string{"#icc", "-icc"}, true, "Enable inter-container communication")
		flGraphDriver        = flag.String([]string{"s", "-storage-driver"}, "", "Force the Docker runtime to use a specific storage driver")
		flExecDriver         = flag.String([]string{"e", "-exec-driver"}, "native", "Force the Docker runtime to use a specific exec driver")
		flHosts              = opts.NewListOpts(api.ValidateHost)
		flMtu                = flag.Int([]string{"#mtu", "-mtu"}, 0, "Set the containers network MTU\nif no value is provided: default to the default route MTU or 1500 if no default route is available")
		flTls                = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by tls-verify flags")
		flTlsVerify          = flag.Bool([]string{"-tlsverify"}, false, "Use TLS and verify the remote (daemon: verify client, client: verify daemon)")
		flCa                 = flag.String([]string{"-tlscacert"}, filepath.Join(dockerConfDir, defaultCaFile), "Trust only remotes providing a certificate signed by the CA given here")
		flCert               = flag.String([]string{"-tlscert"}, filepath.Join(dockerConfDir, defaultCertFile), "Path to TLS certificate file")
		flKey                = flag.String([]string{"-tlskey"}, filepath.Join(dockerConfDir, defaultKeyFile), "Path to TLS key file")
		flSelinuxEnabled     = flag.Bool([]string{"-selinux-enabled"}, false, "Enable selinux support. SELinux does not presently support the BTRFS storage driver")
	)
	flag.Var(&flDns, []string{"#dns", "-dns"}, "Force Docker to use specific DNS servers")
	flag.Var(&flDnsSearch, []string{"-dns-search"}, "Force Docker to use specific DNS search domains")
	flag.Var(&flHosts, []string{"H", "-host"}, "The socket(s) to bind to in daemon mode\nspecified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.")
	flag.Var(&flGraphOpts, []string{"-storage-opt"}, "Set storage driver options")

	flag.Parse()

	if *flVersion {
		showVersion()
		return
	}
	if flHosts.Len() == 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)
		}
		if _, err := api.ValidateHost(defaultHost); err != nil {
			log.Fatal(err)
		}
		flHosts.Set(defaultHost)
	}

	if *bridgeName != "" && *bridgeIp != "" {
		log.Fatal("You specified -b & --bip, mutually exclusive options. Please specify only one.")
	}

	if !*flEnableIptables && !*flInterContainerComm {
		log.Fatal("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
	}

	if net.ParseIP(*flDefaultIp) == nil {
		log.Fatalf("Specified --ip=%s is not in correct format \"0.0.0.0\".", *flDefaultIp)
	}

	if *flDebug {
		os.Setenv("DEBUG", "1")
	}

	if *flDaemon {
		if runtime.GOOS != "linux" {
			log.Fatalf("The Docker daemon is only supported on linux")
		}
		if os.Geteuid() != 0 {
			log.Fatalf("The Docker daemon needs to be run as root")
		}

		if flag.NArg() != 0 {
			flag.Usage()
			return
		}

		// set up the TempDir to use a canonical path
		tmp := os.TempDir()
		realTmp, err := utils.ReadSymlinkedDirectory(tmp)
		if err != nil {
			log.Fatalf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
		}
		os.Setenv("TMPDIR", realTmp)

		// get the canonical path to the Docker root directory
		root := *flRoot
		var realRoot string
		if _, err := os.Stat(root); err != nil && os.IsNotExist(err) {
			realRoot = root
		} else {
			realRoot, err = utils.ReadSymlinkedDirectory(root)
			if err != nil {
				log.Fatalf("Unable to get the full path to root (%s): %s", root, err)
			}
		}
		if err := checkKernelAndArch(); err != nil {
			log.Fatal(err)
		}

		eng := engine.New()
		// Load builtins
		if err := builtins.Register(eng); err != nil {
			log.Fatal(err)
		}

		// handle the pidfile early. https://github.com/docker/docker/issues/6973
		if len(*pidfile) > 0 {
			job := eng.Job("initserverpidfile", *pidfile)
			if err := job.Run(); err != nil {
				log.Fatal(err)
			}
		}

		// load the daemon in the background so we can immediately start
		// the http api so that connections don't fail while the daemon
		// is booting
		go func() {
			// Load plugin: httpapi
			job := eng.Job("initserver")
			// include the variable here too, for the server config
			job.Setenv("Pidfile", *pidfile)
			job.Setenv("Root", realRoot)
			job.SetenvBool("AutoRestart", *flAutoRestart)
			job.SetenvList("Dns", flDns.GetAll())
			job.SetenvList("DnsSearch", flDnsSearch.GetAll())
			job.SetenvBool("EnableIptables", *flEnableIptables)
			job.SetenvBool("EnableIpForward", *flEnableIpForward)
			job.Setenv("BridgeIface", *bridgeName)
			job.Setenv("BridgeIP", *bridgeIp)
			job.Setenv("DefaultIp", *flDefaultIp)
			job.SetenvBool("InterContainerCommunication", *flInterContainerComm)
			job.Setenv("GraphDriver", *flGraphDriver)
			job.SetenvList("GraphOptions", flGraphOpts.GetAll())
			job.Setenv("ExecDriver", *flExecDriver)
			job.SetenvInt("Mtu", *flMtu)
			job.SetenvBool("EnableSelinuxSupport", *flSelinuxEnabled)
			job.SetenvList("Sockets", flHosts.GetAll())
			if err := job.Run(); err != nil {
				log.Fatal(err)
			}
			// after the daemon is done setting up we can tell the api to start
			// accepting connections
			if err := eng.Job("acceptconnections").Run(); err != nil {
				log.Fatal(err)
			}
		}()

		// TODO actually have a resolved graphdriver to show?
		log.Printf("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
			dockerversion.VERSION,
			dockerversion.GITCOMMIT,
			*flExecDriver,
			*flGraphDriver)

		// Serve api
		job := eng.Job("serveapi", flHosts.GetAll()...)
		job.SetenvBool("Logging", true)
		job.SetenvBool("EnableCors", *flEnableCors)
		job.Setenv("Version", dockerversion.VERSION)
		job.Setenv("SocketGroup", *flSocketGroup)

		job.SetenvBool("Tls", *flTls)
		job.SetenvBool("TlsVerify", *flTlsVerify)
		job.Setenv("TlsCa", *flCa)
		job.Setenv("TlsCert", *flCert)
		job.Setenv("TlsKey", *flKey)
		job.SetenvBool("BufferRequests", true)
		if err := job.Run(); err != nil {
			log.Fatal(err)
		}
	} else {
		if flHosts.Len() > 1 {
			log.Fatal("Please specify only one -H")
		}
		protoAddrParts := strings.SplitN(flHosts.GetAll()[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, protoAddrParts[0], protoAddrParts[1], &tlsConfig)
		} else {
			cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, protoAddrParts[0], protoAddrParts[1], nil)
		}

		if err := cli.ParseCommands(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)
		}
	}
}