env.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package docker
  2. import (
  3. "fmt"
  4. "strings"
  5. composeConfig "github.com/docker/libcompose/config"
  6. "github.com/rancher/os/config"
  7. "github.com/rancher/os/log"
  8. )
  9. type ConfigEnvironment struct {
  10. cfg *config.CloudConfig
  11. }
  12. func NewConfigEnvironment(cfg *config.CloudConfig) *ConfigEnvironment {
  13. return &ConfigEnvironment{
  14. cfg: cfg,
  15. }
  16. }
  17. func appendEnv(array []string, key, value string) []string {
  18. parts := strings.SplitN(key, "/", 2)
  19. if len(parts) == 2 {
  20. key = parts[1]
  21. }
  22. return append(array, fmt.Sprintf("%s=%s", key, value))
  23. }
  24. func environmentFromCloudConfig(cfg *config.CloudConfig) map[string]string {
  25. environment := cfg.Rancher.Environment
  26. if cfg.Rancher.Network.HTTPProxy != "" {
  27. environment["http_proxy"] = cfg.Rancher.Network.HTTPProxy
  28. environment["HTTP_PROXY"] = cfg.Rancher.Network.HTTPProxy
  29. }
  30. if cfg.Rancher.Network.HTTPSProxy != "" {
  31. environment["https_proxy"] = cfg.Rancher.Network.HTTPSProxy
  32. environment["HTTPS_PROXY"] = cfg.Rancher.Network.HTTPSProxy
  33. }
  34. if cfg.Rancher.Network.NoProxy != "" {
  35. environment["no_proxy"] = cfg.Rancher.Network.NoProxy
  36. environment["NO_PROXY"] = cfg.Rancher.Network.NoProxy
  37. }
  38. if v := config.GetKernelVersion(); v != "" {
  39. environment["KERNEL_VERSION"] = v
  40. log.Debugf("Using /proc/version to set rancher.environment.KERNEL_VERSION = %s", v)
  41. }
  42. return environment
  43. }
  44. func lookupKeys(cfg *config.CloudConfig, keys ...string) []string {
  45. environment := environmentFromCloudConfig(cfg)
  46. for _, key := range keys {
  47. if strings.HasSuffix(key, "*") {
  48. result := []string{}
  49. for envKey, envValue := range environment {
  50. keyPrefix := key[:len(key)-1]
  51. if strings.HasPrefix(envKey, keyPrefix) {
  52. result = appendEnv(result, envKey, envValue)
  53. }
  54. }
  55. if len(result) > 0 {
  56. return result
  57. }
  58. } else if value, ok := environment[key]; ok {
  59. return appendEnv([]string{}, key, value)
  60. }
  61. }
  62. return []string{}
  63. }
  64. func (c *ConfigEnvironment) SetConfig(cfg *config.CloudConfig) {
  65. c.cfg = cfg
  66. }
  67. func (c *ConfigEnvironment) Lookup(key, serviceName string, serviceConfig *composeConfig.ServiceConfig) []string {
  68. fullKey := fmt.Sprintf("%s/%s", serviceName, key)
  69. return lookupKeys(c.cfg, fullKey, key)
  70. }