Skip to content

Commit

Permalink
chore: consolidate all CLI configuration (#233)
Browse files Browse the repository at this point in the history
  • Loading branch information
enocom committed Jan 19, 2023
1 parent d412475 commit 6dc8bd0
Show file tree
Hide file tree
Showing 5 changed files with 261 additions and 204 deletions.
93 changes: 30 additions & 63 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,30 +82,10 @@ func Execute() {
// Command represents an invocation of the AlloyDB Auth Proxy.
type Command struct {
*cobra.Command
conf *proxy.Config
logger alloydb.Logger
dialer alloydb.Dialer

cleanup func() error
disableTraces bool
telemetryTracingSampleRate int
disableMetrics bool
telemetryProject string
telemetryPrefix string
prometheus bool
prometheusNamespace string
healthCheck bool
httpAddress string
httpPort string
quiet bool
otherUserAgents string

// impersonationChain is a comma separated list of one or more service
// accounts. The first entry in the chain is the impersonation target. Any
// additional service accounts after the target are delegates. The
// roles/iam.serviceAccountTokenCreator must be configured for each account
// that will be impersonated.
impersonationChain string
conf *proxy.Config
logger alloydb.Logger
dialer alloydb.Dialer
cleanup func() error
}

// Option is a function that configures a Command.
Expand Down Expand Up @@ -337,7 +317,7 @@ func NewCommand(opts ...Option) *Command {
if c.conf.StructuredLogs {
c.logger, c.cleanup = log.NewStructuredLogger()
}
if c.quiet {
if c.conf.Quiet {
c.logger = log.NewStdLogger(io.Discard, os.Stderr)
}
err := parseConfig(c, c.conf, args)
Expand All @@ -356,7 +336,7 @@ func NewCommand(opts ...Option) *Command {
pflags := cmd.PersistentFlags()

// Global-only flags
pflags.StringVar(&c.otherUserAgents, "user-agent", "",
pflags.StringVar(&c.conf.OtherUserAgents, "user-agent", "",
"Space separated list of additional user agents, e.g. cloud-sql-proxy-operator/0.0.1")
pflags.StringVarP(&c.conf.Token, "token", "t", "",
"Bearer token used for authorization.")
Expand Down Expand Up @@ -384,30 +364,30 @@ the maximum time has passed. Defaults to 0s.`)
pflags.StringVar(&c.conf.FUSETempDir, "fuse-tmp-dir",
filepath.Join(os.TempDir(), "alloydb-tmp"),
"Temp dir for Unix sockets created with FUSE")
pflags.StringVar(&c.impersonationChain, "impersonate-service-account", "",
pflags.StringVar(&c.conf.ImpersonationChain, "impersonate-service-account", "",
`Comma separated list of service accounts to impersonate. Last value
+is the target account.`)
cmd.PersistentFlags().BoolVar(&c.quiet, "quiet", false, "Log error messages only")
cmd.PersistentFlags().BoolVar(&c.conf.Quiet, "quiet", false, "Log error messages only")

pflags.StringVar(&c.telemetryProject, "telemetry-project", "",
pflags.StringVar(&c.conf.TelemetryProject, "telemetry-project", "",
"Enable Cloud Monitoring and Cloud Trace integration with the provided project ID.")
pflags.BoolVar(&c.disableTraces, "disable-traces", false,
pflags.BoolVar(&c.conf.DisableTraces, "disable-traces", false,
"Disable Cloud Trace integration (used with telemetry-project)")
pflags.IntVar(&c.telemetryTracingSampleRate, "telemetry-sample-rate", 10_000,
pflags.IntVar(&c.conf.TelemetryTracingSampleRate, "telemetry-sample-rate", 10_000,
"Configure the denominator of the probabilistic sample rate of traces sent to Cloud Trace\n(e.g., 10,000 traces 1/10,000 calls).")
pflags.BoolVar(&c.disableMetrics, "disable-metrics", false,
pflags.BoolVar(&c.conf.DisableMetrics, "disable-metrics", false,
"Disable Cloud Monitoring integration (used with telemetry-project)")
pflags.StringVar(&c.telemetryPrefix, "telemetry-prefix", "",
pflags.StringVar(&c.conf.TelemetryPrefix, "telemetry-prefix", "",
"Prefix to use for Cloud Monitoring metrics.")
pflags.BoolVar(&c.prometheus, "prometheus", false,
pflags.BoolVar(&c.conf.Prometheus, "prometheus", false,
"Enable Prometheus HTTP endpoint /metrics")
pflags.StringVar(&c.prometheusNamespace, "prometheus-namespace", "",
pflags.StringVar(&c.conf.PrometheusNamespace, "prometheus-namespace", "",
"Use the provided Prometheus namespace for metrics")
pflags.StringVar(&c.httpAddress, "http-address", "localhost",
pflags.StringVar(&c.conf.HTTPAddress, "http-address", "localhost",
"Address for Prometheus and health check server")
pflags.StringVar(&c.httpPort, "http-port", "9090",
pflags.StringVar(&c.conf.HTTPPort, "http-port", "9090",
"Port for the Prometheus server to use")
pflags.BoolVar(&c.healthCheck, "health-check", false,
pflags.BoolVar(&c.conf.HealthCheck, "health-check", false,
`Enables HTTP endpoints /startup, /liveness, and /readiness
that report on the proxy's health. Endpoints are available on localhost
only. Uses the port specified by the http-port flag.`)
Expand Down Expand Up @@ -521,23 +501,10 @@ func parseConfig(cmd *Command, conf *proxy.Config, args []string) error {
}

if userHasSet("user-agent") {
defaultUserAgent += " " + cmd.otherUserAgents
defaultUserAgent += " " + cmd.conf.OtherUserAgents
conf.UserAgent = defaultUserAgent
}

if cmd.impersonationChain != "" {
accts := strings.Split(cmd.impersonationChain, ",")
conf.ImpersonateTarget = accts[0]
// Assign delegates if the chain is more than one account. Delegation
// goes from last back towards target, e.g., With sa1,sa2,sa3, sa3
// delegates to sa2, which impersonates the target sa1.
if l := len(accts); l > 1 {
for i := l - 1; i > 0; i-- {
conf.ImpersonateDelegates = append(conf.ImpersonateDelegates, accts[i])
}
}
}

var ics []proxy.InstanceConnConfig
for _, a := range args {
// split into instance uri and query parameters
Expand Down Expand Up @@ -615,12 +582,12 @@ func runSignalWrapper(cmd *Command) error {

// Configure collectors before the proxy has started to ensure we are
// collecting metrics before *ANY* AlloyDB Admin API calls are made.
enableMetrics := !cmd.disableMetrics
enableTraces := !cmd.disableTraces
if cmd.telemetryProject != "" && (enableMetrics || enableTraces) {
enableMetrics := !cmd.conf.DisableMetrics
enableTraces := !cmd.conf.DisableTraces
if cmd.conf.TelemetryProject != "" && (enableMetrics || enableTraces) {
sd, err := stackdriver.NewExporter(stackdriver.Options{
ProjectID: cmd.telemetryProject,
MetricPrefix: cmd.telemetryPrefix,
ProjectID: cmd.conf.TelemetryProject,
MetricPrefix: cmd.conf.TelemetryPrefix,
})
if err != nil {
return err
Expand All @@ -632,7 +599,7 @@ func runSignalWrapper(cmd *Command) error {
}
}
if enableTraces {
s := trace.ProbabilitySampler(1 / float64(cmd.telemetryTracingSampleRate))
s := trace.ProbabilitySampler(1 / float64(cmd.conf.TelemetryTracingSampleRate))
trace.ApplyConfig(trace.Config{DefaultSampler: s})
trace.RegisterExporter(sd)
}
Expand All @@ -646,10 +613,10 @@ func runSignalWrapper(cmd *Command) error {
needsHTTPServer bool
mux = http.NewServeMux()
)
if cmd.prometheus {
if cmd.conf.Prometheus {
needsHTTPServer = true
e, err := prometheus.NewExporter(prometheus.Options{
Namespace: cmd.prometheusNamespace,
Namespace: cmd.conf.PrometheusNamespace,
})
if err != nil {
return err
Expand Down Expand Up @@ -704,10 +671,10 @@ func runSignalWrapper(cmd *Command) error {
}()

notify := func() {}
if cmd.healthCheck {
if cmd.conf.HealthCheck {
needsHTTPServer = true
cmd.logger.Infof("Starting health check server at %s",
net.JoinHostPort(cmd.httpAddress, cmd.httpPort))
net.JoinHostPort(cmd.conf.HTTPAddress, cmd.conf.HTTPPort))
hc := healthcheck.NewCheck(p, cmd.logger)
mux.HandleFunc("/startup", hc.HandleStartup)
mux.HandleFunc("/readiness", hc.HandleReadiness)
Expand All @@ -718,7 +685,7 @@ func runSignalWrapper(cmd *Command) error {
// Start the HTTP server if anything requiring HTTP is specified.
if needsHTTPServer {
server := &http.Server{
Addr: net.JoinHostPort(cmd.httpAddress, cmd.httpPort),
Addr: net.JoinHostPort(cmd.conf.HTTPAddress, cmd.conf.HTTPPort),
Handler: mux,
}
// Start the HTTP server.
Expand Down
Loading

0 comments on commit 6dc8bd0

Please sign in to comment.