| 1 |
package config |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"os" |
| 7 |
"strconv" |
| 8 |
"time" |
| 9 |
|
| 10 |
mesostime "github.com/mesos/mesos-go/api/v1/lib/time" |
| 11 |
) |
| 12 |
|
| 13 |
type Config struct { |
| 14 |
|
| 15 |
FrameworkID string |
| 16 |
|
| 17 |
ExecutorID string |
| 18 |
|
| 19 |
Directory string |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
Sandbox string |
| 25 |
|
| 26 |
|
| 27 |
AgentEndpoint string |
| 28 |
|
| 29 |
|
| 30 |
ExecutorShutdownGracePeriod time.Duration |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
Checkpoint bool |
| 35 |
|
| 36 |
|
| 37 |
RecoveryTimeout time.Duration |
| 38 |
|
| 39 |
|
| 40 |
SubscriptionBackoffMax time.Duration |
| 41 |
} |
| 42 |
|
| 43 |
type EnvError struct { |
| 44 |
Reasons []error |
| 45 |
Message string |
| 46 |
} |
| 47 |
|
| 48 |
func (ee *EnvError) Error() string { return fmt.Sprintf("%s: %v", ee.Message, ee.Reasons) } |
| 49 |
|
| 50 |
|
| 51 |
func FromEnv() (Config, error) { return fromEnv(os.Getenv) } |
| 52 |
|
| 53 |
func fromEnv(getter func(string) string) (Config, error) { |
| 54 |
ee := EnvError{Message: "illegal configuration in process environment"} |
| 55 |
required := func(name string) string { |
| 56 |
value := getter(name) |
| 57 |
if value == "" { |
| 58 |
ee.Reasons = append(ee.Reasons, errors.New("missing environment variable: "+name)) |
| 59 |
} |
| 60 |
return value |
| 61 |
} |
| 62 |
requiredDuration := func(name string) time.Duration { |
| 63 |
stringValue := required(name) |
| 64 |
if stringValue != "" { |
| 65 |
d, err := mesostime.ParseDuration(stringValue) |
| 66 |
if err != nil { |
| 67 |
ee.Reasons = append(ee.Reasons, err) |
| 68 |
} else { |
| 69 |
return d |
| 70 |
} |
| 71 |
} |
| 72 |
return 0 |
| 73 |
} |
| 74 |
c := Config{ |
| 75 |
FrameworkID: required("MESOS_FRAMEWORK_ID"), |
| 76 |
ExecutorID: required("MESOS_EXECUTOR_ID"), |
| 77 |
Directory: required("MESOS_DIRECTORY"), |
| 78 |
Sandbox: required("MESOS_SANDBOX"), |
| 79 |
AgentEndpoint: required("MESOS_AGENT_ENDPOINT"), |
| 80 |
ExecutorShutdownGracePeriod: requiredDuration("MESOS_EXECUTOR_SHUTDOWN_GRACE_PERIOD"), |
| 81 |
} |
| 82 |
checkpoint, err := envBool("MESOS_CHECKPOINT", getter) |
| 83 |
if err != nil { |
| 84 |
ee.Reasons = append(ee.Reasons, err) |
| 85 |
} |
| 86 |
if checkpoint { |
| 87 |
c.Checkpoint = true |
| 88 |
c.RecoveryTimeout = requiredDuration("MESOS_RECOVERY_TIMEOUT") |
| 89 |
c.SubscriptionBackoffMax = requiredDuration("MESOS_SUBSCRIPTION_BACKOFF_MAX") |
| 90 |
} |
| 91 |
if len(ee.Reasons) == 0 { |
| 92 |
return c, nil |
| 93 |
} |
| 94 |
return Config{}, &ee |
| 95 |
} |
| 96 |
|
| 97 |
func envBool(name string, getter func(string) string) (b bool, err error) { |
| 98 |
value := getter(name) |
| 99 |
if value != "" { |
| 100 |
b, err = strconv.ParseBool(value) |
| 101 |
} |
| 102 |
return |
| 103 |
} |