lib/envflag: substitute dots with underscores in env var names if -envflag.enable is set

See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/311
This commit is contained in:
Aliaksandr Valialkin 2020-02-24 21:14:22 +02:00
parent ae51300973
commit fed2959658
2 changed files with 12 additions and 3 deletions

View file

@ -138,7 +138,8 @@ The following command-line flags are used the most:
Pass `-help` to see all the available flags with description and default values.
Default flag values may be read from environment variables if `-envflag.enable` command-line flag is set.
See [this feature request](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/311) for more details.
Substitute dots with underscores in env var names. Alternative syntax can be used for setting repeatable flags:
`-arg=foo -arg=bar` can be written as `-arg=foo,bar`. See [this feature request](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/311) for more details.
It is recommended setting up [monitoring](#monitoring) for VictoriaMetrics.

View file

@ -4,6 +4,7 @@ import (
"flag"
"log"
"os"
"strings"
)
var enable = flag.Bool("envflag.enable", false, "Whether to enable reading flags from environment variables additionally to command line. "+
@ -34,11 +35,18 @@ func Parse() {
return
}
// Get flag value from environment var.
if v, ok := os.LookupEnv(f.Name); ok {
fname := getEnvFlagName(f.Name)
if v, ok := os.LookupEnv(fname); ok {
if err := f.Value.Set(v); err != nil {
// Do not use lib/logger here, since it is uninitialized yet.
log.Fatalf("cannot set flag %s to %q, which is read from environment variable: %s", f.Name, v, err)
log.Fatalf("cannot set flag %s to %q, which is read from environment variable %q: %s", f.Name, v, fname, err)
}
}
})
}
func getEnvFlagName(s string) string {
// Substitute dots with underscores, since env var names cannot contain dots.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/311#issuecomment-586354129 for details.
return strings.ReplaceAll(s, ".", "_")
}