cloudinit.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // Copyright 2015 CoreOS, Inc.
  2. // Copyright 2015 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 cloudinit
  16. import (
  17. "errors"
  18. "flag"
  19. "fmt"
  20. "os"
  21. "os/exec"
  22. "strings"
  23. "sync"
  24. "time"
  25. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  26. log "github.com/Sirupsen/logrus"
  27. "github.com/coreos/coreos-cloudinit/config"
  28. "github.com/coreos/coreos-cloudinit/datasource"
  29. "github.com/coreos/coreos-cloudinit/datasource/configdrive"
  30. "github.com/coreos/coreos-cloudinit/datasource/file"
  31. "github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean"
  32. "github.com/coreos/coreos-cloudinit/datasource/metadata/ec2"
  33. "github.com/coreos/coreos-cloudinit/datasource/metadata/gce"
  34. "github.com/coreos/coreos-cloudinit/datasource/metadata/packet"
  35. "github.com/coreos/coreos-cloudinit/datasource/proc_cmdline"
  36. "github.com/coreos/coreos-cloudinit/datasource/url"
  37. "github.com/coreos/coreos-cloudinit/pkg"
  38. "github.com/coreos/coreos-cloudinit/system"
  39. "github.com/rancher/netconf"
  40. rancherConfig "github.com/rancher/os/config"
  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. sshKeyName = "rancheros-cloud-config"
  48. resizeStamp = "/var/lib/rancher/resizefs.done"
  49. )
  50. var (
  51. save bool
  52. execute bool
  53. network bool
  54. flags *flag.FlagSet
  55. )
  56. func init() {
  57. flags = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
  58. flags.BoolVar(&network, "network", true, "use network based datasources")
  59. flags.BoolVar(&save, "save", false, "save cloud config and exit")
  60. flags.BoolVar(&execute, "execute", false, "execute saved cloud config")
  61. }
  62. func saveFiles(cloudConfigBytes, scriptBytes []byte, metadata datasource.Metadata) error {
  63. os.MkdirAll(rancherConfig.CloudConfigDir, os.ModeDir|0600)
  64. os.Remove(rancherConfig.CloudConfigScriptFile)
  65. os.Remove(rancherConfig.CloudConfigBootFile)
  66. os.Remove(rancherConfig.MetaDataFile)
  67. if len(scriptBytes) > 0 {
  68. log.Infof("Writing to %s", rancherConfig.CloudConfigScriptFile)
  69. if err := util.WriteFileAtomic(rancherConfig.CloudConfigScriptFile, scriptBytes, 500); err != nil {
  70. log.Errorf("Error while writing file %s: %v", rancherConfig.CloudConfigScriptFile, err)
  71. return err
  72. }
  73. }
  74. if err := util.WriteFileAtomic(rancherConfig.CloudConfigBootFile, cloudConfigBytes, 400); err != nil {
  75. return err
  76. }
  77. log.Infof("Written to %s:\n%s", rancherConfig.CloudConfigBootFile, string(cloudConfigBytes))
  78. metaDataBytes, err := yaml.Marshal(metadata)
  79. if err != nil {
  80. return err
  81. }
  82. if err = util.WriteFileAtomic(rancherConfig.MetaDataFile, metaDataBytes, 400); err != nil {
  83. return err
  84. }
  85. log.Infof("Written to %s:\n%s", rancherConfig.MetaDataFile, string(metaDataBytes))
  86. return nil
  87. }
  88. func currentDatasource() (datasource.Datasource, error) {
  89. cfg := rancherConfig.LoadConfig()
  90. dss := getDatasources(cfg)
  91. if len(dss) == 0 {
  92. return nil, nil
  93. }
  94. ds := selectDatasource(dss)
  95. return ds, nil
  96. }
  97. func saveCloudConfig() error {
  98. userDataBytes, metadata, err := fetchUserData()
  99. if err != nil {
  100. return err
  101. }
  102. userData := string(userDataBytes)
  103. scriptBytes := []byte{}
  104. if config.IsScript(userData) {
  105. scriptBytes = userDataBytes
  106. userDataBytes = []byte{}
  107. } else if isCompose(userData) {
  108. if userDataBytes, err = composeToCloudConfig(userDataBytes); err != nil {
  109. log.Errorf("Failed to convert compose to cloud-config syntax: %v", err)
  110. return err
  111. }
  112. } else if config.IsCloudConfig(userData) {
  113. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  114. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config, not saving.")
  115. userDataBytes = []byte{}
  116. }
  117. } else {
  118. log.Errorf("Unrecognized user-data\n%s", userData)
  119. userDataBytes = []byte{}
  120. }
  121. if _, err := rancherConfig.ReadConfig(userDataBytes, false); err != nil {
  122. log.WithFields(log.Fields{"cloud-config": userData, "err": err}).Warn("Failed to parse cloud-config")
  123. return errors.New("Failed to parse cloud-config")
  124. }
  125. return saveFiles(userDataBytes, scriptBytes, metadata)
  126. }
  127. func fetchUserData() ([]byte, datasource.Metadata, error) {
  128. var metadata datasource.Metadata
  129. ds, err := currentDatasource()
  130. if err != nil || ds == nil {
  131. log.Errorf("Failed to select datasource: %v", err)
  132. return nil, metadata, err
  133. }
  134. log.Infof("Fetching user-data from datasource %v", ds.Type())
  135. userDataBytes, err := ds.FetchUserdata()
  136. if err != nil {
  137. log.Errorf("Failed fetching user-data from datasource: %v", err)
  138. return nil, metadata, err
  139. }
  140. log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
  141. metadata, err = ds.FetchMetadata()
  142. if err != nil {
  143. log.Errorf("Failed fetching meta-data from datasource: %v", err)
  144. return nil, metadata, err
  145. }
  146. return userDataBytes, metadata, nil
  147. }
  148. func resizeDevice(cfg *rancherConfig.CloudConfig) error {
  149. cmd := exec.Command("growpart", cfg.Rancher.ResizeDevice, "1")
  150. err := cmd.Run()
  151. if err != nil {
  152. return err
  153. }
  154. cmd = exec.Command("partprobe")
  155. err = cmd.Run()
  156. if err != nil {
  157. return err
  158. }
  159. cmd = exec.Command("resize2fs", fmt.Sprintf("%s1", cfg.Rancher.ResizeDevice))
  160. err = cmd.Run()
  161. if err != nil {
  162. return err
  163. }
  164. return nil
  165. }
  166. func executeCloudConfig() error {
  167. cc := rancherConfig.LoadConfig()
  168. if len(cc.SSHAuthorizedKeys) > 0 {
  169. authorizeSSHKeys("rancher", cc.SSHAuthorizedKeys, sshKeyName)
  170. authorizeSSHKeys("docker", cc.SSHAuthorizedKeys, sshKeyName)
  171. }
  172. for _, file := range cc.WriteFiles {
  173. f := system.File{File: file}
  174. fullPath, err := system.WriteFile(&f, "/")
  175. if err != nil {
  176. log.WithFields(log.Fields{"err": err, "path": fullPath}).Error("Error writing file")
  177. continue
  178. }
  179. log.Printf("Wrote file %s to filesystem", fullPath)
  180. }
  181. if _, err := os.Stat(resizeStamp); os.IsNotExist(err) && cc.Rancher.ResizeDevice != "" {
  182. if err := resizeDevice(cc); err == nil {
  183. os.Create(resizeStamp)
  184. } else {
  185. log.Errorf("Failed to resize %s: %s", cc.Rancher.ResizeDevice, err)
  186. }
  187. }
  188. return nil
  189. }
  190. func Main() {
  191. flags.Parse(os.Args[1:])
  192. log.Infof("Running cloud-init: save=%v, execute=%v", save, execute)
  193. if save {
  194. err := saveCloudConfig()
  195. if err != nil {
  196. log.WithFields(log.Fields{"err": err}).Error("Failed to save cloud-config")
  197. }
  198. }
  199. if execute {
  200. err := executeCloudConfig()
  201. if err != nil {
  202. log.WithFields(log.Fields{"err": err}).Error("Failed to execute cloud-config")
  203. }
  204. }
  205. }
  206. // getDatasources creates a slice of possible Datasources for cloudinit based
  207. // on the different source command-line flags.
  208. func getDatasources(cfg *rancherConfig.CloudConfig) []datasource.Datasource {
  209. dss := make([]datasource.Datasource, 0, 5)
  210. for _, ds := range cfg.Rancher.CloudInit.Datasources {
  211. parts := strings.SplitN(ds, ":", 2)
  212. switch parts[0] {
  213. case "ec2":
  214. if network {
  215. if len(parts) == 1 {
  216. dss = append(dss, ec2.NewDatasource(ec2.DefaultAddress))
  217. } else {
  218. dss = append(dss, ec2.NewDatasource(parts[1]))
  219. }
  220. }
  221. case "file":
  222. if len(parts) == 2 {
  223. dss = append(dss, file.NewDatasource(parts[1]))
  224. }
  225. case "url":
  226. if network {
  227. if len(parts) == 2 {
  228. dss = append(dss, url.NewDatasource(parts[1]))
  229. }
  230. }
  231. case "cmdline":
  232. if network {
  233. if len(parts) == 1 {
  234. dss = append(dss, proc_cmdline.NewDatasource())
  235. }
  236. }
  237. case "configdrive":
  238. if len(parts) == 2 {
  239. dss = append(dss, configdrive.NewDatasource(parts[1]))
  240. }
  241. case "digitalocean":
  242. if network {
  243. if len(parts) == 1 {
  244. dss = append(dss, digitalocean.NewDatasource(digitalocean.DefaultAddress))
  245. } else {
  246. dss = append(dss, digitalocean.NewDatasource(parts[1]))
  247. }
  248. } else {
  249. enableDoLinkLocal()
  250. }
  251. case "gce":
  252. if network {
  253. dss = append(dss, gce.NewDatasource("http://metadata.google.internal/"))
  254. }
  255. case "packet":
  256. if !network {
  257. enablePacketNetwork(&cfg.Rancher)
  258. }
  259. dss = append(dss, packet.NewDatasource("https://metadata.packet.net/"))
  260. }
  261. }
  262. return dss
  263. }
  264. func enableDoLinkLocal() {
  265. err := netconf.ApplyNetworkConfigs(&netconf.NetworkConfig{
  266. Interfaces: map[string]netconf.InterfaceConfig{
  267. "eth0": {
  268. IPV4LL: true,
  269. },
  270. },
  271. })
  272. if err != nil {
  273. log.Errorf("Failed to apply link local on eth0: %v", err)
  274. }
  275. }
  276. // selectDatasource attempts to choose a valid Datasource to use based on its
  277. // current availability. The first Datasource to report to be available is
  278. // returned. Datasources will be retried if possible if they are not
  279. // immediately available. If all Datasources are permanently unavailable or
  280. // datasourceTimeout is reached before one becomes available, nil is returned.
  281. func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
  282. ds := make(chan datasource.Datasource)
  283. stop := make(chan struct{})
  284. var wg sync.WaitGroup
  285. for _, s := range sources {
  286. wg.Add(1)
  287. go func(s datasource.Datasource) {
  288. defer wg.Done()
  289. duration := datasourceInterval
  290. for {
  291. log.Infof("Checking availability of %q\n", s.Type())
  292. if s.IsAvailable() {
  293. ds <- s
  294. return
  295. } else if !s.AvailabilityChanges() {
  296. return
  297. }
  298. select {
  299. case <-stop:
  300. return
  301. case <-time.After(duration):
  302. duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
  303. }
  304. }
  305. }(s)
  306. }
  307. done := make(chan struct{})
  308. go func() {
  309. wg.Wait()
  310. close(done)
  311. }()
  312. var s datasource.Datasource
  313. select {
  314. case s = <-ds:
  315. case <-done:
  316. case <-time.After(datasourceTimeout):
  317. }
  318. close(stop)
  319. return s
  320. }
  321. func isCompose(content string) bool {
  322. return strings.HasPrefix(content, "#compose\n")
  323. }
  324. func composeToCloudConfig(bytes []byte) ([]byte, error) {
  325. compose := make(map[interface{}]interface{})
  326. err := yaml.Unmarshal(bytes, &compose)
  327. if err != nil {
  328. return nil, err
  329. }
  330. return yaml.Marshal(map[interface{}]interface{}{
  331. "rancher": map[interface{}]interface{}{
  332. "services": compose,
  333. },
  334. })
  335. }