cloudinitsave.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. "errors"
  18. "os"
  19. "strings"
  20. "sync"
  21. "syscall"
  22. "time"
  23. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  24. "github.com/coreos/coreos-cloudinit/config"
  25. "github.com/coreos/coreos-cloudinit/datasource"
  26. "github.com/coreos/coreos-cloudinit/datasource/configdrive"
  27. "github.com/coreos/coreos-cloudinit/datasource/file"
  28. "github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean"
  29. "github.com/coreos/coreos-cloudinit/datasource/metadata/ec2"
  30. "github.com/coreos/coreos-cloudinit/datasource/metadata/packet"
  31. "github.com/coreos/coreos-cloudinit/datasource/proc_cmdline"
  32. "github.com/coreos/coreos-cloudinit/datasource/url"
  33. "github.com/coreos/coreos-cloudinit/pkg"
  34. "github.com/docker/docker/pkg/mount"
  35. "github.com/rancher/os/cmd/cloudinitsave/gce"
  36. "github.com/rancher/os/cmd/control"
  37. "github.com/rancher/os/cmd/network"
  38. rancherConfig "github.com/rancher/os/config"
  39. "github.com/rancher/os/log"
  40. "github.com/rancher/os/netconf"
  41. "github.com/rancher/os/util"
  42. )
  43. const (
  44. datasourceInterval = 100 * time.Millisecond
  45. datasourceMaxInterval = 30 * time.Second
  46. datasourceTimeout = 5 * time.Minute
  47. configDevName = "config-2"
  48. configDev = "LABEL=" + configDevName
  49. configDevMountPoint = "/media/config-2"
  50. )
  51. func Main() {
  52. log.InitLogger()
  53. log.Info("Running cloud-init-save")
  54. if err := control.UdevSettle(); err != nil {
  55. log.Errorf("Failed to run udev settle: %v", err)
  56. }
  57. cfg := rancherConfig.LoadConfig()
  58. network.ApplyNetworkConfig(cfg)
  59. if err := SaveCloudConfig(true); err != nil {
  60. log.Errorf("Failed to save cloud-config: %v", err)
  61. }
  62. }
  63. func MountConfigDrive() error {
  64. if err := os.MkdirAll(configDevMountPoint, 644); err != nil {
  65. return err
  66. }
  67. configDev := util.ResolveDevice(configDev)
  68. if configDev == "" {
  69. return mount.Mount(configDevName, configDevMountPoint, "9p", "trans=virtio,version=9p2000.L")
  70. }
  71. fsType, err := util.GetFsType(configDev)
  72. if err != nil {
  73. return err
  74. }
  75. return mount.Mount(configDev, configDevMountPoint, fsType, "ro")
  76. }
  77. func UnmountConfigDrive() error {
  78. return syscall.Unmount(configDevMountPoint, 0)
  79. }
  80. func SaveCloudConfig(network bool) error {
  81. userDataBytes, metadata, err := fetchUserData(network)
  82. if err != nil {
  83. return err
  84. }
  85. userData := string(userDataBytes)
  86. scriptBytes := []byte{}
  87. if config.IsScript(userData) {
  88. scriptBytes = userDataBytes
  89. userDataBytes = []byte{}
  90. } else if isCompose(userData) {
  91. if userDataBytes, err = composeToCloudConfig(userDataBytes); err != nil {
  92. log.Errorf("Failed to convert compose to cloud-config syntax: %v", err)
  93. return err
  94. }
  95. } else if config.IsCloudConfig(userData) {
  96. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  97. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config, not saving.")
  98. userDataBytes = []byte{}
  99. }
  100. } else {
  101. log.Errorf("Unrecognized user-data\n%s", userData)
  102. userDataBytes = []byte{}
  103. }
  104. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  105. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config")
  106. return errors.New("Failed to parse cloud-config")
  107. }
  108. return saveFiles(userDataBytes, scriptBytes, metadata)
  109. }
  110. func RequiresNetwork(datasource string) bool {
  111. parts := strings.SplitN(datasource, ":", 2)
  112. requiresNetwork, ok := map[string]bool{
  113. "ec2": true,
  114. "file": false,
  115. "url": true,
  116. "cmdline": true,
  117. "configdrive": false,
  118. "digitalocean": true,
  119. "gce": true,
  120. "packet": true,
  121. }[parts[0]]
  122. return ok && requiresNetwork
  123. }
  124. func saveFiles(cloudConfigBytes, scriptBytes []byte, metadata datasource.Metadata) error {
  125. os.MkdirAll(rancherConfig.CloudConfigDir, os.ModeDir|0600)
  126. if len(scriptBytes) > 0 {
  127. log.Infof("Writing to %s", rancherConfig.CloudConfigScriptFile)
  128. if err := util.WriteFileAtomic(rancherConfig.CloudConfigScriptFile, scriptBytes, 500); err != nil {
  129. log.Errorf("Error while writing file %s: %v", rancherConfig.CloudConfigScriptFile, err)
  130. return err
  131. }
  132. }
  133. if len(cloudConfigBytes) > 0 {
  134. if err := util.WriteFileAtomic(rancherConfig.CloudConfigBootFile, cloudConfigBytes, 400); err != nil {
  135. return err
  136. }
  137. log.Infof("Written to %s:\n%s", rancherConfig.CloudConfigBootFile, string(cloudConfigBytes))
  138. }
  139. metaDataBytes, err := yaml.Marshal(metadata)
  140. if err != nil {
  141. return err
  142. }
  143. if err = util.WriteFileAtomic(rancherConfig.MetaDataFile, metaDataBytes, 400); err != nil {
  144. return err
  145. }
  146. log.Infof("Written to %s:\n%s", rancherConfig.MetaDataFile, string(metaDataBytes))
  147. return nil
  148. }
  149. func currentDatasource(network bool) (datasource.Datasource, error) {
  150. cfg := rancherConfig.LoadConfig()
  151. dss := getDatasources(cfg, network)
  152. if len(dss) == 0 {
  153. return nil, nil
  154. }
  155. ds := selectDatasource(dss)
  156. return ds, nil
  157. }
  158. func fetchUserData(network bool) ([]byte, datasource.Metadata, error) {
  159. var metadata datasource.Metadata
  160. ds, err := currentDatasource(network)
  161. if err != nil || ds == nil {
  162. log.Errorf("Failed to select datasource: %v", err)
  163. return nil, metadata, err
  164. }
  165. log.Infof("Fetching user-data from datasource %v", ds.Type())
  166. userDataBytes, err := ds.FetchUserdata()
  167. if err != nil {
  168. log.Errorf("Failed fetching user-data from datasource: %v", err)
  169. return nil, metadata, err
  170. }
  171. log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
  172. metadata, err = ds.FetchMetadata()
  173. if err != nil {
  174. log.Errorf("Failed fetching meta-data from datasource: %v", err)
  175. return nil, metadata, err
  176. }
  177. return userDataBytes, metadata, nil
  178. }
  179. // getDatasources creates a slice of possible Datasources for cloudinit based
  180. // on the different source command-line flags.
  181. func getDatasources(cfg *rancherConfig.CloudConfig, network bool) []datasource.Datasource {
  182. dss := make([]datasource.Datasource, 0, 5)
  183. for _, ds := range cfg.Rancher.CloudInit.Datasources {
  184. parts := strings.SplitN(ds, ":", 2)
  185. switch parts[0] {
  186. case "ec2":
  187. if network {
  188. if len(parts) == 1 {
  189. dss = append(dss, ec2.NewDatasource(ec2.DefaultAddress))
  190. } else {
  191. dss = append(dss, ec2.NewDatasource(parts[1]))
  192. }
  193. }
  194. case "file":
  195. if len(parts) == 2 {
  196. dss = append(dss, file.NewDatasource(parts[1]))
  197. }
  198. case "url":
  199. if network {
  200. if len(parts) == 2 {
  201. dss = append(dss, url.NewDatasource(parts[1]))
  202. }
  203. }
  204. case "cmdline":
  205. if network {
  206. if len(parts) == 1 {
  207. dss = append(dss, proc_cmdline.NewDatasource())
  208. }
  209. }
  210. case "configdrive":
  211. if len(parts) == 2 {
  212. dss = append(dss, configdrive.NewDatasource(parts[1]))
  213. }
  214. case "digitalocean":
  215. if network {
  216. if len(parts) == 1 {
  217. dss = append(dss, digitalocean.NewDatasource(digitalocean.DefaultAddress))
  218. } else {
  219. dss = append(dss, digitalocean.NewDatasource(parts[1]))
  220. }
  221. } else {
  222. enableDoLinkLocal()
  223. }
  224. case "gce":
  225. if network {
  226. dss = append(dss, gce.NewDatasource("http://metadata.google.internal/"))
  227. }
  228. case "packet":
  229. if !network {
  230. enablePacketNetwork(&cfg.Rancher)
  231. }
  232. dss = append(dss, packet.NewDatasource("https://metadata.packet.net/"))
  233. }
  234. }
  235. return dss
  236. }
  237. func enableDoLinkLocal() {
  238. err := netconf.ApplyNetworkConfigs(&rancherConfig.NetworkConfig{
  239. Interfaces: map[string]rancherConfig.InterfaceConfig{
  240. "eth0": {
  241. IPV4LL: true,
  242. },
  243. },
  244. })
  245. if err != nil {
  246. log.Errorf("Failed to apply link local on eth0: %v", err)
  247. }
  248. }
  249. // selectDatasource attempts to choose a valid Datasource to use based on its
  250. // current availability. The first Datasource to report to be available is
  251. // returned. Datasources will be retried if possible if they are not
  252. // immediately available. If all Datasources are permanently unavailable or
  253. // datasourceTimeout is reached before one becomes available, nil is returned.
  254. func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
  255. ds := make(chan datasource.Datasource)
  256. stop := make(chan struct{})
  257. var wg sync.WaitGroup
  258. for _, s := range sources {
  259. wg.Add(1)
  260. go func(s datasource.Datasource) {
  261. defer wg.Done()
  262. duration := datasourceInterval
  263. for {
  264. log.Infof("Checking availability of %q\n", s.Type())
  265. if s.IsAvailable() {
  266. ds <- s
  267. return
  268. } else if !s.AvailabilityChanges() {
  269. return
  270. }
  271. select {
  272. case <-stop:
  273. return
  274. case <-time.After(duration):
  275. duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
  276. }
  277. }
  278. }(s)
  279. }
  280. done := make(chan struct{})
  281. go func() {
  282. wg.Wait()
  283. close(done)
  284. }()
  285. var s datasource.Datasource
  286. select {
  287. case s = <-ds:
  288. case <-done:
  289. case <-time.After(datasourceTimeout):
  290. }
  291. close(stop)
  292. return s
  293. }
  294. func isCompose(content string) bool {
  295. return strings.HasPrefix(content, "#compose\n")
  296. }
  297. func composeToCloudConfig(bytes []byte) ([]byte, error) {
  298. compose := make(map[interface{}]interface{})
  299. err := yaml.Unmarshal(bytes, &compose)
  300. if err != nil {
  301. return nil, err
  302. }
  303. return yaml.Marshal(map[interface{}]interface{}{
  304. "rancher": map[interface{}]interface{}{
  305. "services": compose,
  306. },
  307. })
  308. }