cloudinitsave.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright 2015 CoreOS, Inc.
  2. // Copyright 2015-2017 Rancher Labs, Inc.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package cloudinitsave
  16. import (
  17. "bytes"
  18. "errors"
  19. "os"
  20. "path"
  21. "strings"
  22. "sync"
  23. "time"
  24. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  25. "github.com/rancher/os/cmd/control"
  26. "github.com/rancher/os/cmd/network"
  27. rancherConfig "github.com/rancher/os/config"
  28. "github.com/rancher/os/config/cloudinit/config"
  29. "github.com/rancher/os/config/cloudinit/datasource"
  30. "github.com/rancher/os/config/cloudinit/datasource/configdrive"
  31. "github.com/rancher/os/config/cloudinit/datasource/file"
  32. "github.com/rancher/os/config/cloudinit/datasource/metadata/digitalocean"
  33. "github.com/rancher/os/config/cloudinit/datasource/metadata/ec2"
  34. "github.com/rancher/os/config/cloudinit/datasource/metadata/gce"
  35. "github.com/rancher/os/config/cloudinit/datasource/metadata/packet"
  36. "github.com/rancher/os/config/cloudinit/datasource/proccmdline"
  37. "github.com/rancher/os/config/cloudinit/datasource/url"
  38. "github.com/rancher/os/config/cloudinit/datasource/vmware"
  39. "github.com/rancher/os/config/cloudinit/pkg"
  40. "github.com/rancher/os/log"
  41. "github.com/rancher/os/netconf"
  42. "github.com/rancher/os/util"
  43. )
  44. const (
  45. datasourceInterval = 100 * time.Millisecond
  46. datasourceMaxInterval = 30 * time.Second
  47. datasourceTimeout = 5 * time.Minute
  48. )
  49. func Main() {
  50. log.InitLogger()
  51. log.Info("Running cloud-init-save")
  52. if err := control.UdevSettle(); err != nil {
  53. log.Errorf("Failed to run udev settle: %v", err)
  54. }
  55. if err := saveCloudConfig(); err != nil {
  56. log.Errorf("Failed to save cloud-config: %v", err)
  57. }
  58. }
  59. func saveCloudConfig() error {
  60. log.Infof("SaveCloudConfig")
  61. cfg := rancherConfig.LoadConfig()
  62. log.Debugf("init: SaveCloudConfig(pre ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  63. network.ApplyNetworkConfig(cfg)
  64. log.Infof("datasources that will be consided: %#v", cfg.Rancher.CloudInit.Datasources)
  65. dss := getDatasources(cfg.Rancher.CloudInit.Datasources)
  66. if len(dss) == 0 {
  67. log.Errorf("currentDatasource - none found")
  68. return nil
  69. }
  70. foundDs := selectDatasource(dss)
  71. log.Infof("Cloud-init datasource that was used: %s", foundDs)
  72. // Apply any newly detected network config.
  73. cfg = rancherConfig.LoadConfig()
  74. log.Debugf("init: SaveCloudConfig(post ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  75. network.ApplyNetworkConfig(cfg)
  76. return nil
  77. }
  78. func RequiresNetwork(datasource string) bool {
  79. // TODO: move into the datasources (and metadatasources)
  80. // and then we can enable that platforms defaults..
  81. parts := strings.SplitN(datasource, ":", 2)
  82. requiresNetwork, ok := map[string]bool{
  83. "ec2": true,
  84. "file": false,
  85. "url": true,
  86. "cmdline": true,
  87. "configdrive": false,
  88. "digitalocean": true,
  89. "gce": true,
  90. "packet": true,
  91. }[parts[0]]
  92. return ok && requiresNetwork
  93. }
  94. func saveFiles(cloudConfigBytes, scriptBytes []byte, metadata datasource.Metadata) error {
  95. os.MkdirAll(rancherConfig.CloudConfigDir, os.ModeDir|0600)
  96. if len(scriptBytes) > 0 {
  97. log.Infof("Writing to %s", rancherConfig.CloudConfigScriptFile)
  98. if err := util.WriteFileAtomic(rancherConfig.CloudConfigScriptFile, scriptBytes, 500); err != nil {
  99. log.Errorf("Error while writing file %s: %v", rancherConfig.CloudConfigScriptFile, err)
  100. return err
  101. }
  102. }
  103. if len(cloudConfigBytes) > 0 {
  104. if err := util.WriteFileAtomic(rancherConfig.CloudConfigBootFile, cloudConfigBytes, 400); err != nil {
  105. return err
  106. }
  107. log.Infof("Wrote to %s", rancherConfig.CloudConfigBootFile)
  108. }
  109. metaDataBytes, err := yaml.Marshal(metadata)
  110. if err != nil {
  111. return err
  112. }
  113. if err = util.WriteFileAtomic(rancherConfig.MetaDataFile, metaDataBytes, 400); err != nil {
  114. return err
  115. }
  116. log.Infof("Wrote to %s", rancherConfig.MetaDataFile)
  117. // if we write the empty meta yml, the merge fails.
  118. // TODO: the problem is that a partially filled one will still have merge issues, so that needs fixing - presumably by making merge more clever, and making more fields optional
  119. emptyMeta, err := yaml.Marshal(datasource.Metadata{})
  120. if err != nil {
  121. return err
  122. }
  123. if bytes.Compare(metaDataBytes, emptyMeta) == 0 {
  124. log.Infof("not writing %s: its all defaults.", rancherConfig.CloudConfigNetworkFile)
  125. return nil
  126. }
  127. type nonRancherCfg struct {
  128. Network netconf.NetworkConfig `yaml:"network,omitempty"`
  129. }
  130. type nonCfg struct {
  131. Rancher nonRancherCfg `yaml:"rancher,omitempty"`
  132. }
  133. // write the network.yml file from metadata
  134. cc := nonCfg{
  135. Rancher: nonRancherCfg{
  136. Network: metadata.NetworkConfig,
  137. },
  138. }
  139. if err := os.MkdirAll(path.Dir(rancherConfig.CloudConfigNetworkFile), 0700); err != nil {
  140. log.Errorf("Failed to create directory for file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  141. }
  142. if err := rancherConfig.WriteToFile(cc, rancherConfig.CloudConfigNetworkFile); err != nil {
  143. log.Errorf("Failed to save config file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  144. }
  145. log.Infof("Wrote to %s", rancherConfig.CloudConfigNetworkFile)
  146. return nil
  147. }
  148. func fetchAndSave(ds datasource.Datasource) error {
  149. var metadata datasource.Metadata
  150. log.Infof("Fetching user-data from datasource %s", ds)
  151. userDataBytes, err := ds.FetchUserdata()
  152. if err != nil {
  153. log.Errorf("Failed fetching user-data from datasource: %v", err)
  154. return err
  155. }
  156. log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
  157. metadata, err = ds.FetchMetadata()
  158. if err != nil {
  159. log.Errorf("Failed fetching meta-data from datasource: %v", err)
  160. return err
  161. }
  162. userData := string(userDataBytes)
  163. scriptBytes := []byte{}
  164. if config.IsScript(userData) {
  165. scriptBytes = userDataBytes
  166. userDataBytes = []byte{}
  167. } else if isCompose(userData) {
  168. if userDataBytes, err = composeToCloudConfig(userDataBytes); err != nil {
  169. log.Errorf("Failed to convert compose to cloud-config syntax: %v", err)
  170. return err
  171. }
  172. } else if config.IsCloudConfig(userData) {
  173. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  174. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config, not saving.")
  175. userDataBytes = []byte{}
  176. }
  177. } else {
  178. log.Errorf("Unrecognized user-data\n(%s)", userData)
  179. userDataBytes = []byte{}
  180. }
  181. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  182. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config")
  183. return errors.New("Failed to parse cloud-config")
  184. }
  185. return saveFiles(userDataBytes, scriptBytes, metadata)
  186. }
  187. // getDatasources creates a slice of possible Datasources for cloudinit based
  188. // on the different source command-line flags.
  189. func getDatasources(datasources []string) []datasource.Datasource {
  190. dss := make([]datasource.Datasource, 0, 5)
  191. for _, ds := range datasources {
  192. parts := strings.SplitN(ds, ":", 2)
  193. root := ""
  194. if len(parts) > 1 {
  195. root = parts[1]
  196. }
  197. switch parts[0] {
  198. case "*":
  199. dss = append(dss, getDatasources([]string{"configdrive", "vmware", "ec2", "digitalocean", "packet", "gce"})...)
  200. case "ec2":
  201. dss = append(dss, ec2.NewDatasource(root))
  202. case "file":
  203. if root != "" {
  204. dss = append(dss, file.NewDatasource(root))
  205. }
  206. case "url":
  207. if root != "" {
  208. dss = append(dss, url.NewDatasource(root))
  209. }
  210. case "cmdline":
  211. if len(parts) == 1 {
  212. dss = append(dss, proccmdline.NewDatasource())
  213. }
  214. case "configdrive":
  215. if root == "" {
  216. root = "/media/config-2"
  217. }
  218. dss = append(dss, configdrive.NewDatasource(root))
  219. case "digitalocean":
  220. // TODO: should we enableDoLinkLocal() - to avoid the need for the other kernel/oem options?
  221. dss = append(dss, digitalocean.NewDatasource(root))
  222. case "gce":
  223. dss = append(dss, gce.NewDatasource(root))
  224. case "packet":
  225. dss = append(dss, packet.NewDatasource(root))
  226. case "vmware":
  227. // made vmware datasource dependent on detecting vmware independently, as it crashes things otherwise
  228. v := vmware.NewDatasource(root)
  229. if v != nil {
  230. dss = append(dss, v)
  231. }
  232. }
  233. }
  234. return dss
  235. }
  236. func enableDoLinkLocal() {
  237. err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  238. Interfaces: map[string]netconf.InterfaceConfig{
  239. "eth0": {
  240. IPV4LL: true,
  241. },
  242. },
  243. }, false, false)
  244. if err != nil {
  245. log.Errorf("Failed to apply link local on eth0: %v", err)
  246. }
  247. }
  248. // selectDatasource attempts to choose a valid Datasource to use based on its
  249. // current availability. The first Datasource to report to be available is
  250. // returned. Datasources will be retried if possible if they are not
  251. // immediately available. If all Datasources are permanently unavailable or
  252. // datasourceTimeout is reached before one becomes available, nil is returned.
  253. func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
  254. ds := make(chan datasource.Datasource)
  255. stop := make(chan struct{})
  256. var wg sync.WaitGroup
  257. for _, s := range sources {
  258. wg.Add(1)
  259. go func(s datasource.Datasource) {
  260. defer wg.Done()
  261. duration := datasourceInterval
  262. for {
  263. log.Infof("cloud-init: Checking availability of %q", s.Type())
  264. if s.IsAvailable() {
  265. log.Infof("cloud-init: Datasource available: %s", s)
  266. ds <- s
  267. return
  268. }
  269. if !s.AvailabilityChanges() {
  270. log.Infof("cloud-init: Datasource unavailable, skipping: %s", s)
  271. return
  272. }
  273. log.Errorf("cloud-init: Datasource not ready, will retry: %s", s)
  274. select {
  275. case <-stop:
  276. return
  277. case <-time.After(duration):
  278. duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
  279. }
  280. }
  281. }(s)
  282. }
  283. done := make(chan struct{})
  284. go func() {
  285. wg.Wait()
  286. close(done)
  287. }()
  288. var s datasource.Datasource
  289. select {
  290. case s = <-ds:
  291. err := fetchAndSave(s)
  292. if err != nil {
  293. log.Errorf("Error fetching cloud-init datasource(%s): %s", s, err)
  294. }
  295. case <-done:
  296. case <-time.After(datasourceTimeout):
  297. }
  298. close(stop)
  299. return s
  300. }
  301. func isCompose(content string) bool {
  302. return strings.HasPrefix(content, "#compose\n")
  303. }
  304. func composeToCloudConfig(bytes []byte) ([]byte, error) {
  305. compose := make(map[interface{}]interface{})
  306. err := yaml.Unmarshal(bytes, &compose)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return yaml.Marshal(map[interface{}]interface{}{
  311. "rancher": map[interface{}]interface{}{
  312. "services": compose,
  313. },
  314. })
  315. }