env.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 environmentFromCloudConfig(cfg *config.CloudConfig) map[string]string {
  24. environment := cfg.Rancher.Environment
  25. if cfg.Rancher.Network.HttpProxy != "" {
  26. environment["http_proxy"] = cfg.Rancher.Network.HttpProxy
  27. environment["HTTP_PROXY"] = cfg.Rancher.Network.HttpProxy
  28. }
  29. if cfg.Rancher.Network.HttpsProxy != "" {
  30. environment["https_proxy"] = cfg.Rancher.Network.HttpsProxy
  31. environment["HTTPS_PROXY"] = cfg.Rancher.Network.HttpsProxy
  32. }
  33. if cfg.Rancher.Network.NoProxy != "" {
  34. environment["no_proxy"] = cfg.Rancher.Network.NoProxy
  35. environment["NO_PROXY"] = cfg.Rancher.Network.NoProxy
  36. }
  37. return environment
  38. }
  39. func lookupKeys(cfg *config.CloudConfig, keys ...string) []string {
  40. environment := environmentFromCloudConfig(cfg)
  41. for _, key := range keys {
  42. if strings.HasSuffix(key, "*") {
  43. result := []string{}
  44. for envKey, envValue := range environment {
  45. keyPrefix := key[:len(key)-1]
  46. if strings.HasPrefix(envKey, keyPrefix) {
  47. result = appendEnv(result, envKey, envValue)
  48. }
  49. }
  50. if len(result) > 0 {
  51. return result
  52. }
  53. } else if value, ok := environment[key]; ok {
  54. return appendEnv([]string{}, key, value)
  55. }
  56. }
  57. return []string{}
  58. }
  59. func (c *ConfigEnvironment) SetConfig(cfg *config.CloudConfig) {
  60. c.cfg = cfg
  61. }
  62. func (c *ConfigEnvironment) Lookup(key, serviceName string, serviceConfig *composeConfig.ServiceConfig) []string {
  63. fullKey := fmt.Sprintf("%s/%s", serviceName, key)
  64. return lookupKeys(c.cfg, fullKey, key)
  65. }