// NewCli would generate Convoy CLI
332652
func NewCli(version string) *cli.App {
	app := cli.NewApp()
	app.Name = "Convoy"
	app.Version = version
	app.Author = "Sheng Yang <sheng.yang@rancher.com>"
	app.Usage = "A volume manager capable of snapshot and delta backup"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "socket, s",
			Value: "/var/run/convoy/convoy.sock",
			Usage: "Specify unix domain socket for communication between server and client",
		},
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "Enable debug level log with client or not",
		},
		cli.BoolFlag{
			Name:  "verbose",
			Usage: "Verbose level output for client, for create volume/snapshot etc",
		},
	}
	app.CommandNotFound = cmdNotFound
	app.Before = initClient
	app.Commands = []cli.Command{
		daemonCmd,
		infoCmd,
		volumeCreateCmd,
		volumeDeleteCmd,
		volumeMountCmd,
		volumeUmountCmd,
		volumeListCmd,
		volumeInspectCmd,
		snapshotCmd,
		backupCmd,
	}
	return app
}
863903
func FromCli(c *cli.Context) (plugin.Middleware, error) {
	return NewSpec(c.String("condition"), c.String("fallback"), c.String("onTripped"), c.String("onStandby"), c.Duration("fallbackDuration"), c.Duration("recoveryDuration"), c.Duration("checkPeriod"))
}
1123
func NewCluster(options *ClusterOptions) (*Cluster, error) {
	if options == nil {
		options = defaultClusterOptions
	}
	if options.NodeManager == nil {
		options.NodeManager = &defaultNodeManager{}
	}
	if options.ExecutionAttempts == 0 {
		options.ExecutionAttempts = defaultExecutionAttempts
	}

	c := &Cluster{
		executionAttempts: options.ExecutionAttempts,
		nodeManager:       options.NodeManager,
	}
	c.initStateData("clusterCreated", "clusterRunning", "clusterShuttingDown", "clusterShutdown", "clusterError")

	if options.Nodes == nil {
		c.nodes = make([]*Node, 0)
	} else {
		c.nodes = options.Nodes
	}

	if options.NoDefaultNode == false && len(c.nodes) == 0 {
		defaultNode, nerr := NewNode(nil)
		if nerr != nil {
			return nil, nerr
		}
		c.nodes = append(c.nodes, defaultNode)
	}

	for _, node := range c.nodes {
		if node == nil {
			return nil, ErrClusterNodesMustBeNonNil
		}
	}

	if options.QueueMaxDepth > 0 {
		if options.QueueExecutionInterval == 0 {
			options.QueueExecutionInterval = defaultQueueExecutionInterval
		}
		c.queueCommands = true
		c.stopChan = make(chan struct{})
		c.cq = newQueue(options.QueueMaxDepth)
		c.commandQueueTicker = time.NewTicker(options.QueueExecutionInterval)
		go c.executeEnqueuedCommands()
	}

	c.setState(clusterCreated)
	return c, nil
}
1132163
func NewDockerCli(ops ...DockerCliOption) (*DockerCli, error) {
	cli := &DockerCli{}
	defaultOps := []DockerCliOption{
		WithContentTrustFromEnv(),
		WithContainerizedClient(containerizedengine.NewClient),
	}
	cli.contextStoreConfig = defaultContextStoreConfig()
	ops = append(defaultOps, ops...)
	if err := cli.Apply(ops...); err != nil {
		return nil, err
	}
	if cli.out == nil || cli.in == nil || cli.err == nil {
		stdin, stdout, stderr := term.StdStreams()
		if cli.in == nil {
			cli.in = streams.NewIn(stdin)
		}
		if cli.out == nil {
			cli.out = streams.NewOut(stdout)
		}
		if cli.err == nil {
			cli.err = stderr
		}
	}
	return cli, nil
}
553744
func NewAliCloudOSSBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) {
	endpoint := os.Getenv("ALICLOUD_OSS_ENDPOINT")
	if endpoint == "" {
		endpoint = conf["endpoint"]
		if endpoint == "" {
			return nil, fmt.Errorf("'endpoint' must be set")
		}
	}

	bucket := os.Getenv("ALICLOUD_OSS_BUCKET")
	if bucket == "" {
		bucket = conf["bucket"]
		if bucket == "" {
			return nil, fmt.Errorf("'bucket' must be set")
		}
	}

	accessKeyID := os.Getenv("ALICLOUD_ACCESS_KEY")
	if accessKeyID == "" {
		accessKeyID = conf["access_key"]
		if accessKeyID == "" {
			return nil, fmt.Errorf("'access_key' must be set")
		}
	}

	accessKeySecret := os.Getenv("ALICLOUD_SECRET_KEY")
	if accessKeySecret == "" {
		accessKeySecret = conf["secret_key"]
		if accessKeySecret == "" {
			return nil, fmt.Errorf("'secret_key' must be set")
		}
	}

	options := func(c *oss.Client) {
		c.Config.Timeout = 30
	}

	client, err := oss.New(endpoint, accessKeyID, accessKeySecret, options)
	if err != nil {
		return nil, err
	}

	bucketObj, err := client.Bucket(bucket)
	if err != nil {
		return nil, err
	}

	_, err = bucketObj.ListObjects()
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("unable to access bucket %q at endpoint %q: {{err}}", bucket, endpoint), err)
	}

	maxParStr, ok := conf["max_parallel"]
	var maxParInt int
	if ok {
		maxParInt, err = strconv.Atoi(maxParStr)
		if err != nil {
			return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
		}
		if logger.IsDebug() {
			logger.Debug("max_parallel set", "max_parallel", maxParInt)
		}
	}

	a := &AliCloudOSSBackend{
		client:     client,
		bucket:     bucket,
		logger:     logger,
		permitPool: physical.NewPermitPool(maxParInt),
	}
	return a, nil
}
839932
func NewExportCommand(dockerCli command.Cli) *cobra.Command {
	var opts exportOptions

	cmd := &cobra.Command{
		Use:   "export [OPTIONS] CONTAINER",
		Short: "Export a container's filesystem as a tar archive",
		Args:  cli.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.container = args[0]
			return runExport(dockerCli, opts)
		},
	}

	flags := cmd.Flags()

	flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT")

	return cmd
}
1194183
func NewClient(caller base.APICaller) leadership.Claimer {
	return &client{base.NewFacadeCaller(caller, "LeadershipService")}
}
585407
func NewClient(uri string, cli *http.Client) Client {
	return &client{cli, strings.TrimSuffix(uri, "/")}
}
1039437
func NewClient(uploadPackBin, receivePackBin string) transport.Transport {
	return common.NewClient(&runner{
		UploadPackBin:  uploadPackBin,
		ReceivePackBin: receivePackBin,
	})
}
1164967
func New(transport runtime.ClientTransport, formats strfmt.Registry) *TodoList {
	// ensure nullable parameters have default
	if formats == nil {
		formats = strfmt.Default
	}

	cli := new(TodoList)
	cli.Transport = transport

	cli.Todos = todos.New(transport, formats)

	return cli
}
240713
func newApp() (app *cli.App) {
	app = utils.NewApp(gitCommit, "Swarm Snapshot Utility")

	app.Name = "swarm-snapshot"
	app.Usage = ""

	// app flags (for all commands)
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:  "verbosity",
			Value: 1,
			Usage: "verbosity level",
		},
	}

	app.Commands = []cli.Command{
		{
			Name:    "create",
			Aliases: []string{"c"},
			Usage:   "create a swarm snapshot",
			Action:  create,
			// Flags only for "create" command.
			// Allow app flags to be specified after the
			// command argument.
			Flags: append(app.Flags,
				cli.IntFlag{
					Name:  "nodes",
					Value: defaultNodes,
					Usage: "number of nodes",
				},
				cli.StringFlag{
					Name:  "services",
					Value: "bzz",
					Usage: "comma separated list of services to boot the nodes with",
				},
			),
		},
	}

	return app
}
749575
func New(driver api.API, config utils.ConfigReader, logControl logging.LogControl) *ServicedCli {
	if config == nil {
		log.Fatal("Missing configuration data")
	}
	defaultOps := api.GetDefaultOptions(config)

	c := &ServicedCli{
		driver:     driver,
		app:        cli.NewApp(),
		config:     config,
		logControl: logControl,
	}

	c.app.Name = "serviced"
	c.app.Usage = "A container-based management system"
	c.app.Version = fmt.Sprintf("%s - %s ", servicedversion.Version, servicedversion.Gitcommit)
	c.app.EnableBashCompletion = true
	c.app.Before = c.cmdInit
	c.app.Flags = []cli.Flag{
		cli.StringFlag{"docker-registry", defaultOps.DockerRegistry, "local docker registry to use"},
		cli.StringSliceFlag{"static-ip", convertToStringSlice(defaultOps.StaticIPs), "static ips for this agent to advertise"},
		cli.StringFlag{"endpoint", defaultOps.Endpoint, fmt.Sprintf("endpoint for remote serviced (example.com:%d)", api.DefaultRPCPort)},
		cli.StringFlag{"outbound", defaultOps.OutboundIP, "outbound ip address"},
		cli.StringFlag{"uiport", defaultOps.UIPort, "port for ui"},
		cli.StringFlag{"nfs-client", defaultOps.NFSClient, "establish agent as an nfs client sharing data, 0 to disable"},
		cli.IntFlag{"listen", config.IntVal("RPC_PORT", api.DefaultRPCPort), fmt.Sprintf("rpc port for serviced (%d)", api.DefaultRPCPort)},
		cli.StringSliceFlag{"docker-dns", convertToStringSlice(defaultOps.DockerDNS), "docker dns configuration used for running containers"},
		cli.BoolFlag{"master", "run in master mode, i.e., the control center service"},
		cli.BoolFlag{"agent", "deprecated"},
		cli.IntFlag{"mux", defaultOps.MuxPort, "multiplexing port"},
		cli.StringFlag{"mux-disable-tls", defaultOps.MuxDisableTLS, "disable TLS for mux connections"},
		cli.StringSliceFlag{"mux-tls-ciphers", convertToStringSlice(defaultOps.MUXTLSCiphers), "list of supported TLS ciphers for MUX"},
		cli.StringFlag{"mux-tls-min-version", string(defaultOps.MUXTLSMinVersion), "mininum TLS version for MUX"},
		cli.StringFlag{"volumes-path", defaultOps.VolumesPath, "path where application data is stored"},
		cli.StringFlag{"isvcs-path", defaultOps.IsvcsPath, "path where internal application data is stored"},
		cli.StringFlag{"backups-path", defaultOps.BackupsPath, "default path where backups are stored"},
		cli.StringFlag{"etc-path", defaultOps.EtcPath, "default path for configuration files"},
		cli.StringFlag{"log-path", defaultOps.LogPath, "path where serviced logs are located"},
		cli.StringFlag{"keyfile", defaultOps.KeyPEMFile, "path to private key file (defaults to compiled in private key)"},
		cli.StringFlag{"certfile", defaultOps.CertPEMFile, "path to public certificate file (defaults to compiled in public cert)"},
		cli.StringSliceFlag{"zk", convertToStringSlice(defaultOps.Zookeepers), "Specify a zookeeper instance to connect to (e.g. -zk localhost:2181)"},
		cli.StringSliceFlag{"mount", convertToStringSlice(defaultOps.Mount), "bind mount: DOCKER_IMAGE,HOST_PATH[,CONTAINER_PATH]"},
		cli.StringFlag{"fstype", string(defaultOps.FSType), "driver for underlying file system"},
		cli.StringSliceFlag{"alias", convertToStringSlice(defaultOps.HostAliases), "list of aliases for this host, e.g., localhost"},
		cli.IntFlag{"es-startup-timeout", defaultOps.ESStartupTimeout, "time (in seconds) to wait on elasticsearch startup before bailing"},
		cli.IntFlag{"max-container-age", defaultOps.MaxContainerAge, "maximum age (seconds) of a stopped container before removing"},
		cli.IntFlag{"max-dfs-timeout", defaultOps.MaxDFSTimeout, "max timeout to perform a dfs snapshot"},
		cli.StringFlag{"virtual-address-subnet", defaultOps.VirtualAddressSubnet, "/16 subnet for virtual addresses"},
		cli.StringFlag{"master-pool-id", defaultOps.MasterPoolID, "master's pool ID"},
		cli.StringFlag{"admin-group", defaultOps.AdminGroup, "system group that can log in to control center"},
		cli.StringSliceFlag{"storage-opts", convertToStringSlice(defaultOps.StorageArgs), "storage args to initialize filesystem"},
		cli.StringSliceFlag{"isvcs-start", convertToStringSlice(defaultOps.StartISVCS), "isvcs to start on agent"},
		cli.IntFlag{"isvcs-zk-id", defaultOps.IsvcsZKID, "zookeeper id when running in a cluster"},
		cli.StringSliceFlag{"isvcs-zk-quorum", convertToStringSlice(defaultOps.IsvcsZKQuorum), "isvcs zookeeper host quorum (e.g. -isvcs-zk-quorum zk1@localhost:2888:3888)"},
		cli.StringFlag{"isvcs-zk-username", defaultOps.IsvcsZKUsername, "isvcs zookeeper username"},
		cli.StringFlag{"isvcs-zk-passwd", defaultOps.IsvcsZKPasswd, "isvcs zookeeper password"},
		cli.StringSliceFlag{"isvcs-env", convertToStringSlice(defaultOps.IsvcsENV), "internal-service environment variable: ISVC:KEY=VAL"},
		cli.StringSliceFlag{"tls-ciphers", convertToStringSlice(defaultOps.TLSCiphers), "list of supported TLS ciphers for HTTP"},
		cli.StringFlag{"tls-min-version", string(defaultOps.TLSMinVersion), "mininum TLS version for HTTP"},

		cli.BoolTFlag{"report-stats", "report container statistics"},
		cli.StringFlag{"host-stats", defaultOps.HostStats, "container statistics for host:port"},
		cli.IntFlag{"stats-period", defaultOps.StatsPeriod, "Period (seconds) for container statistics reporting"},
		cli.StringFlag{"mc-username", defaultOps.MCUsername, "Username for Zenoss metric consumer"},
		cli.StringFlag{"mc-password", defaultOps.MCPasswd, "Password for the Zenoss metric consumer"},
		cli.StringFlag{"cpuprofile", defaultOps.CPUProfile, "write cpu profile to file"},
		cli.IntFlag{"debug-port", defaultOps.DebugPort, "Port on which to listen for profiler connections"},
		cli.IntFlag{"max-rpc-clients", defaultOps.MaxRPCClients, "max number of rpc clients to an endpoint"},
		cli.IntFlag{"rpc-dial-timeout", defaultOps.RPCDialTimeout, "timeout for creating rpc connections"},
		cli.StringFlag{"rpc-cert-verify", defaultOps.RPCCertVerify, "enable verification of rpc server certificate"},
		cli.StringFlag{"rpc-disable-tls", defaultOps.RPCDisableTLS, "disable tls for RPC connections"},
		cli.StringSliceFlag{"rpc-tls-ciphers", convertToStringSlice(defaultOps.RPCTLSCiphers), "list of supported TLS ciphers for RPC"},
		cli.StringFlag{"rpc-tls-min-version", string(defaultOps.RPCTLSMinVersion), "mininum TLS version for RPC"},
		cli.IntFlag{"snapshot-ttl", defaultOps.SnapshotTTL, "snapshot TTL in hours, 0 to disable"},
		cli.IntFlag{"snapshot-space-percent", defaultOps.SnapshotSpacePercent, "percent of tenant volume size that is assumed to be needed to create a snapshot"},
		cli.StringFlag{"controller-binary", defaultOps.ControllerBinary, "path to the container controller binary"},
		cli.StringFlag{"log-driver", defaultOps.DockerLogDriver, "log driver for docker containers"},
		cli.StringSliceFlag{"log-config", convertToStringSlice(defaultOps.DockerLogConfigList), "comma-separated list of key=value settings for docker log driver"},

		cli.IntFlag{"ui-poll-frequency", defaultOps.UIPollFrequency, "frequency in seconds that the UI polls serviced for changes"},
		cli.IntFlag{"storage-stats-update-interval", defaultOps.StorageStatsUpdateInterval, "frequency in seconds that the thin pool usage will be analyzed"},
		cli.IntFlag{"zk-session-timeout", defaultOps.ZKSessionTimeout, "zookeeper session timeout in seconds"},
		cli.IntFlag{"zk-connection-timeout", defaultOps.ZKConnectTimeout, "zookeeper connection timeout in seconds"},
		cli.IntFlag{"zk-per-host-connect-delay", defaultOps.ZKPerHostConnectDelay, "zookeeper per-host delay in seconds"},
		cli.IntFlag{"zk-reconnect-start-delay", defaultOps.ZKReconnectStartDelay, "zookeeper initial reconnect delay in seconds"},
		cli.IntFlag{"zk-reconnect-max-delay", defaultOps.ZKReconnectMaxDelay, "zookeeper max recoonect delay in seconds"},
		cli.IntFlag{"auth-token-expiry", defaultOps.TokenExpiration, "authentication token expiration in seconds"},
		cli.StringFlag{"conntrack-flush", defaultOps.ConntrackFlush, "whether to flush the conntrack table when a service with an assigned IP is started"},
		cli.IntFlag{"service-run-level-timeout", defaultOps.ServiceRunLevelTimeout, "max time in seconds to wait for services to start/stop before moving on to services at the next run level"},

		cli.BoolTFlag{"logtostderr", "log to standard error instead of files"},
		cli.BoolFlag{"alsologtostderr", "log to standard error as well as files"},
		cli.StringFlag{"logstashurl", defaultOps.LogstashURL, "logstash url and port"},
		cli.StringFlag{"logstash-es", defaultOps.LogstashES, "host and port for logstash elastic search"},
		cli.IntFlag{"logstash-max-days", defaultOps.LogstashMaxDays, "days to keep Logstash data"},
		cli.IntFlag{"logstash-max-size", defaultOps.LogstashMaxSize, "max size of Logstash data to keep in gigabytes"},

		cli.IntFlag{"storage-report-interval", defaultOps.StorageReportInterval, "frequency in seconds to report storage stats to opentsdb"},
		cli.IntFlag{"storage-metric-monitor-window", defaultOps.StorageMetricMonitorWindow, "the amount of time in seconds for which serviced will consider storage availability metrics in order to predict future availability"},
		cli.IntFlag{"storage-lookahead-period", defaultOps.StorageLookaheadPeriod, "the amount of time in the future in seconds serviced should predict storage availability for the purposes of emergency shutdown"},
		cli.StringFlag{"storage-min-free", string(defaultOps.StorageMinimumFreeSpace), "the amount of space the emergency shutdown algorithm should reserve when deciding to shut down"},

		cli.IntFlag{"logstash-cycle-time", defaultOps.LogstashCycleTime, "logstash purging cycle time in hours"},
		cli.IntFlag{"v", defaultOps.Verbosity, "log level for V logs"},
		cli.StringFlag{"stderrthreshold", "", "logs at or above this threshold go to stderr"},
		cli.StringFlag{"vmodule", "", "comma-separated list of pattern=N settings for file-filtered logging"},
		cli.StringFlag{"log_backtrace_at", "", "when logging hits line file:N, emit a stack trace"},
		cli.StringFlag{"config-file", "/etc/default/serviced", "path to config"},
		cli.StringFlag{"allow-loop-back", defaultOps.AllowLoopBack, "allow loop-back device with devicemapper"},
		cli.StringFlag{"backup-min-overhead", defaultOps.BackupMinOverhead, "Minimum free space to allow when calculating backup estimates"},
		cli.Float64Flag{"backup-estimated-compression", defaultOps.BackupEstimatedCompression, "Estimate of compression rate to use when calculating backup estimates"},
		cli.StringFlag{"auth0-domain", defaultOps.Auth0Domain, "Domain configured for tenant in Auth0. Ref: https://auth0.com/docs/getting-started/the-basics#domain"},
		cli.StringFlag{"auth0-audience", defaultOps.Auth0Audience, "Audience configured for application (?) in Auth0."},
		cli.StringSliceFlag{"auth0-group", convertToStringSlice(defaultOps.Auth0Group), "Group(s) configured for application in Auth0. A comma-separated list."},
		cli.StringFlag{"auth0-client-id", defaultOps.Auth0ClientID, "Client ID of Auth0 application"},
		cli.StringFlag{"auth0-scope", defaultOps.Auth0Scope, "Scope to request in Auth0"},
		cli.StringFlag{"keyproxy-json-server", defaultOps.KeyProxyJsonServer, "URL for API key server (cc auth token endpoint)"},
		cli.StringFlag{"keyproxy-listen-port", defaultOps.KeyProxyListenPort, "Port for API key proxy to listen on"},
		cli.BoolFlag{"no-prefix-match", "Make matches on SERVICEID by name strictly 'ends-with' rather than 'contains'"},
	}

	c.initVersion()
	c.initPool()
	c.initConfig()
	c.initHealthCheck()
	c.initHost()
	c.initTemplate()
	c.initService()
	c.initSnapshot()
	c.initLog()
	c.initBackup()
	c.initMetric()
	c.initDocker()
	c.initScript()
	c.initServer()
	c.initVolume()
	c.initKey()
	c.initDebug()

	return c
}
681804
func NewConsumerFromClient(client Client) (Consumer, error) {
	// For clients passed in by the client, ensure we don't
	// call Close() on it.
	cli := &nopCloserClient{client}
	return newConsumer(cli)
}
205655
func NewCmdSimpleFS(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
	return cli.Command{
		Name:         "fs",
		Usage:        "Perform filesystem operations",
		ArgumentHelp: "[arguments...]",
		Subcommands: append([]cli.Command{
			NewCmdSimpleFSList(cl, g),
			NewCmdSimpleFSCopy(cl, g),
			NewCmdSimpleFSMove(cl, g),
			NewCmdSimpleFSSymlink(cl, g),
			NewCmdSimpleFSRead(cl, g),
			NewCmdSimpleFSRemove(cl, g),
			NewCmdSimpleFSMkdir(cl, g),
			NewCmdSimpleFSStat(cl, g),
			NewCmdSimpleFSGetStatus(cl, g),
			NewCmdSimpleFSKill(cl, g),
			NewCmdSimpleFSPs(cl, g),
			NewCmdSimpleFSWrite(cl, g),
			NewCmdSimpleFSDebug(cl, g),
			NewCmdSimpleFSSetDebugLevel(cl, g),
			NewCmdSimpleFSHistory(cl, g),
			NewCmdSimpleFSQuota(cl, g),
			NewCmdSimpleFSRecover(cl, g),
			NewCmdSimpleFSReset(cl, g),
			NewCmdSimpleFSClearConflicts(cl, g),
			NewCmdSimpleFSSync(cl, g),
		}, getBuildSpecificFSCommands(cl, g)...),
	}
}
569635
func NewRoutes(compute *gophercloud.ServiceClient, network *gophercloud.ServiceClient, opts RouterOpts) (cloudprovider.Routes, error) {
	if opts.RouterID == "" {
		return nil, errNoRouterID
	}

	return &Routes{
		compute: compute,
		network: network,
		opts:    opts,
	}, nil
}
303169
func NewPushCommand(dockerCli command.Cli) *cobra.Command {
	var opts pushOptions

	cmd := &cobra.Command{
		Use:   "push [OPTIONS] NAME[:TAG]",
		Short: "Push an image or a repository to a registry",
		Args:  cli.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.remote = args[0]
			return RunPush(dockerCli, opts)
		},
	}

	flags := cmd.Flags()

	command.AddTrustSigningFlags(flags, &opts.untrusted, dockerCli.ContentTrustEnabled())

	return cmd
}
975499
func (b *Backend) CLIInit(opts *backend.CLIOpts) error {
	b.CLI = opts.CLI
	b.CLIColor = opts.CLIColor
	b.ContextOpts = opts.ContextOpts
	return nil
}