1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.arvados.org/arvados.git/sdk/go/arvados"
20 "github.com/ghodss/yaml"
21 "github.com/imdario/mergo"
22 "github.com/sirupsen/logrus"
25 var ErrNoClustersDefined = errors.New("config does not define any clusters")
29 Logger logrus.FieldLogger
30 SkipDeprecated bool // Don't load deprecated config keys
31 SkipLegacy bool // Don't load legacy config files
32 SkipAPICalls bool // Don't do checks that call RailsAPI/controller
37 CrunchDispatchSlurmPath string
41 KeepBalancePath string
46 // NewLoader returns a new Loader with Stdin and Logger set to the
47 // given values, and all config paths set to their default values.
48 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
49 ldr := &Loader{Stdin: stdin, Logger: logger}
50 // Calling SetupFlags on a throwaway FlagSet has the side
51 // effect of assigning default values to the configurable
53 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
57 // SetupFlags configures a flagset so arguments like -config X can be
58 // used to change the loader's Path fields.
60 // ldr := NewLoader(os.Stdin, logrus.New())
61 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
62 // ldr.SetupFlags(flagset)
63 // // ldr.Path == "/etc/arvados/config.yml"
64 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
65 // // ldr.Path == "/tmp/c.yaml"
66 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
67 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
69 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
70 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
71 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
72 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
73 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
74 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arv-git-httpd configuration `file`")
75 flagset.StringVar(&ldr.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
76 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
80 // MungeLegacyConfigArgs checks args for a -config flag whose argument
81 // is a regular file (or a symlink to one), but doesn't have a
82 // top-level "Clusters" key and therefore isn't a valid cluster
83 // configuration file. If it finds such a flag, it replaces -config
84 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
86 // This is used by programs that still need to accept "-config" as a
87 // way to specify a per-component config file until their config has
90 // If any errors are encountered while reading or parsing a config
91 // file, the given args are not munged. We presume the same errors
92 // will be encountered again and reported later on when trying to load
93 // cluster configuration from the same file, regardless of which
94 // struct we end up using.
95 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
96 munged := append([]string(nil), args...)
97 for i := 0; i < len(args); i++ {
98 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
102 if strings.Contains(args[i], "=") {
103 operand = strings.SplitN(args[i], "=", 2)[1]
104 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
110 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
113 f, err := os.Open(operand)
118 buf, err := ioutil.ReadAll(f)
122 var cfg arvados.Config
123 err = yaml.Unmarshal(buf, &cfg)
127 if len(cfg.Clusters) == 0 {
128 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
129 if operand == args[i] {
130 munged[i-1] = legacyConfigArg
132 munged[i] = legacyConfigArg + "=" + operand
137 // Disable legacy config loading for components other than the
138 // one that was specified
139 if legacyConfigArg != "-legacy-keepstore-config" {
140 ldr.KeepstorePath = ""
142 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
143 ldr.CrunchDispatchSlurmPath = ""
145 if legacyConfigArg != "-legacy-ws-config" {
146 ldr.WebsocketPath = ""
148 if legacyConfigArg != "-legacy-keepweb-config" {
151 if legacyConfigArg != "-legacy-keepproxy-config" {
152 ldr.KeepproxyPath = ""
154 if legacyConfigArg != "-legacy-git-httpd-config" {
155 ldr.GitHttpdPath = ""
157 if legacyConfigArg != "-legacy-keepbalance-config" {
158 ldr.KeepBalancePath = ""
164 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
166 return ioutil.ReadAll(ldr.Stdin)
168 f, err := os.Open(path)
173 return ioutil.ReadAll(f)
176 func (ldr *Loader) Load() (*arvados.Config, error) {
177 if ldr.configdata == nil {
178 buf, err := ldr.loadBytes(ldr.Path)
185 // Load the config into a dummy map to get the cluster ID
186 // keys, discarding the values; then set up defaults for each
187 // cluster ID; then load the real config on top of the
190 Clusters map[string]struct{}
192 err := yaml.Unmarshal(ldr.configdata, &dummy)
196 if len(dummy.Clusters) == 0 {
197 return nil, ErrNoClustersDefined
200 // We can't merge deep structs here; instead, we unmarshal the
201 // default & loaded config files into generic maps, merge
202 // those, and then json-encode+decode the result into the
203 // config struct type.
204 var merged map[string]interface{}
205 for id := range dummy.Clusters {
206 var src map[string]interface{}
207 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
209 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
211 err = mergo.Merge(&merged, src, mergo.WithOverride)
213 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
216 var src map[string]interface{}
217 err = yaml.Unmarshal(ldr.configdata, &src)
219 return nil, fmt.Errorf("loading config data: %s", err)
221 ldr.logExtraKeys(merged, src, "")
222 removeSampleKeys(merged)
223 err = mergo.Merge(&merged, src, mergo.WithOverride)
225 return nil, fmt.Errorf("merging config data: %s", err)
228 // map[string]interface{} => json => arvados.Config
229 var cfg arvados.Config
233 errEnc = json.NewEncoder(pw).Encode(merged)
236 err = json.NewDecoder(pr).Decode(&cfg)
241 return nil, fmt.Errorf("transcoding config data: %s", err)
244 var loadFuncs []func(*arvados.Config) error
245 if !ldr.SkipDeprecated {
246 loadFuncs = append(loadFuncs,
247 ldr.applyDeprecatedConfig,
248 ldr.applyDeprecatedVolumeDriverParameters,
252 // legacy file is required when either:
253 // * a non-default location was specified
254 // * no primary config was loaded, and this is the
255 // legacy config file for the current component
256 loadFuncs = append(loadFuncs,
257 ldr.loadOldEnvironmentVariables,
258 ldr.loadOldKeepstoreConfig,
259 ldr.loadOldKeepWebConfig,
260 ldr.loadOldCrunchDispatchSlurmConfig,
261 ldr.loadOldWebsocketConfig,
262 ldr.loadOldKeepproxyConfig,
263 ldr.loadOldGitHttpdConfig,
264 ldr.loadOldKeepBalanceConfig,
267 for _, f := range loadFuncs {
274 // Check for known mistakes
275 for id, cc := range cfg.Clusters {
276 for remote := range cc.RemoteClusters {
277 if remote == "*" || remote == "SAMPLE" {
280 err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
285 for _, err = range []error{
286 ldr.checkClusterID(fmt.Sprintf("Clusters.%s", id), id, false),
287 ldr.checkClusterID(fmt.Sprintf("Clusters.%s.Login.LoginCluster", id), cc.Login.LoginCluster, true),
288 ldr.checkToken(fmt.Sprintf("Clusters.%s.ManagementToken", id), cc.ManagementToken),
289 ldr.checkToken(fmt.Sprintf("Clusters.%s.SystemRootToken", id), cc.SystemRootToken),
290 ldr.checkToken(fmt.Sprintf("Clusters.%s.Collections.BlobSigningKey", id), cc.Collections.BlobSigningKey),
291 checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
292 ldr.checkEmptyKeepstores(cc),
293 ldr.checkUnlistedKeepstores(cc),
303 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
305 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
306 if emptyStringOk && clusterID == "" {
308 } else if !acceptableClusterIDRe.MatchString(clusterID) {
309 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
314 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
315 var acceptableTokenLength = 32
317 func (ldr *Loader) checkToken(label, token string) error {
319 if ldr.Logger != nil {
320 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
322 } else if !acceptableTokenRe.MatchString(token) {
323 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
324 } else if len(token) < acceptableTokenLength {
325 if ldr.Logger != nil {
326 ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
332 func checkKeyConflict(label string, m map[string]string) error {
333 saw := map[string]bool{}
335 k = strings.ToLower(k)
337 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
344 func removeSampleKeys(m map[string]interface{}) {
346 for _, v := range m {
347 if v, _ := v.(map[string]interface{}); v != nil {
353 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
354 if ldr.Logger == nil {
357 allowed := map[string]interface{}{}
358 for k, v := range expected {
359 allowed[strings.ToLower(k)] = v
361 for k, vsupp := range supplied {
363 // entry will be dropped in removeSampleKeys anyway
366 vexp, ok := allowed[strings.ToLower(k)]
367 if expected["SAMPLE"] != nil {
368 vexp = expected["SAMPLE"]
370 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
373 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
374 // if vsupp is a map but vexp isn't map, this
375 // will be caught elsewhere; see TestBadType.
377 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
378 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
380 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")