env.go 2.2 KB

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