github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/provider/gce/config.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package gce 5 6 import ( 7 "github.com/juju/errors" 8 "github.com/juju/schema" 9 "gopkg.in/juju/environschema.v1" 10 11 "github.com/juju/juju/environs/config" 12 ) 13 14 const ( 15 cfgBaseImagePath = "base-image-path" 16 ) 17 18 var configSchema = environschema.Fields{ 19 cfgBaseImagePath: { 20 Description: "Base path to look for machine disk images.", 21 Type: environschema.Tstring, 22 }, 23 } 24 25 // configFields is the spec for each GCE config value's type. 26 var configFields = func() schema.Fields { 27 fs, _, err := configSchema.ValidationSchema() 28 if err != nil { 29 panic(err) 30 } 31 return fs 32 }() 33 34 var configImmutableFields = []string{} 35 36 var configDefaults = schema.Defaults{ 37 cfgBaseImagePath: schema.Omit, 38 } 39 40 type environConfig struct { 41 config *config.Config 42 attrs map[string]interface{} 43 } 44 45 // newConfig builds a new environConfig from the provided Config 46 // filling in default values, if any. It returns an error if the 47 // resulting configuration is not valid. 48 func newConfig(cfg, old *config.Config) (*environConfig, error) { 49 // Ensure that the provided config is valid. 50 if err := config.Validate(cfg, old); err != nil { 51 return nil, errors.Trace(err) 52 } 53 attrs, err := cfg.ValidateUnknownAttrs(configFields, configDefaults) 54 if err != nil { 55 return nil, errors.Trace(err) 56 } 57 58 if old != nil { 59 // There's an old configuration. Validate it so that any 60 // default values are correctly coerced for when we check 61 // the old values later. 62 oldEcfg, err := newConfig(old, nil) 63 if err != nil { 64 return nil, errors.Annotatef(err, "invalid base config") 65 } 66 for _, attr := range configImmutableFields { 67 oldv, newv := oldEcfg.attrs[attr], attrs[attr] 68 if oldv != newv { 69 return nil, errors.Errorf( 70 "%s: cannot change from %v to %v", 71 attr, oldv, newv, 72 ) 73 } 74 } 75 } 76 77 ecfg := &environConfig{ 78 config: cfg, 79 attrs: attrs, 80 } 81 return ecfg, nil 82 } 83 84 func (c *environConfig) baseImagePath() (string, bool) { 85 path, ok := c.attrs[cfgBaseImagePath].(string) 86 return path, ok 87 }