env.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package docker
  2. import (
  3. "fmt"
  4. "strings"
  5. composeConfig "github.com/docker/libcompose/config"
  6. "github.com/rancher/os/config"
  7. )
  8. type ConfigEnvironment struct {
  9. cfg *config.CloudConfig
  10. }
  11. func NewConfigEnvironment(cfg *config.CloudConfig) *ConfigEnvironment {
  12. return &ConfigEnvironment{
  13. cfg: cfg,
  14. }
  15. }
  16. func appendEnv(array []string, key, value string) []string {
  17. parts := strings.SplitN(key, "/", 2)
  18. if len(parts) == 2 {
  19. key = parts[1]
  20. }
  21. return append(array, fmt.Sprintf("%s=%s", key, value))
  22. }
  23. func lookupKeys(cfg *config.CloudConfig, keys ...string) []string {
  24. for _, key := range keys {
  25. if strings.HasSuffix(key, "*") {
  26. result := []string{}
  27. for envKey, envValue := range cfg.Rancher.Environment {
  28. keyPrefix := key[:len(key)-1]
  29. if strings.HasPrefix(envKey, keyPrefix) {
  30. result = appendEnv(result, envKey, envValue)
  31. }
  32. }
  33. if len(result) > 0 {
  34. return result
  35. }
  36. } else if value, ok := cfg.Rancher.Environment[key]; ok {
  37. return appendEnv([]string{}, key, value)
  38. }
  39. }
  40. return []string{}
  41. }
  42. func (c *ConfigEnvironment) SetConfig(cfg *config.CloudConfig) {
  43. c.cfg = cfg
  44. }
  45. func (c *ConfigEnvironment) Lookup(key, serviceName string, serviceConfig *composeConfig.ServiceConfig) []string {
  46. fullKey := fmt.Sprintf("%s/%s", serviceName, key)
  47. return lookupKeys(c.cfg, fullKey, key)
  48. }