func NewCommand()

in cmd/root.go [390:545]


func NewCommand(opts ...Option) *Command {
	rootCmd := &cobra.Command{
		Use:     "cloud-sql-proxy INSTANCE_CONNECTION_NAME...",
		Version: versionString,
		Short:   "cloud-sql-proxy authorizes and encrypts connections to Cloud SQL.",
		//remove the inline annotation required by release-please to update version.
		Long: strings.ReplaceAll(longHelp, "{x-release-please-version}", ""),
	}

	logger := log.NewStdLogger(os.Stdout, os.Stderr)
	c := &Command{
		Command: rootCmd,
		logger:  logger,
		cleanup: func() error { return nil },
		conf: &proxy.Config{
			UserAgent: userAgent,
		},
	}
	var waitCmd = &cobra.Command{
		Use:   "wait",
		Short: "Wait for another Proxy process to start",
		Long:  waitHelp,
		RunE:  runWaitCmd,
	}
	waitFlags := waitCmd.Flags()
	waitFlags.DurationP(
		waitMaxFlag, "m",
		30*time.Second,
		"maximum amount of time to wait for startup",
	)
	rootCmd.AddCommand(waitCmd)

	rootCmd.Args = func(_ *cobra.Command, args []string) error {
		// Load the configuration file before running the command. This should
		// ensure that the configuration is loaded in the correct order:
		//
		//   flags > environment variables > configuration files
		//
		// See https://github.com/carolynvs/stingoftheviper for more info
		return loadConfig(c, args, opts)
	}
	rootCmd.RunE = func(*cobra.Command, []string) error { return runSignalWrapper(c) }

	// Flags that apply only to the root command
	localFlags := rootCmd.Flags()
	// Flags that apply to all sub-commands
	globalFlags := rootCmd.PersistentFlags()

	localFlags.BoolP("help", "h", false, "Display help information for cloud-sql-proxy")
	localFlags.BoolP("version", "v", false, "Print the cloud-sql-proxy version")

	localFlags.StringVar(&c.conf.Filepath, "config-file", c.conf.Filepath,
		"Path to a TOML file containing configuration options.")
	localFlags.StringVar(&c.conf.OtherUserAgents, "user-agent", "",
		"Space separated list of additional user agents, e.g. cloud-sql-proxy-operator/0.0.1")
	localFlags.StringVarP(&c.conf.Token, "token", "t", "",
		"Use bearer token as a source of IAM credentials.")
	localFlags.StringVar(&c.conf.LoginToken, "login-token", "",
		"Use bearer token as a database password (used with token and auto-iam-authn only)")
	localFlags.StringVarP(&c.conf.CredentialsFile, "credentials-file", "c", "",
		"Use service account key file as a source of IAM credentials.")
	localFlags.StringVarP(&c.conf.CredentialsJSON, "json-credentials", "j", "",
		"Use service account key JSON as a source of IAM credentials.")
	localFlags.BoolVarP(&c.conf.GcloudAuth, "gcloud-auth", "g", false,
		`Use gclouds user credentials as a source of IAM credentials.
NOTE: this flag is a legacy feature and generally should not be used.
Instead prefer Application Default Credentials
(enabled with: gcloud auth application-default login) which
the Proxy will then pick-up automatically.`)
	localFlags.BoolVarP(&c.conf.StructuredLogs, "structured-logs", "l", false,
		"Enable structured logging with LogEntry format")
	localFlags.BoolVar(&c.conf.DebugLogs, "debug-logs", false,
		"Enable debug logging")
	localFlags.Uint64Var(&c.conf.MaxConnections, "max-connections", 0,
		"Limit the number of connections. Default is no limit.")
	localFlags.DurationVar(&c.conf.WaitBeforeClose, "min-sigterm-delay", 0,
		"The number of seconds to accept new connections after receiving a TERM signal.")
	localFlags.DurationVar(&c.conf.WaitOnClose, "max-sigterm-delay", 0,
		"Maximum number of seconds to wait for connections to close after receiving a TERM signal.")
	localFlags.StringVar(&c.conf.TelemetryProject, "telemetry-project", "",
		"Enable Cloud Monitoring and Cloud Trace with the provided project ID.")
	localFlags.BoolVar(&c.conf.DisableTraces, "disable-traces", false,
		"Disable Cloud Trace integration (used with --telemetry-project)")
	localFlags.IntVar(&c.conf.TelemetryTracingSampleRate, "telemetry-sample-rate", 10_000,
		"Set the Cloud Trace sample rate. A smaller number means more traces.")
	localFlags.BoolVar(&c.conf.DisableMetrics, "disable-metrics", false,
		"Disable Cloud Monitoring integration (used with --telemetry-project)")
	localFlags.StringVar(&c.conf.TelemetryPrefix, "telemetry-prefix", "",
		"Prefix for Cloud Monitoring metrics.")
	localFlags.BoolVar(&c.conf.ExitZeroOnSigterm, "exit-zero-on-sigterm", false,
		"Exit with 0 exit code when Sigterm received (default is 143)")
	localFlags.BoolVar(&c.conf.Prometheus, "prometheus", false,
		"Enable Prometheus HTTP endpoint /metrics on localhost")
	localFlags.StringVar(&c.conf.PrometheusNamespace, "prometheus-namespace", "",
		"Use the provided Prometheus namespace for metrics")
	globalFlags.StringVar(&c.conf.HTTPAddress, httpAddressFlag, "localhost",
		"Address for Prometheus and health check server")
	globalFlags.StringVar(&c.conf.HTTPPort, httpPortFlag, "9090",
		"Port for Prometheus and health check server")
	localFlags.BoolVar(&c.conf.Debug, "debug", false,
		"Enable pprof on the localhost admin server")
	localFlags.BoolVar(&c.conf.QuitQuitQuit, "quitquitquit", false,
		"Enable quitquitquit endpoint on the localhost admin server")
	localFlags.StringVar(&c.conf.AdminPort, "admin-port", "9091",
		"Port for localhost-only admin server")
	localFlags.BoolVar(&c.conf.HealthCheck, "health-check", false,
		"Enables health check endpoints /startup, /liveness, and /readiness on localhost.")
	localFlags.StringVar(&c.conf.APIEndpointURL, "sqladmin-api-endpoint", "",
		"API endpoint for all Cloud SQL Admin API requests. (default: https://sqladmin.googleapis.com)")
	localFlags.StringVar(&c.conf.UniverseDomain, "universe-domain", "",
		"Universe Domain for non-GDU environments. (default: googleapis.com)")
	localFlags.StringVar(&c.conf.QuotaProject, "quota-project", "",
		`Specifies the project to use for Cloud SQL Admin API quota tracking.
The IAM principal must have the "serviceusage.services.use" permission
for the given project. See https://cloud.google.com/service-usage/docs/overview and
https://cloud.google.com/storage/docs/requester-pays`)
	localFlags.StringVar(&c.conf.FUSEDir, "fuse", "",
		"Mount a directory at the path using FUSE to access Cloud SQL instances.")
	localFlags.StringVar(&c.conf.FUSETempDir, "fuse-tmp-dir",
		filepath.Join(os.TempDir(), "csql-tmp"),
		"Temp dir for Unix sockets created with FUSE")
	localFlags.StringVar(&c.conf.ImpersonationChain, "impersonate-service-account", "",
		`Comma separated list of service accounts to impersonate. Last value
is the target account.`)
	localFlags.BoolVar(&c.conf.Quiet, "quiet", false, "Log error messages only")
	localFlags.BoolVar(&c.conf.AutoIP, "auto-ip", false,
		`Supports legacy behavior of v1 and will try to connect to first IP
address returned by the SQL Admin API. In most cases, this flag should not be used.
Prefer default of public IP or use --private-ip instead.`)
	localFlags.BoolVar(&c.conf.LazyRefresh, "lazy-refresh", false,
		`Configure a lazy refresh where connection info is retrieved only if
the cached copy has expired. Use this setting in environments where the
CPU may be throttled and a background refresh cannot run reliably
(e.g., Cloud Run)`,
	)

	localFlags.BoolVar(&c.conf.RunConnectionTest, "run-connection-test", false, `Runs a connection test
against all specified instances. If an instance is unreachable, the Proxy exits with a failure
status code.`)

	// Global and per instance flags
	localFlags.StringVarP(&c.conf.Addr, "address", "a", "127.0.0.1",
		"(*) Address to bind Cloud SQL instance listeners.")
	localFlags.IntVarP(&c.conf.Port, "port", "p", 0,
		"(*) Initial port for listeners. Subsequent listeners increment from this value.")
	localFlags.StringVarP(&c.conf.UnixSocket, "unix-socket", "u", "",
		`(*) Enables Unix sockets for all listeners with the provided directory.`)
	localFlags.BoolVarP(&c.conf.IAMAuthN, "auto-iam-authn", "i", false,
		"(*) Enables Automatic IAM Authentication for all instances")
	localFlags.BoolVar(&c.conf.PrivateIP, "private-ip", false,
		"(*) Connect to the private ip address for all instances")
	localFlags.BoolVar(&c.conf.PSC, "psc", false,
		"(*) Connect to the PSC endpoint for all instances")

	return c
}