disk.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package config
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "reflect"
  8. "sort"
  9. "strings"
  10. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  11. "github.com/docker/engine-api/types"
  12. composeConfig "github.com/docker/libcompose/config"
  13. "github.com/rancher/os/config/cloudinit/datasource"
  14. "github.com/rancher/os/config/cloudinit/initialize"
  15. "github.com/rancher/os/log"
  16. "github.com/rancher/os/util"
  17. )
  18. func ReadConfig(bytes []byte, substituteMetadataVars bool, files ...string) (*CloudConfig, error) {
  19. data, err := readConfigs(bytes, substituteMetadataVars, true, files...)
  20. if err != nil {
  21. return nil, err
  22. }
  23. c := &CloudConfig{}
  24. if err := util.Convert(data, c); err != nil {
  25. return nil, err
  26. }
  27. c = amendNils(c)
  28. c = amendContainerNames(c)
  29. return c, nil
  30. }
  31. func loadRawDiskConfig(dirPrefix string, full bool) map[interface{}]interface{} {
  32. var rawCfg map[interface{}]interface{}
  33. if full {
  34. rawCfg, _ = readConfigs(nil, true, false, OsConfigFile, OemConfigFile)
  35. }
  36. files := CloudConfigDirFiles(dirPrefix)
  37. files = append(files, path.Join(dirPrefix, CloudConfigFile))
  38. additionalCfgs, _ := readConfigs(nil, true, false, files...)
  39. return util.Merge(rawCfg, additionalCfgs)
  40. }
  41. func loadRawConfig(dirPrefix string, full bool) map[interface{}]interface{} {
  42. rawCfg := loadRawDiskConfig(dirPrefix, full)
  43. rawCfg = util.Merge(rawCfg, readCmdline())
  44. rawCfg = util.Merge(rawCfg, readElidedCmdline(rawCfg))
  45. rawCfg = applyDebugFlags(rawCfg)
  46. return mergeMetadata(rawCfg, readMetadata())
  47. }
  48. func LoadConfig() *CloudConfig {
  49. return LoadConfigWithPrefix("")
  50. }
  51. func LoadConfigWithPrefix(dirPrefix string) *CloudConfig {
  52. rawCfg := loadRawConfig(dirPrefix, true)
  53. cfg := &CloudConfig{}
  54. if err := util.Convert(rawCfg, cfg); err != nil {
  55. log.Errorf("Failed to parse configuration: %s", err)
  56. return &CloudConfig{}
  57. }
  58. cfg = amendNils(cfg)
  59. cfg = amendContainerNames(cfg)
  60. return cfg
  61. }
  62. func Insert(m interface{}, args ...interface{}) interface{} {
  63. // TODO: move to util.go
  64. if len(args)%2 != 0 {
  65. panic("must have pairs of keys and values")
  66. }
  67. mv := reflect.ValueOf(m)
  68. if mv.IsNil() {
  69. mv = reflect.MakeMap(mv.Type())
  70. }
  71. for i := 0; i < len(args); i += 2 {
  72. mv.SetMapIndex(reflect.ValueOf(args[i]), reflect.ValueOf(args[i+1]))
  73. }
  74. return mv.Interface()
  75. }
  76. func SaveInitCmdline(cmdLineArgs string) {
  77. elidedCfg := parseCmdline(cmdLineArgs)
  78. env := Insert(make(map[interface{}]interface{}), interface{}("EXTRA_CMDLINE"), interface{}(cmdLineArgs))
  79. rancher := Insert(make(map[interface{}]interface{}), interface{}("environment"), env)
  80. newCfg := Insert(elidedCfg, interface{}("rancher"), rancher)
  81. // make it easy for readElidedCmdline(rawCfg)
  82. newCfg = Insert(newCfg, interface{}("EXTRA_CMDLINE"), interface{}(cmdLineArgs))
  83. if err := WriteToFile(newCfg, CloudConfigInitFile); err != nil {
  84. log.Errorf("Failed to write init-cmdline config: %s", err)
  85. }
  86. }
  87. func CloudConfigDirFiles(dirPrefix string) []string {
  88. cloudConfigDir := path.Join(dirPrefix, CloudConfigDir)
  89. files, err := ioutil.ReadDir(cloudConfigDir)
  90. if err != nil {
  91. if os.IsNotExist(err) {
  92. // do nothing
  93. log.Debugf("%s does not exist", CloudConfigDir)
  94. } else {
  95. log.Errorf("Failed to read %s: %v", CloudConfigDir, err)
  96. }
  97. return []string{}
  98. }
  99. var finalFiles []string
  100. for _, file := range files {
  101. if !file.IsDir() && !strings.HasPrefix(file.Name(), ".") {
  102. finalFiles = append(finalFiles, path.Join(cloudConfigDir, file.Name()))
  103. }
  104. }
  105. return finalFiles
  106. }
  107. func applyDebugFlags(rawCfg map[interface{}]interface{}) map[interface{}]interface{} {
  108. cfg := &CloudConfig{}
  109. if err := util.Convert(rawCfg, cfg); err != nil {
  110. return rawCfg
  111. }
  112. if !cfg.Rancher.Debug {
  113. return rawCfg
  114. }
  115. log.SetLevel(log.DebugLevel)
  116. _, rawCfg = getOrSetVal("rancher.docker.debug", rawCfg, true)
  117. _, rawCfg = getOrSetVal("rancher.system_docker.debug", rawCfg, true)
  118. _, rawCfg = getOrSetVal("rancher.bootstrap_docker.debug", rawCfg, true)
  119. _, rawCfg = getOrSetVal("rancher.log", rawCfg, true)
  120. return rawCfg
  121. }
  122. // mergeMetadata merges certain options from md (meta-data from the datasource)
  123. // onto cc (a CloudConfig derived from user-data), if they are not already set
  124. // on cc (i.e. user-data always takes precedence)
  125. func mergeMetadata(rawCfg map[interface{}]interface{}, md datasource.Metadata) map[interface{}]interface{} {
  126. if rawCfg == nil {
  127. return nil
  128. }
  129. out := util.MapCopy(rawCfg)
  130. outHostname, ok := out["hostname"]
  131. if !ok {
  132. outHostname = ""
  133. }
  134. if md.Hostname != "" {
  135. if outHostname != "" {
  136. log.Debugf("Warning: user-data hostname (%s) overrides metadata hostname (%s)\n", outHostname, md.Hostname)
  137. } else {
  138. out["hostname"] = md.Hostname
  139. }
  140. }
  141. // Sort SSH keys by key name
  142. keys := []string{}
  143. for k := range md.SSHPublicKeys {
  144. keys = append(keys, k)
  145. }
  146. sort.Sort(sort.StringSlice(keys))
  147. finalKeys, _ := out["ssh_authorized_keys"].([]interface{})
  148. for _, k := range keys {
  149. finalKeys = append(finalKeys, md.SSHPublicKeys[k])
  150. }
  151. out["ssh_authorized_keys"] = finalKeys
  152. return out
  153. }
  154. func readMetadata() datasource.Metadata {
  155. metadata := datasource.Metadata{}
  156. if metaDataBytes, err := ioutil.ReadFile(MetaDataFile); err == nil {
  157. yaml.Unmarshal(metaDataBytes, &metadata)
  158. }
  159. return metadata
  160. }
  161. func readElidedCmdline(rawCfg map[interface{}]interface{}) map[interface{}]interface{} {
  162. for k, v := range rawCfg {
  163. if key, _ := k.(string); key == "EXTRA_CMDLINE" {
  164. if val, ok := v.(string); ok {
  165. cmdLineObj := parseCmdline(strings.TrimSpace(util.UnescapeKernelParams(string(val))))
  166. return cmdLineObj
  167. }
  168. }
  169. }
  170. return nil
  171. }
  172. func readCmdline() map[interface{}]interface{} {
  173. cmdLine, err := ioutil.ReadFile("/proc/cmdline")
  174. if err != nil {
  175. log.WithFields(log.Fields{"err": err}).Error("Failed to read kernel params")
  176. return nil
  177. }
  178. if len(cmdLine) == 0 {
  179. return nil
  180. }
  181. cmdLineObj := parseCmdline(strings.TrimSpace(util.UnescapeKernelParams(string(cmdLine))))
  182. return cmdLineObj
  183. }
  184. func amendNils(c *CloudConfig) *CloudConfig {
  185. t := *c
  186. if t.Rancher.Environment == nil {
  187. t.Rancher.Environment = map[string]string{}
  188. }
  189. if t.Rancher.BootstrapContainers == nil {
  190. t.Rancher.BootstrapContainers = map[string]*composeConfig.ServiceConfigV1{}
  191. }
  192. if t.Rancher.Services == nil {
  193. t.Rancher.Services = map[string]*composeConfig.ServiceConfigV1{}
  194. }
  195. if t.Rancher.ServicesInclude == nil {
  196. t.Rancher.ServicesInclude = map[string]bool{}
  197. }
  198. if t.Rancher.RegistryAuths == nil {
  199. t.Rancher.RegistryAuths = map[string]types.AuthConfig{}
  200. }
  201. if t.Rancher.Sysctl == nil {
  202. t.Rancher.Sysctl = map[string]string{}
  203. }
  204. return &t
  205. }
  206. func amendContainerNames(c *CloudConfig) *CloudConfig {
  207. for _, scm := range []map[string]*composeConfig.ServiceConfigV1{
  208. c.Rancher.BootstrapContainers,
  209. c.Rancher.Services,
  210. } {
  211. for k, v := range scm {
  212. v.ContainerName = k
  213. }
  214. }
  215. return c
  216. }
  217. func WriteToFile(data interface{}, filename string) error {
  218. content, err := yaml.Marshal(data)
  219. if err != nil {
  220. return err
  221. }
  222. if err := os.MkdirAll(filepath.Dir(filename), os.ModeDir|0700); err != nil {
  223. return err
  224. }
  225. return util.WriteFileAtomic(filename, content, 400)
  226. }
  227. func readConfigs(bytes []byte, substituteMetadataVars, returnErr bool, files ...string) (map[interface{}]interface{}, error) {
  228. // You can't just overlay yaml bytes on to maps, it won't merge, but instead
  229. // just override the keys and not merge the map values.
  230. left := make(map[interface{}]interface{})
  231. metadata := readMetadata()
  232. for _, file := range files {
  233. //os.Stderr.WriteString(fmt.Sprintf("READCONFIGS(%s)", file))
  234. content, err := readConfigFile(file)
  235. if err != nil {
  236. if returnErr {
  237. return nil, err
  238. }
  239. log.Errorf("Failed to read config file %s: %s", file, err)
  240. continue
  241. }
  242. if len(content) == 0 {
  243. continue
  244. }
  245. if substituteMetadataVars {
  246. content = substituteVars(content, metadata)
  247. }
  248. right := make(map[interface{}]interface{})
  249. err = yaml.Unmarshal(content, &right)
  250. if err != nil {
  251. if returnErr {
  252. return nil, err
  253. }
  254. log.Errorf("Failed to parse config file %s: %s", file, err)
  255. continue
  256. }
  257. // Verify there are no issues converting to CloudConfig
  258. c := &CloudConfig{}
  259. if err := util.Convert(right, c); err != nil {
  260. if returnErr {
  261. return nil, err
  262. }
  263. log.Errorf("Failed to parse config file %s: %s", file, err)
  264. continue
  265. }
  266. left = util.Merge(left, right)
  267. }
  268. if bytes == nil || len(bytes) == 0 {
  269. return left, nil
  270. }
  271. right := make(map[interface{}]interface{})
  272. if substituteMetadataVars {
  273. bytes = substituteVars(bytes, metadata)
  274. }
  275. if err := yaml.Unmarshal(bytes, &right); err != nil {
  276. if returnErr {
  277. return nil, err
  278. }
  279. log.Errorf("Failed to parse bytes: %s", err)
  280. return left, nil
  281. }
  282. c := &CloudConfig{}
  283. if err := util.Convert(right, c); err != nil {
  284. if returnErr {
  285. return nil, err
  286. }
  287. log.Errorf("Failed to parse bytes: %s", err)
  288. return left, nil
  289. }
  290. left = util.Merge(left, right)
  291. return left, nil
  292. }
  293. func readConfigFile(file string) ([]byte, error) {
  294. content, err := ioutil.ReadFile(file)
  295. if err != nil {
  296. if os.IsNotExist(err) {
  297. err = nil
  298. content = []byte{}
  299. } else {
  300. return nil, err
  301. }
  302. }
  303. return content, err
  304. }
  305. func substituteVars(userDataBytes []byte, metadata datasource.Metadata) []byte {
  306. // TODO: I think this currently does nothing - its hardcoded for COREOS env..
  307. env := initialize.NewEnvironment("", "", "", "", metadata)
  308. userData := env.Apply(string(userDataBytes))
  309. return []byte(userData)
  310. }