Exemplo n.º 1
0
func isVerbose(cmd *cobra.Command) bool {
	verbose, err := cmd.PersistentFlags().GetBool("verbose")
	if err != nil {
		panic(err)
	}
	return verbose
}
Exemplo n.º 2
0
func collectFlags(v *viper.Viper, cmd *cobra.Command) {
	v.BindPFlags(cmd.PersistentFlags())
	v.BindPFlags(cmd.Flags())
	for _, cmd := range cmd.Commands() {
		collectFlags(v, cmd)
	}
}
Exemplo n.º 3
0
// AddFlags adds cli flags to logvac
func AddFlags(cmd *cobra.Command) {
	// collectors
	cmd.Flags().StringVarP(&ListenHttp, "listen-http", "a", ListenHttp, "API listen address (same endpoint for http log collection)")
	cmd.Flags().StringVarP(&ListenUdp, "listen-udp", "u", ListenUdp, "UDP log collection endpoint")
	cmd.Flags().StringVarP(&ListenTcp, "listen-tcp", "t", ListenTcp, "TCP log collection endpoint")

	// drains
	cmd.Flags().StringVarP(&PubAddress, "pub-address", "p", PubAddress, "Log publisher (mist) address (\"mist://127.0.0.1:1445\")")
	cmd.Flags().StringVarP(&PubAuth, "pub-auth", "P", PubAuth, "Log publisher (mist) auth token")
	cmd.Flags().StringVarP(&DbAddress, "db-address", "d", DbAddress, "Log storage address")

	// authenticator
	cmd.PersistentFlags().StringVarP(&AuthAddress, "auth-address", "A", AuthAddress, "Address or file location of authentication db. ('boltdb:///var/db/logvac.bolt' or 'postgresql://127.0.0.1')")

	// other
	cmd.Flags().StringVarP(&CorsAllow, "cors-allow", "C", CorsAllow, "Sets the 'Access-Control-Allow-Origin' header")
	cmd.Flags().StringVarP(&LogKeep, "log-keep", "k", LogKeep, "Age or number of logs to keep per type '{\"app\":\"2w\", \"deploy\": 10}' (int or X(m)in, (h)our,  (d)ay, (w)eek, (y)ear)")
	cmd.Flags().StringVarP(&LogLevel, "log-level", "l", LogLevel, "Level at which to log")
	cmd.Flags().StringVarP(&LogType, "log-type", "L", LogType, "Default type to apply to incoming logs (commonly used: app|deploy)")
	cmd.Flags().StringVarP(&Token, "token", "T", Token, "Administrative token to add/remove 'X-USER-TOKEN's used to pub/sub via http")
	cmd.Flags().BoolVarP(&Server, "server", "s", Server, "Run as server")
	cmd.Flags().BoolVarP(&Insecure, "insecure", "i", Insecure, "Don't use TLS (used for testing)")
	cmd.Flags().BoolVarP(&Version, "version", "v", Version, "Print version info and exit")

	Log = lumber.NewConsoleLogger(lumber.LvlInt("ERROR"))
}
Exemplo n.º 4
0
func initializeFlags(cmd *cobra.Command) {
	persFlagKeys := []string{"verbose", "logFile"}
	flagKeys := []string{
		"cleanDestinationDir",
		"buildDrafts",
		"buildFuture",
		"buildExpired",
		"uglyURLs",
		"canonifyURLs",
		"disable404",
		"disableRSS",
		"disableSitemap",
		"enableRobotsTXT",
		"enableGitInfo",
		"pluralizeListTitles",
		"preserveTaxonomyNames",
		"ignoreCache",
		"forceSyncStatic",
		"noTimes",
	}

	for _, key := range persFlagKeys {
		setValueFromFlag(cmd.PersistentFlags(), key)
	}
	for _, key := range flagKeys {
		setValueFromFlag(cmd.Flags(), key)
	}
}
Exemplo n.º 5
0
// RegisterCommands registers the resource action CLI commands.
func RegisterCommands(app *cobra.Command, c *client.Client) {
	var command, sub *cobra.Command
	command = &cobra.Command{
		Use:   "create",
		Short: `creates a bottle`,
	}
	tmp1 := new(CreateBottleCommand)
	sub = &cobra.Command{
		Use:   `bottle ["/bottles"]`,
		Short: `A wine bottle`,
		RunE:  func(cmd *cobra.Command, args []string) error { return tmp1.Run(c, args) },
	}
	tmp1.RegisterFlags(sub, c)
	sub.PersistentFlags().BoolVar(&tmp1.PrettyPrint, "pp", false, "Pretty print response body")
	command.AddCommand(sub)
	app.AddCommand(command)
	command = &cobra.Command{
		Use:   "show",
		Short: `shows a bottle`,
	}
	tmp2 := new(ShowBottleCommand)
	sub = &cobra.Command{
		Use:   `bottle ["/bottles/ID"]`,
		Short: `A wine bottle`,
		RunE:  func(cmd *cobra.Command, args []string) error { return tmp2.Run(c, args) },
	}
	tmp2.RegisterFlags(sub, c)
	sub.PersistentFlags().BoolVar(&tmp2.PrettyPrint, "pp", false, "Pretty print response body")
	command.AddCommand(sub)
	app.AddCommand(command)
}
Exemplo n.º 6
0
// SetupRootCommand sets default usage, help, and error handling for the
// root command.
func SetupRootCommand(rootCmd *cobra.Command) {
	rootCmd.SetUsageTemplate(usageTemplate)
	rootCmd.SetHelpTemplate(helpTemplate)
	rootCmd.SetFlagErrorFunc(FlagErrorFunc)

	rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
	rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
}
func testBindClientConfig(cmd *cobra.Command) ClientConfig {
	loadingRules := &ClientConfigLoadingRules{}
	cmd.PersistentFlags().StringVar(&loadingRules.ExplicitPath, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests.")

	overrides := &ConfigOverrides{}
	BindOverrideFlags(overrides, cmd.PersistentFlags(), RecommendedConfigOverrideFlags(""))
	clientConfig := NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin)

	return clientConfig
}
Exemplo n.º 8
0
func addSubmitFlags(cmd *cobra.Command, config *SubmitQueueConfig) {
	cmd.Flags().BoolVar(&config.Once, "once", false, "If true, run one loop and exit")
	cmd.Flags().StringSliceVar(&config.JenkinsJobs, "jenkins-jobs", []string{"kubernetes-e2e-gce", "kubernetes-e2e-gke-ci", "kubernetes-build", "kubernetes-e2e-gce-parallel", "kubernetes-e2e-gce-autoscaling", "kubernetes-e2e-gce-reboot", "kubernetes-e2e-gce-scalability"}, "Comma separated list of jobs in Jenkins to use for stability testing")
	cmd.Flags().StringVar(&config.JenkinsHost, "jenkins-host", "", "The URL for the jenkins job to watch")
	cmd.Flags().StringSliceVar(&config.RequiredStatusContexts, "required-contexts", []string{"cla/google", "Shippable", "continuous-integration/travis-ci/pr"}, "Comma separate list of status contexts required for a PR to be considered ok to merge")
	cmd.Flags().DurationVar(&config.PollPeriod, "poll-period", 30*time.Minute, "The period for running the submit-queue")
	cmd.Flags().StringVar(&config.Address, "address", ":8080", "The address to listen on for HTTP Status")
	cmd.Flags().StringVar(&config.DontRequireE2ELabel, "dont-require-e2e-label", "e2e-not-required", "If non-empty, a PR with this label will be merged automatically without looking at e2e results")
	cmd.Flags().StringVar(&config.E2EStatusContext, "e2e-status-context", "Jenkins GCE e2e", "The name of the github status context for the e2e PR Builder")
	cmd.Flags().StringVar(&config.WWWRoot, "www", "", "Path to static web files to serve from the webserver")
	cmd.PersistentFlags().AddGoFlagSet(goflag.CommandLine)
}
Exemplo n.º 9
0
func (c *CLI) globalFlags(cmd *cobra.Command) *flag.FlagSet {
	fs := &flag.FlagSet{}
	if cmd.HasParent() {
		fs.AddFlagSet(cmd.InheritedFlags())
		if fs.Lookup("help") == nil && cmd.Flag("help") != nil {
			fs.AddFlag(cmd.Flag("help"))
		}
	} else {
		fs.AddFlagSet(cmd.PersistentFlags())
	}
	return c.sansDriverFlags(c.sansAdditionalFlags(fs))
}
Exemplo n.º 10
0
func testBindClientConfig(cmd *cobra.Command) ClientConfig {
	loadingRules := NewClientConfigLoadingRules()
	loadingRules.EnvVarPath = ""
	loadingRules.HomeDirectoryPath = ""
	loadingRules.CurrentDirectoryPath = ""
	cmd.PersistentFlags().StringVar(&loadingRules.CommandLinePath, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests.")

	overrides := &ConfigOverrides{}
	overrides.BindFlags(cmd.PersistentFlags(), RecommendedConfigOverrideFlags(""))
	clientConfig := NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin)

	return clientConfig
}
Exemplo n.º 11
0
// SetupRootCommand sets default usage, help, and error handling for the
// root command.
func SetupRootCommand(rootCmd *cobra.Command) {
	cobra.AddTemplateFunc("hasSubCommands", hasSubCommands)
	cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands)
	cobra.AddTemplateFunc("operationSubCommands", operationSubCommands)
	cobra.AddTemplateFunc("managementSubCommands", managementSubCommands)

	rootCmd.SetUsageTemplate(usageTemplate)
	rootCmd.SetHelpTemplate(helpTemplate)
	rootCmd.SetFlagErrorFunc(FlagErrorFunc)

	rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
	rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
}
Exemplo n.º 12
0
func AddFlags(cmd *cobra.Command) {
	cmd.Flags().StringVarP(&SshListenAddress, "ssh-address", "", ":2222", "[server] SshListenAddress")
	cmd.Flags().StringVarP(&HttpListenAddress, "http-address", "", ":8080", "[server] HttpListenAddress")
	cmd.Flags().StringVarP(&KeyPath, "key-path", "", "", "[server] KeyPath")
	cmd.Flags().StringVarP(&RepoType, "repo-type", "", "", "[server] RepoType")
	cmd.Flags().StringVarP(&RepoLocation, "repo-location", "", "", "[server] RepoLocation")
	cmd.Flags().StringVarP(&KeyAuthType, "key-auth-type", "", "", "[server] KeyAuthType")
	cmd.Flags().StringVarP(&KeyAuthLocation, "key-auth-location", "", "", "[server] KeyAuthLocation")
	cmd.Flags().StringVarP(&PassAuthType, "pass-auth-type", "", "", "[server] PassAuthType")
	cmd.Flags().StringVarP(&PassAuthLocation, "pass-auth-location", "", "", "[server] PassAuthLocation")
	cmd.Flags().StringVarP(&DeployType, "deploy-type", "", "", "[server] DeployType")
	cmd.Flags().StringVarP(&DeployLocation, "deploy-location", "", "", "[server] DeployLocation")
	cmd.PersistentFlags().StringVarP(&Token, "token", "", "secret", "Token security")
}
Exemplo n.º 13
0
// CommandFor returns the appropriate command for this base name,
// or the OpenShift CLI command.
func CommandFor(basename string) *cobra.Command {
	var cmd *cobra.Command

	out := os.Stdout

	// Make case-insensitive and strip executable suffix if present
	if runtime.GOOS == "windows" {
		basename = strings.ToLower(basename)
		basename = strings.TrimSuffix(basename, ".exe")
	}

	switch basename {
	case "kubectl":
		cmd = NewCmdKubectl(basename, out)
	default:
		cmd = NewCommandCLI(basename, basename, out)
	}

	if cmd.UsageFunc() == nil {
		templates.ActsAsRootCommand(cmd)
	}
	flagtypes.GLog(cmd.PersistentFlags())

	return cmd
}
Exemplo n.º 14
0
func (sq *SubmitQueue) addWhitelistCommand(root *cobra.Command, config *github_util.Config) {
	genCommitters := &cobra.Command{
		Use:   "gencommiters",
		Short: "Generate the list of people with commit access",
		RunE: func(_ *cobra.Command, _ []string) error {
			if err := config.PreExecute(); err != nil {
				return err
			}
			return sq.doGenCommitters(config)
		},
	}
	root.PersistentFlags().StringVar(&sq.Whitelist, "user-whitelist", "./whitelist.txt", "Path to a whitelist file that contains users to auto-merge.  Required.")
	root.PersistentFlags().StringVar(&sq.Committers, "committers", "./committers.txt", "File in which the list of authorized committers is stored; only used if this list cannot be gotten at run time.  (Merged with whitelist; separate so that it can be auto-generated)")

	root.AddCommand(genCommitters)
}
Exemplo n.º 15
0
func addWhitelistCommand(root *cobra.Command, config *SubmitQueueConfig) {
	genCommitters := &cobra.Command{
		Use:   "gencommiters",
		Short: "Generate the list of people with commit access",
		RunE: func(_ *cobra.Command, _ []string) error {
			if err := config.PreExecute(); err != nil {
				return err
			}
			return config.doGenCommitters()
		},
	}
	root.PersistentFlags().StringVar(&config.Whitelist, "user-whitelist", "./whitelist.txt", "Path to a whitelist file that contains users to auto-merge.  Required.")
	root.PersistentFlags().StringVar(&config.Committers, "committers", "./committers.txt", "File in which the list of authorized committers is stored; only used if this list cannot be gotten at run time.  (Merged with whitelist; separate so that it can be auto-generated)")
	root.Flags().StringVar(&config.WhitelistOverride, "whitelist-override-label", "ok-to-merge", "Github label, if present on a PR it will be merged even if the author isn't in the whitelist")

	root.AddCommand(genCommitters)
}
Exemplo n.º 16
0
func AddFlags(cmd *cobra.Command) {
	cmd.PersistentFlags().BoolVarP(&Insecure, "insecure", "i", Insecure, "Disable tls key checking (client) and listen on http (server)")
	cmd.PersistentFlags().StringVarP(&ApiToken, "api-token", "t", ApiToken, "Token for API Access")
	cmd.PersistentFlags().StringVarP(&ApiHost, "api-host", "H", ApiHost, "Listen address for the API")
	cmd.PersistentFlags().StringVarP(&ApiPort, "api-port", "P", ApiPort, "Listen address for the API")
	cmd.PersistentFlags().StringVarP(&ConfigFile, "conf", "c", ConfigFile, "Configuration file to load")

	cmd.Flags().StringVarP(&ApiKey, "api-key", "k", ApiKey, "SSL key for the api")
	cmd.Flags().StringVarP(&ApiCert, "api-cert", "C", ApiCert, "SSL cert for the api")
	cmd.Flags().StringVarP(&ApiKeyPassword, "api-key-password", "p", ApiKeyPassword, "Password for the SSL key")
	cmd.Flags().StringVarP(&DatabaseConnection, "db-connection", "d", DatabaseConnection, "Database connection string")
	cmd.Flags().StringVarP(&ClusterConnection, "cluster-connection", "r", ClusterConnection, "Cluster connection string (redis://127.0.0.1:6379)")
	cmd.Flags().StringVarP(&ClusterToken, "cluster-token", "T", ClusterToken, "Cluster security token")
	cmd.Flags().StringVarP(&LogLevel, "log-level", "l", LogLevel, "Log level to output")
	cmd.Flags().StringVarP(&LogFile, "log-file", "L", LogFile, "Log file to write to")
	cmd.Flags().BoolVarP(&ProxyIgnore, "proxy-ignore-upstream", "u", Server, "Ignore upstream's(target's) certs when routing")
	cmd.Flags().StringVarP(&RouteHttp, "proxy-http", "x", RouteHttp, "Address to listen on for proxying http")
	cmd.Flags().StringVarP(&RouteTls, "proxy-tls", "X", RouteTls, "Address to listen on for proxying https")
	cmd.Flags().StringVarP(&Balancer, "balancer", "b", Balancer, "Load balancer to use (nginx|lvs)")
	cmd.Flags().StringVarP(&WorkDir, "work-dir", "w", WorkDir, "Directory for portal to use (balancer config)")

	cmd.Flags().BoolVarP(&Server, "server", "s", Server, "Run in server mode")
	cmd.Flags().BoolVarP(&Version, "version", "v", Version, "Print version info and exit")
	cmd.Flags().BoolVarP(&JustProxy, "just-proxy", "j", JustProxy, "Proxy only (no tcp/udp load balancing)")

}
Exemplo n.º 17
0
// CommandFor returns the appropriate command for this base name,
// or the global OpenShift command
func CommandFor(basename string) *cobra.Command {
	var cmd *cobra.Command

	in, out, errout := os.Stdin, os.Stdout, os.Stderr

	// Make case-insensitive and strip executable suffix if present
	if runtime.GOOS == "windows" {
		basename = strings.ToLower(basename)
		basename = strings.TrimSuffix(basename, ".exe")
	}

	switch basename {
	case "openshift-router":
		cmd = irouter.NewCommandTemplateRouter(basename)
	case "openshift-f5-router":
		cmd = irouter.NewCommandF5Router(basename)
	case "openshift-deploy":
		cmd = deployer.NewCommandDeployer(basename)
	case "openshift-recycle":
		cmd = recycle.NewCommandRecycle(basename, out)
	case "openshift-sti-build":
		cmd = builder.NewCommandSTIBuilder(basename)
	case "openshift-docker-build":
		cmd = builder.NewCommandDockerBuilder(basename)
	case "oc", "osc":
		cmd = cli.NewCommandCLI(basename, basename, in, out, errout)
	case "oadm", "osadm":
		cmd = admin.NewCommandAdmin(basename, basename, out, errout)
	case "kubectl":
		cmd = cli.NewCmdKubectl(basename, out)
	case "kube-apiserver":
		cmd = kubernetes.NewAPIServerCommand(basename, basename, out)
	case "kube-controller-manager":
		cmd = kubernetes.NewControllersCommand(basename, basename, out)
	case "kubelet":
		cmd = kubernetes.NewKubeletCommand(basename, basename, out)
	case "kube-proxy":
		cmd = kubernetes.NewProxyCommand(basename, basename, out)
	case "kube-scheduler":
		cmd = kubernetes.NewSchedulerCommand(basename, basename, out)
	case "kubernetes":
		cmd = kubernetes.NewCommand(basename, basename, out)
	case "origin", "atomic-enterprise":
		cmd = NewCommandOpenShift(basename)
	default:
		cmd = NewCommandOpenShift("openshift")
	}

	if cmd.UsageFunc() == nil {
		templates.ActsAsRootCommand(cmd, []string{"options"})
	}
	flagtypes.GLog(cmd.PersistentFlags())

	return cmd
}
Exemplo n.º 18
0
// RegisterCommands registers the resource action CLI commands.
func RegisterCommands(app *cobra.Command, c *client.Client) {
	var command, sub *cobra.Command
	command = &cobra.Command{
		Use:   "create",
		Short: `creates a bottle`,
	}
	tmp1 := new(CreateBottleCommand)
	sub = &cobra.Command{
		Use:   `bottle ["/bottles"]`,
		Short: `A wine bottle`,
		RunE:  func(cmd *cobra.Command, args []string) error { return tmp1.Run(c, args) },
	}
	tmp1.RegisterFlags(sub, c)
	sub.PersistentFlags().BoolVar(&tmp1.PrettyPrint, "pp", false, "Pretty print response body")
	command.AddCommand(sub)
	app.AddCommand(command)
	command = &cobra.Command{
		Use:   "show",
		Short: `shows a bottle`,
	}
	tmp2 := new(ShowBottleCommand)
	sub = &cobra.Command{
		Use:   `bottle ["/bottles/ID"]`,
		Short: `A wine bottle`,
		RunE:  func(cmd *cobra.Command, args []string) error { return tmp2.Run(c, args) },
	}
	tmp2.RegisterFlags(sub, c)
	sub.PersistentFlags().BoolVar(&tmp2.PrettyPrint, "pp", false, "Pretty print response body")
	command.AddCommand(sub)
	app.AddCommand(command)

	dl := new(DownloadCommand)
	dlc := &cobra.Command{
		Use:   "download [PATH]",
		Short: "Download file with given path",
		RunE: func(cmd *cobra.Command, args []string) error {
			return dl.Run(c, args)
		},
	}
	dlc.Flags().StringVar(&dl.OutFile, "out", "", "Output file")
	app.AddCommand(dlc)
}
Exemplo n.º 19
0
func localFlags(cmd *cobra.Command) *flag.FlagSet {

	fs := &flag.FlagSet{}

	if cmd.HasParent() {
		cmd.LocalFlags().VisitAll(func(f *flag.Flag) {
			if f.Name != "help" {
				fs.AddFlag(f)
			}
		})
	} else {
		cmd.LocalFlags().VisitAll(func(f *flag.Flag) {
			if cmd.PersistentFlags().Lookup(f.Name) == nil {
				fs.AddFlag(f)
			}
		})
	}

	return sansAdditionalFlags(fs)
}
Exemplo n.º 20
0
func AddFlags(cmd *cobra.Command) {
	flags := cmd.PersistentFlags()

	flags.StringVarP(&chaincodeLang, "lang", "l", "golang",
		fmt.Sprintf("Language the %s is written in", chainFuncName))
	flags.StringVarP(&chaincodeCtorJSON, "ctor", "c", "{}",
		fmt.Sprintf("Constructor message for the %s in JSON format", chainFuncName))
	flags.StringVarP(&chaincodeAttributesJSON, "attributes", "a", "[]",
		fmt.Sprintf("User attributes for the %s in JSON format", chainFuncName))
	flags.StringVarP(&chaincodePath, "path", "p", common.UndefinedParamValue,
		fmt.Sprintf("Path to %s", chainFuncName))
	flags.StringVarP(&chaincodeName, "name", "n", common.UndefinedParamValue,
		fmt.Sprint("Name of the chaincode returned by the deploy transaction"))
	flags.StringVarP(&chaincodeUsr, "username", "u", common.UndefinedParamValue,
		fmt.Sprint("Username for chaincode operations when security is enabled"))
	flags.StringVarP(&customIDGenAlg, "tid", "t", common.UndefinedParamValue,
		fmt.Sprint("Name of a custom ID generation algorithm (hashing and decoding) e.g. sha256base64"))
	flags.StringVarP(&chainID, "chainID", "C", util.GetTestChainID(),
		fmt.Sprint("The chain on which this command should be executed"))
}
Exemplo n.º 21
0
func setupCommand(notaryCmd *cobra.Command) {
	var versionCmd = &cobra.Command{
		Use:   "version",
		Short: "Print the version number of notary",
		Long:  `print the version number of notary`,
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Printf("notary\n Version:    %s\n Git commit: %s\n", version.NotaryVersion, version.GitCommit)
		},
	}

	notaryCmd.AddCommand(versionCmd)

	notaryCmd.PersistentFlags().StringVarP(&trustDir, "trustDir", "d", "", "Directory where the trust data is persisted to")
	notaryCmd.PersistentFlags().StringVarP(&configFile, "configFile", "c", "", "Path to the configuration file to use")
	notaryCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
	notaryCmd.PersistentFlags().StringVarP(&remoteTrustServer, "server", "s", "", "Remote trust server location")

	cmdKeyGenerator := &keyCommander{
		configGetter: parseConfig,
		retriever:    retriever,
	}

	notaryCmd.AddCommand(cmdKeyGenerator.GetCommand())
	notaryCmd.AddCommand(cmdCert)
	notaryCmd.AddCommand(cmdTufInit)
	notaryCmd.AddCommand(cmdTufList)
	notaryCmd.AddCommand(cmdTufAdd)
	notaryCmd.AddCommand(cmdTufRemove)
	notaryCmd.AddCommand(cmdTufStatus)
	notaryCmd.AddCommand(cmdTufPublish)
	notaryCmd.AddCommand(cmdTufLookup)
	notaryCmd.AddCommand(cmdVerify)
}
Exemplo n.º 22
0
func contextWithFlags(ctx context.Context, cmd *cobra.Command, flags []*Flag) context.Context {
	if len(flags) < 1 {
		return ctx
	}

	values := make(map[string]interface{})
	for _, f := range flags {
		v := cmd.PersistentFlags().Lookup(f.Long).Value.String()
		vi := interface{}(v)
		if f.Type == FlagBool {
			b, err := strconv.ParseBool(v)
			if err != nil {
				vi = v
			} else {
				vi = b
			}
		}

		values["flags."+f.Long] = vi
	}

	return context.WithValues(ctx, values)
}
Exemplo n.º 23
0
// CommandFor returns the appropriate command for this base name,
// or the global OpenShift command
func CommandFor(basename string) *cobra.Command {
	var cmd *cobra.Command

	out := os.Stdout

	// Make case-insensitive and strip executable suffix if present
	if runtime.GOOS == "windows" {
		basename = strings.ToLower(basename)
		basename = strings.TrimSuffix(basename, ".exe")
	}

	switch basename {
	case "atomic-enterprise-router":
		cmd = irouter.NewCommandTemplateRouter(basename)
	case "atomic-enterprise-deploy":
		cmd = deployer.NewCommandDeployer(basename)
	case "atomic-enterprise-gitserver":
		cmd = gitserver.NewCommandGitServer(basename)
	case "oc", "osc":
		cmd = cli.NewCommandCLI(basename, basename)
	case "oadm", "osadm":
		cmd = admin.NewCommandAdmin(basename, basename, out)
	case "kubectl":
		cmd = cli.NewCmdKubectl(basename, out)
	case "kube-apiserver":
		cmd = kubernetes.NewAPIServerCommand(basename, basename, out)
	case "kube-controller-manager":
		cmd = kubernetes.NewControllersCommand(basename, basename, out)
	case "kubelet":
		cmd = kubernetes.NewKubeletCommand(basename, basename, out)
	case "kube-proxy":
		cmd = kubernetes.NewProxyCommand(basename, basename, out)
	case "kube-scheduler":
		cmd = kubernetes.NewSchedulerCommand(basename, basename, out)
	case "kubernetes":
		cmd = kubernetes.NewCommand(basename, basename, out)
	case "origin":
		cmd = NewCommandAtomicEnterprise("origin")
	default:
		cmd = NewCommandAtomicEnterprise("atomic-enterprise")
	}

	if cmd.UsageFunc() == nil {
		templates.ActsAsRootCommand(cmd)
	}
	flagtypes.GLog(cmd.PersistentFlags())

	return cmd
}
Exemplo n.º 24
0
func run(cmd *cobra.Command, args []string) {
	var (
		cfg     Config
		cfgPath = cmd.PersistentFlags().Lookup("conf").Value.String()
	)
	log.SetLevel(log.InfoLevel)
	err := config.Read(cfgPath, &cfg)

	if err != nil {
		switch cause := errors.Cause(err).(type) {
		case *config.InvalidConfigError:
			log.Error("config file: ", cause)
		default:
			log.Error(err)
		}
		os.Exit(1)
	}

	driver, err := initDriver(cfg)
	if err != nil {
		log.Error(err)
		os.Exit(1)
	}

	mux := initMux(driver)
	addr := fmt.Sprintf("0.0.0.0:%d", cfg.Port)

	http.Run(http.Config{
		ListenAddr: addr,
		Handler:    mux,
		OnStarting: func() {
			log.Infof("starting federation server - %s", app.Version())
			log.Infof("listening on %s", addr)
		},
	})
}
Exemplo n.º 25
0
// AddFlags adds the available cli flags
func AddFlags(cmd *cobra.Command) {
	// api
	cmd.Flags().StringVarP(&ApiCrt, "api-crt", "C", ApiCrt, "Path to SSL crt for API access")
	cmd.Flags().StringVarP(&ApiKey, "api-key", "k", ApiKey, "Path to SSL key for API access")
	cmd.Flags().StringVarP(&ApiKeyPassword, "api-key-password", "p", ApiKeyPassword, "Password for SSL key")
	cmd.PersistentFlags().StringVarP(&ApiListen, "api-listen", "H", ApiListen, "Listen address for the API (ip:port)")
	cmd.PersistentFlags().StringVarP(&ApiToken, "token", "t", ApiToken, "Token for API Access")
	cmd.PersistentFlags().BoolVarP(&Insecure, "insecure", "i", Insecure, "Disable tls key checking (client) and listen on http (api)")

	// dns
	cmd.Flags().StringVarP(&L2Connect, "l2-connect", "2", L2Connect, "Connection string for the l2 cache")
	cmd.Flags().IntVarP(&TTL, "ttl", "T", TTL, "Default TTL for DNS records")
	cmd.Flags().StringVarP(&Domain, "domain", "d", Domain, "Parent domain for requests")
	cmd.Flags().StringVarP(&DnsListen, "dns-listen", "O", DnsListen, "Listen address for DNS requests (ip:port)")

	// core
	cmd.Flags().StringVarP(&LogLevel, "log-level", "l", LogLevel, "Log level to output [fatal|error|info|debug|trace]")
	cmd.Flags().BoolVarP(&Server, "server", "s", Server, "Run in server mode")
	cmd.PersistentFlags().StringVarP(&ConfigFile, "config-file", "c", ConfigFile, "Configuration file to load")

	cmd.Flags().BoolVarP(&Version, "version", "v", Version, "Print version info and exit")
}
Exemplo n.º 26
0
func (n *notaryCommander) GetCommand() *cobra.Command {
	notaryCmd := cobra.Command{
		Use:           "notary",
		Short:         "Notary allows the creation of trusted collections.",
		Long:          "Notary allows the creation and management of collections of signed targets, allowing the signing and validation of arbitrary content.",
		SilenceUsage:  true, // we don't want to print out usage for EVERY error
		SilenceErrors: true, // we do our own error reporting with fatalf
		Run:           func(cmd *cobra.Command, args []string) { cmd.Usage() },
	}
	notaryCmd.SetOutput(os.Stdout)
	notaryCmd.AddCommand(&cobra.Command{
		Use:   "version",
		Short: "Print the version number of notary",
		Long:  "Print the version number of notary",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Printf("notary\n Version:    %s\n Git commit: %s\n", version.NotaryVersion, version.GitCommit)
		},
	})

	notaryCmd.PersistentFlags().StringVarP(
		&n.trustDir, "trustDir", "d", "", "Directory where the trust data is persisted to")
	notaryCmd.PersistentFlags().StringVarP(
		&n.configFile, "configFile", "c", "", "Path to the configuration file to use")
	notaryCmd.PersistentFlags().BoolVarP(&n.verbose, "verbose", "v", false, "Verbose output")
	notaryCmd.PersistentFlags().BoolVarP(&n.debug, "debug", "D", false, "Debug output")
	notaryCmd.PersistentFlags().StringVarP(&n.remoteTrustServer, "server", "s", "", "Remote trust server location")
	notaryCmd.PersistentFlags().StringVar(&n.tlsCAFile, "tlscacert", "", "Trust certs signed only by this CA")
	notaryCmd.PersistentFlags().StringVar(&n.tlsCertFile, "tlscert", "", "Path to TLS certificate file")
	notaryCmd.PersistentFlags().StringVar(&n.tlsKeyFile, "tlskey", "", "Path to TLS key file")

	cmdKeyGenerator := &keyCommander{
		configGetter: n.parseConfig,
		getRetriever: n.getRetriever,
		input:        os.Stdin,
	}

	cmdDelegationGenerator := &delegationCommander{
		configGetter: n.parseConfig,
		retriever:    n.getRetriever(),
	}

	cmdTUFGenerator := &tufCommander{
		configGetter: n.parseConfig,
		retriever:    n.getRetriever(),
	}

	notaryCmd.AddCommand(cmdKeyGenerator.GetCommand())
	notaryCmd.AddCommand(cmdDelegationGenerator.GetCommand())

	cmdTUFGenerator.AddToCommand(&notaryCmd)

	return &notaryCmd
}
Exemplo n.º 27
0
Arquivo: cmd.go Projeto: pmorie/geard
// Parse the command line arguments and invoke one of the support subcommands.
func (ctx *CommandContext) RegisterRemote(parent *cobra.Command) {
	parent.PersistentFlags().StringVar(&(ctx.deploymentPath), "with", "", "Provide a deployment descriptor to operate on")

	deployCmd := &cobra.Command{
		Use:   "deploy <file|url> <host>...",
		Short: "Deploy a set of containers to the named hosts",
		Long:  "Given a simple description of a group of containers, wire them together using the gear primitives.",
		Run:   ctx.deployContainers,
	}
	deployCmd.Flags().BoolVar(&(ctx.isolate), "isolate", false, "Use an isolated container running as a user")
	deployCmd.Flags().Int64VarP(&(ctx.timeout), "timeout", "", 300, "Number of seconds to wait for a response")
	parent.AddCommand(deployCmd)

	installImageCmd := &cobra.Command{
		Use:   "install <image> <name>... [<env>]",
		Short: "Install a docker image as a systemd service",
		Long:  "Install a docker image as one or more systemd services on one or more servers.\n\nSpecify a location on a remote server with <host>[:<port>]/<name> instead of <name>.  The default port is 2223.",
		Run:   ctx.installImage,
	}
	installImageCmd.Flags().VarP(&(ctx.portPairs), "ports", "p", "List of comma separated port pairs to bind '<internal>:<external>,...'. Use zero to request a port be assigned.")
	installImageCmd.Flags().VarP(&(ctx.networkLinks), "net-links", "n", "List of comma separated port pairs to wire '<local_host>:<local_port>:<remote_host>:<remote_port>,...'. local_host may be empty. It defaults to 127.0.0.1.")
	installImageCmd.Flags().BoolVar(&(ctx.start), "start", false, "Start the container immediately")
	installImageCmd.Flags().BoolVar(&(ctx.isolate), "isolate", false, "Use an isolated container running as a user")
	installImageCmd.Flags().BoolVar(&(ctx.sockAct), "socket-activated", false, "Use a socket-activated container (experimental, requires Docker branch)")
	installImageCmd.Flags().StringVar(&(ctx.environment.Path), "env-file", "", "Path to an environment file to load")
	installImageCmd.Flags().StringVar(&(ctx.environment.Description.Source), "env-url", "", "A url to download environment files from")
	installImageCmd.Flags().StringVar((*string)(&(ctx.environment.Description.Id)), "env-id", "", "An optional identifier for the environment being set")
	installImageCmd.Flags().StringVar(&(ctx.systemdSlice), "slice", cjobs.DefaultSlice, "systemd slice to use. default: "+cjobs.DefaultSlice)
	parent.AddCommand(installImageCmd)

	deleteCmd := &cobra.Command{
		Use:   "delete <name>...",
		Short: "Delete an installed container",
		Long:  "Deletes one or more installed containers from the system.  Will not clean up unused images.",
		Run:   ctx.deleteContainer,
	}
	parent.AddCommand(deleteCmd)

	buildCmd := &cobra.Command{
		Use:   "build <source> <image> <tag> [<env>]",
		Short: "(Local) Build a new image on this host",
		Long:  "Build a new Docker image named <tag> from a source repository and base image.",
		Run:   ctx.buildImage,
	}
	buildCmd.Flags().StringVarP(&(ctx.dockerSocket), "docker-socket", "S", "unix:///var/run/docker.sock", "Set the docker socket to use")
	buildCmd.Flags().BoolVar(&(ctx.buildReq.Clean), "clean", false, "Perform a clean build")
	buildCmd.Flags().StringVarP(&(ctx.buildReq.Ref), "ref", "r", "", "Specify a ref to check-out")
	buildCmd.Flags().BoolVar(&(ctx.buildReq.Verbose), "verbose", false, "Enable verbose output")
	buildCmd.Flags().StringVar(&(ctx.buildReq.CallbackUrl), "callbackUrl", "", "Specify a URL to invoke via HTTP POST upon build completion")
	buildCmd.Flags().StringVar(&(ctx.environment.Path), "env-file", "", "Path to an environment file to load")
	buildCmd.Flags().StringVar(&(ctx.environment.Description.Source), "env-url", "", "A url to download environment files from")
	buildCmd.Flags().StringVarP(&(ctx.buildReq.ScriptsUrl), "scripts", "s", "", "Specify a URL for the assemble and run scripts")
	parent.AddCommand(buildCmd)

	setEnvCmd := &cobra.Command{
		Use:   "set-env <name>... [<env>]",
		Short: "Set environment variable values on servers",
		Long:  "Adds the listed environment values to the specified locations. The name is the environment id that multiple containers may reference. You can pass an environment file or key value pairs on the commandline.",
		Run:   ctx.setEnvironment,
	}
	setEnvCmd.Flags().BoolVar(&(ctx.resetEnv), "reset", false, "Remove any existing values")
	setEnvCmd.Flags().StringVar(&(ctx.environment.Path), "env-file", "", "Path to an environment file to load")
	parent.AddCommand(setEnvCmd)

	envCmd := &cobra.Command{
		Use:   "env <name>...",
		Short: "Retrieve environment variable values by id",
		Long:  "Return the environment variables matching the provided ids",
		Run:   ctx.showEnvironment,
	}
	parent.AddCommand(envCmd)

	linkCmd := &cobra.Command{
		Use:   "link <name>...",
		Short: "Set network links for the named containers",
		Long:  "Sets the network links for the named containers. A restart may be required to use the latest links.",
		Run:   ctx.linkContainers,
	}
	linkCmd.Flags().VarP(&(ctx.networkLinks), "net-links", "n", "List of comma separated port pairs to wire '<local_host>:local_port>:<host>:<remote_port>,...'. local_host may be empty. It defaults to 127.0.0.1")
	parent.AddCommand(linkCmd)

	startCmd := &cobra.Command{
		Use:   "start <name>...",
		Short: "Invoke systemd to start a container",
		Long:  "Queues the start and immediately returns.", //  Use -f to attach to the logs.",
		Run:   ctx.startContainer,
	}
	parent.AddCommand(startCmd)

	stopCmd := &cobra.Command{
		Use:   "stop <name>... [--no-wait]",
		Short: "Invoke systemd to stop a container",
		Long:  "Stop the specified container.  Waits for the container to stop unless --no-wait is specified",
		Run:   ctx.stopContainer,
	}
	stopCmd.Flags().BoolVarP(&(ctx.noWait), "no-wait", "n", false, "Do not wait for the container to stop")
	parent.AddCommand(stopCmd)

	restartCmd := &cobra.Command{
		Use:   "restart <name>...",
		Short: "Invoke systemd to restart a container",
		Long:  "Queues the restart and immediately returns.", //  Use -f to attach to the logs.",
		Run:   ctx.restartContainer,
	}
	parent.AddCommand(restartCmd)

	statusCmd := &cobra.Command{
		Use:   "status <name>...",
		Short: "Retrieve the systemd status of one or more containers",
		Long:  "Shows the equivalent of 'systemctl status ctr-<name>' for each listed unit",
		Run:   ctx.containerStatus,
	}
	parent.AddCommand(statusCmd)

	listUnitsCmd := &cobra.Command{
		Use:   "list-units <host>...",
		Short: "Retrieve the list of services across all hosts",
		Long:  "Shows the equivalent of 'systemctl list-units ctr-<name>' for each installed container",
		Run:   ctx.listUnits,
	}
	listUnitsCmd.Flags().BoolVarP(&(ctx.all), "all", "a", false, "Include inactive or unloaded containers")
	listUnitsCmd.Flags().BoolVarP(&(ctx.quiet), "quiet", "q", false, "Return only the id of each unit")
	parent.AddCommand(listUnitsCmd)

	purgeCmd := &cobra.Command{
		Use:   "purge",
		Short: "Stop and disable all containers",
		Long:  "Disable all registered resources from systemd to allow them to be removed from the system.  Will reload the systemd daemon config.",
		Run:   ctx.purge,
	}
	parent.AddCommand(purgeCmd)
}
Exemplo n.º 28
0
func GetToken(cmd *cobra.Command, args []string) {
	fmt.Printf("Getting token and saving it to %v\n",
		cmd.PersistentFlags().Lookup("tokenFile"))
}
Exemplo n.º 29
0
// Associates all marathon service commands to specified parent
func associateServiceCommands(parent *cobra.Command) {
	parent.PersistentFlags().Bool(INSECURE_FLAG, false, "Skips Insecure TLS/HTTPS Certificate checks")
	viper.BindPFlag(INSECURE_FLAG, parent.PersistentFlags().Lookup(INSECURE_FLAG))

	parent.AddCommand(appCmd, groupCmd, deployCmd, taskCmd, eventCmd, serverCmd)
}
Exemplo n.º 30
0
// AddRootFlags will add all of the flags needed for the github config to the cobra command
func (config *Config) AddRootFlags(cmd *cobra.Command) {
	cmd.PersistentFlags().StringVar(&config.Token, "token", "", "The OAuth Token to use for requests.")
	cmd.PersistentFlags().StringVar(&config.TokenFile, "token-file", "", "The file containing the OAuth Token to use for requests.")
	cmd.PersistentFlags().IntVar(&config.MinPRNumber, "min-pr-number", 0, "The minimum PR to start with")
	cmd.PersistentFlags().IntVar(&config.MaxPRNumber, "max-pr-number", maxInt, "The maximum PR to start with")
	cmd.PersistentFlags().BoolVar(&config.DryRun, "dry-run", true, "If true, don't actually merge anything")
	cmd.PersistentFlags().BoolVar(&config.useMemoryCache, "use-http-cache", true, "If true, use a client side HTTP cache for API requests.")
	cmd.PersistentFlags().StringVar(&config.Org, "organization", "kubernetes", "The github organization to scan")
	cmd.PersistentFlags().StringVar(&config.Project, "project", "kubernetes", "The github project to scan")
	cmd.PersistentFlags().StringVar(&config.state, "state", "open", "State of PRs to process: 'open', 'all', etc")
	cmd.PersistentFlags().StringSliceVar(&config.labels, "labels", []string{}, "CSV list of label which should be set on processed PRs. Unset is all labels.")
	cmd.PersistentFlags().StringVar(&config.Address, "address", ":8080", "The address to listen on for HTTP Status")
	cmd.PersistentFlags().StringVar(&config.WWWRoot, "www", "www", "Path to static web files to serve from the webserver")
	cmd.PersistentFlags().AddGoFlagSet(goflag.CommandLine)
}