cloudinitsave.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. "github.com/rancher/os/cmd/control"
  25. "github.com/rancher/os/cmd/network"
  26. rancherConfig "github.com/rancher/os/config"
  27. "github.com/rancher/os/config/cloudinit/config"
  28. "github.com/rancher/os/config/cloudinit/datasource"
  29. "github.com/rancher/os/config/cloudinit/datasource/configdrive"
  30. "github.com/rancher/os/config/cloudinit/datasource/file"
  31. "github.com/rancher/os/config/cloudinit/datasource/metadata/aliyun"
  32. "github.com/rancher/os/config/cloudinit/datasource/metadata/cloudstack"
  33. "github.com/rancher/os/config/cloudinit/datasource/metadata/digitalocean"
  34. "github.com/rancher/os/config/cloudinit/datasource/metadata/ec2"
  35. "github.com/rancher/os/config/cloudinit/datasource/metadata/gce"
  36. "github.com/rancher/os/config/cloudinit/datasource/metadata/packet"
  37. "github.com/rancher/os/config/cloudinit/datasource/proccmdline"
  38. "github.com/rancher/os/config/cloudinit/datasource/tftp"
  39. "github.com/rancher/os/config/cloudinit/datasource/url"
  40. "github.com/rancher/os/config/cloudinit/datasource/vmware"
  41. "github.com/rancher/os/config/cloudinit/pkg"
  42. "github.com/rancher/os/pkg/log"
  43. "github.com/rancher/os/pkg/netconf"
  44. "github.com/rancher/os/pkg/util"
  45. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  46. )
  47. const (
  48. datasourceInterval = 100 * time.Millisecond
  49. datasourceMaxInterval = 30 * time.Second
  50. datasourceTimeout = 5 * time.Minute
  51. )
  52. func Main() {
  53. log.InitLogger()
  54. log.Info("Running cloud-init-save")
  55. if err := control.UdevSettle(); err != nil {
  56. log.Errorf("Failed to run udev settle: %v", err)
  57. }
  58. if err := saveCloudConfig(); err != nil {
  59. log.Errorf("Failed to save cloud-config: %v", err)
  60. }
  61. // exit wpa_supplicant
  62. netconf.StopWpaSupplicant()
  63. // exit dhcpcd
  64. netconf.StopDhcpcd()
  65. }
  66. func saveCloudConfig() error {
  67. log.Infof("SaveCloudConfig")
  68. cfg := rancherConfig.LoadConfig()
  69. log.Debugf("init: SaveCloudConfig(pre ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  70. network.ApplyNetworkConfig(cfg)
  71. log.Infof("datasources that will be considered: %#v", cfg.Rancher.CloudInit.Datasources)
  72. dss := getDatasources(cfg.Rancher.CloudInit.Datasources)
  73. if len(dss) == 0 {
  74. log.Errorf("currentDatasource - none found")
  75. return nil
  76. }
  77. foundDs := selectDatasource(dss)
  78. log.Infof("Cloud-init datasource that was used: %s", foundDs)
  79. // Apply any newly detected network config.
  80. cfg = rancherConfig.LoadConfig()
  81. log.Debugf("init: SaveCloudConfig(post ApplyNetworkConfig): %#v", cfg.Rancher.Network)
  82. network.ApplyNetworkConfig(cfg)
  83. return nil
  84. }
  85. func saveFiles(cloudConfigBytes, scriptBytes []byte, metadata datasource.Metadata) error {
  86. os.MkdirAll(rancherConfig.CloudConfigDir, os.ModeDir|0600)
  87. if len(scriptBytes) > 0 {
  88. log.Infof("Writing to %s", rancherConfig.CloudConfigScriptFile)
  89. if err := util.WriteFileAtomic(rancherConfig.CloudConfigScriptFile, scriptBytes, 500); err != nil {
  90. log.Errorf("Error while writing file %s: %v", rancherConfig.CloudConfigScriptFile, err)
  91. return err
  92. }
  93. }
  94. if len(cloudConfigBytes) > 0 {
  95. if err := util.WriteFileAtomic(rancherConfig.CloudConfigBootFile, cloudConfigBytes, 400); err != nil {
  96. return err
  97. }
  98. log.Infof("Wrote to %s", rancherConfig.CloudConfigBootFile)
  99. }
  100. metaDataBytes, err := yaml.Marshal(metadata)
  101. if err != nil {
  102. return err
  103. }
  104. if err = util.WriteFileAtomic(rancherConfig.MetaDataFile, metaDataBytes, 400); err != nil {
  105. return err
  106. }
  107. log.Infof("Wrote to %s", rancherConfig.MetaDataFile)
  108. // if we write the empty meta yml, the merge fails.
  109. // 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
  110. emptyMeta, err := yaml.Marshal(datasource.Metadata{})
  111. if err != nil {
  112. return err
  113. }
  114. if bytes.Compare(metaDataBytes, emptyMeta) == 0 {
  115. log.Infof("not writing %s: its all defaults.", rancherConfig.CloudConfigNetworkFile)
  116. return nil
  117. }
  118. type nonRancherCfg struct {
  119. Network netconf.NetworkConfig `yaml:"network,omitempty"`
  120. }
  121. type nonCfg struct {
  122. Rancher nonRancherCfg `yaml:"rancher,omitempty"`
  123. }
  124. // write the network.yml file from metadata
  125. cc := nonCfg{
  126. Rancher: nonRancherCfg{
  127. Network: metadata.NetworkConfig,
  128. },
  129. }
  130. if err := os.MkdirAll(path.Dir(rancherConfig.CloudConfigNetworkFile), 0700); err != nil {
  131. log.Errorf("Failed to create directory for file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  132. }
  133. if err := rancherConfig.WriteToFile(cc, rancherConfig.CloudConfigNetworkFile); err != nil {
  134. log.Errorf("Failed to save config file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  135. }
  136. log.Infof("Wrote to %s", rancherConfig.CloudConfigNetworkFile)
  137. return nil
  138. }
  139. func fetchAndSave(ds datasource.Datasource) error {
  140. var metadata datasource.Metadata
  141. log.Infof("Fetching user-data from datasource %s", ds)
  142. userDataBytes, err := ds.FetchUserdata()
  143. if err != nil {
  144. log.Errorf("Failed fetching user-data from datasource: %v", err)
  145. return err
  146. }
  147. userDataBytes, err = decompressIfGzip(userDataBytes)
  148. if err != nil {
  149. log.Errorf("Failed decompressing user-data from datasource: %v", err)
  150. return err
  151. }
  152. log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
  153. metadata, err = ds.FetchMetadata()
  154. if err != nil {
  155. log.Errorf("Failed fetching meta-data from datasource: %v", err)
  156. return err
  157. }
  158. userData := string(userDataBytes)
  159. scriptBytes := []byte{}
  160. if config.IsScript(userData) {
  161. scriptBytes = userDataBytes
  162. userDataBytes = []byte{}
  163. } else if isCompose(userData) {
  164. if userDataBytes, err = composeToCloudConfig(userDataBytes); err != nil {
  165. log.Errorf("Failed to convert compose to cloud-config syntax: %v", err)
  166. return err
  167. }
  168. } else if config.IsCloudConfig(userData) {
  169. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  170. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config, not saving.")
  171. userDataBytes = []byte{}
  172. }
  173. } else {
  174. log.Errorf("Unrecognized user-data\n(%s)", userData)
  175. userDataBytes = []byte{}
  176. }
  177. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  178. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config")
  179. return errors.New("Failed to parse cloud-config")
  180. }
  181. return saveFiles(userDataBytes, scriptBytes, metadata)
  182. }
  183. // getDatasources creates a slice of possible Datasources for cloudinit based
  184. // on the different source command-line flags.
  185. func getDatasources(datasources []string) []datasource.Datasource {
  186. dss := make([]datasource.Datasource, 0, 5)
  187. for _, ds := range datasources {
  188. parts := strings.SplitN(ds, ":", 2)
  189. root := ""
  190. if len(parts) > 1 {
  191. root = parts[1]
  192. }
  193. switch parts[0] {
  194. case "*":
  195. dss = append(dss, getDatasources([]string{"configdrive", "vmware", "ec2", "digitalocean", "packet", "gce", "cloudstack"})...)
  196. case "cloudstack":
  197. for _, source := range cloudstack.NewDatasource(root) {
  198. dss = append(dss, source)
  199. }
  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 "tftp":
  207. dss = append(dss, tftp.NewDatasource(root))
  208. case "url":
  209. if root != "" {
  210. dss = append(dss, url.NewDatasource(root))
  211. }
  212. case "cmdline":
  213. if len(parts) == 1 {
  214. dss = append(dss, proccmdline.NewDatasource())
  215. }
  216. case "configdrive":
  217. if root == "" {
  218. root = "/media/config-2"
  219. }
  220. dss = append(dss, configdrive.NewDatasource(root))
  221. case "digitalocean":
  222. // TODO: should we enableDoLinkLocal() - to avoid the need for the other kernel/oem options?
  223. dss = append(dss, digitalocean.NewDatasource(root))
  224. case "gce":
  225. dss = append(dss, gce.NewDatasource(root))
  226. case "packet":
  227. dss = append(dss, packet.NewDatasource(root))
  228. case "vmware":
  229. // made vmware datasource dependent on detecting vmware independently, as it crashes things otherwise
  230. v := vmware.NewDatasource(root)
  231. if v != nil {
  232. dss = append(dss, v)
  233. }
  234. case "aliyun":
  235. dss = append(dss, aliyun.NewDatasource(root))
  236. }
  237. }
  238. return dss
  239. }
  240. func enableDoLinkLocal() {
  241. cfg := rancherConfig.LoadConfig()
  242. dhcpTimeout := cfg.Rancher.Defaults.Network.DHCPTimeout
  243. if cfg.Rancher.Network.DHCPTimeout > 0 {
  244. dhcpTimeout = cfg.Rancher.Network.DHCPTimeout
  245. }
  246. _, err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  247. Interfaces: map[string]netconf.InterfaceConfig{
  248. "eth0": {
  249. IPV4LL: true,
  250. },
  251. },
  252. DHCPTimeout: dhcpTimeout,
  253. }, false, false)
  254. if err != nil {
  255. log.Errorf("Failed to apply link local on eth0: %v", err)
  256. }
  257. }
  258. // selectDatasource attempts to choose a valid Datasource to use based on its
  259. // current availability. The first Datasource to report to be available is
  260. // returned. Datasources will be retried if possible if they are not
  261. // immediately available. If all Datasources are permanently unavailable or
  262. // datasourceTimeout is reached before one becomes available, nil is returned.
  263. func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
  264. ds := make(chan datasource.Datasource)
  265. stop := make(chan struct{})
  266. var wg sync.WaitGroup
  267. for _, s := range sources {
  268. wg.Add(1)
  269. go func(s datasource.Datasource) {
  270. defer wg.Done()
  271. duration := datasourceInterval
  272. for {
  273. log.Infof("cloud-init: Checking availability of %q", s.Type())
  274. if s.IsAvailable() {
  275. log.Infof("cloud-init: Datasource available: %s", s)
  276. ds <- s
  277. return
  278. }
  279. if !s.AvailabilityChanges() {
  280. log.Infof("cloud-init: Datasource unavailable, skipping: %s", s)
  281. return
  282. }
  283. log.Errorf("cloud-init: Datasource not ready, will retry: %s", s)
  284. select {
  285. case <-stop:
  286. return
  287. case <-time.After(duration):
  288. duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
  289. }
  290. }
  291. }(s)
  292. }
  293. done := make(chan struct{})
  294. go func() {
  295. wg.Wait()
  296. close(done)
  297. }()
  298. var s datasource.Datasource
  299. select {
  300. case s = <-ds:
  301. err := fetchAndSave(s)
  302. if err != nil {
  303. log.Errorf("Error fetching cloud-init datasource(%s): %s", s, err)
  304. }
  305. case <-done:
  306. case <-time.After(datasourceTimeout):
  307. }
  308. close(stop)
  309. return s
  310. }
  311. func isCompose(content string) bool {
  312. return strings.HasPrefix(content, "#compose\n")
  313. }
  314. func composeToCloudConfig(bytes []byte) ([]byte, error) {
  315. compose := make(map[interface{}]interface{})
  316. err := yaml.Unmarshal(bytes, &compose)
  317. if err != nil {
  318. return nil, err
  319. }
  320. return yaml.Marshal(map[interface{}]interface{}{
  321. "rancher": map[interface{}]interface{}{
  322. "services": compose,
  323. },
  324. })
  325. }
  326. const gzipMagicBytes = "\x1f\x8b"
  327. func decompressIfGzip(userdataBytes []byte) ([]byte, error) {
  328. if !bytes.HasPrefix(userdataBytes, []byte(gzipMagicBytes)) {
  329. return userdataBytes, nil
  330. }
  331. return config.DecompressGzip(userdataBytes)
  332. }