package balanced import ( "encoding/json" "errors" "github.com/ipfs-cluster/ipfs-cluster/config" "github.com/kelseyhightower/envconfig" ) const configKey = "balanced" const envConfigKey = "cluster_balanced" // These are the default values for a Config. var ( DefaultAllocateBy = []string{"tag:group", "freespace"} ) // Config allows to initialize the Allocator. type Config struct { config.Saver AllocateBy []string } type jsonConfig struct { AllocateBy []string `json:"allocate_by"` } // ConfigKey returns a human-friendly identifier for this // Config's type. func (cfg *Config) ConfigKey() string { return configKey } // Default initializes this Config with sensible values. func (cfg *Config) Default() error { cfg.AllocateBy = DefaultAllocateBy return nil } // ApplyEnvVars fills in any Config fields found // as environment variables. func (cfg *Config) ApplyEnvVars() error { jcfg := cfg.toJSONConfig() err := envconfig.Process(envConfigKey, jcfg) if err != nil { return err } return cfg.applyJSONConfig(jcfg) } // Validate checks that the fields of this configuration have // sensible values. func (cfg *Config) Validate() error { if len(cfg.AllocateBy) <= 0 { return errors.New("metricalloc.allocate_by is invalid") } return nil } // LoadJSON parses a raw JSON byte-slice as generated by ToJSON(). func (cfg *Config) LoadJSON(raw []byte) error { jcfg := &jsonConfig{} err := json.Unmarshal(raw, jcfg) if err != nil { return err } cfg.Default() return cfg.applyJSONConfig(jcfg) } func (cfg *Config) applyJSONConfig(jcfg *jsonConfig) error { // When unset, leave default if len(jcfg.AllocateBy) > 0 { cfg.AllocateBy = jcfg.AllocateBy } return cfg.Validate() } // ToJSON generates a human-friendly JSON representation of this Config. func (cfg *Config) ToJSON() ([]byte, error) { jcfg := cfg.toJSONConfig() return config.DefaultJSONMarshal(jcfg) } func (cfg *Config) toJSONConfig() *jsonConfig { return &jsonConfig{ AllocateBy: cfg.AllocateBy, } } // ToDisplayJSON returns JSON config as a string. func (cfg *Config) ToDisplayJSON() ([]byte, error) { return config.DisplayJSON(cfg.toJSONConfig()) }