1
0
mirror of https://github.com/rancher/os.git synced 2025-06-30 16:51:47 +00:00
os/cmd/cloudinit/cloudinit.go

323 lines
8.3 KiB
Go
Raw Normal View History

2015-02-23 19:00:24 +00:00
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 Rancher Labs, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2015-02-19 21:43:37 +00:00
package cloudinit
2015-02-19 03:05:23 +00:00
import (
"flag"
"io/ioutil"
"os"
"os/exec"
2015-02-20 16:18:55 +00:00
"path"
"reflect"
2015-02-20 03:05:17 +00:00
"strings"
2015-02-19 03:05:23 +00:00
"sync"
"time"
2015-02-20 03:05:17 +00:00
log "github.com/Sirupsen/logrus"
2015-02-19 03:05:23 +00:00
"github.com/coreos/coreos-cloudinit/config"
"github.com/coreos/coreos-cloudinit/config/validate"
"github.com/coreos/coreos-cloudinit/datasource"
"github.com/coreos/coreos-cloudinit/datasource/configdrive"
"github.com/coreos/coreos-cloudinit/datasource/file"
"github.com/coreos/coreos-cloudinit/datasource/metadata/ec2"
"github.com/coreos/coreos-cloudinit/datasource/proc_cmdline"
"github.com/coreos/coreos-cloudinit/datasource/url"
"github.com/coreos/coreos-cloudinit/initialize"
"github.com/coreos/coreos-cloudinit/pkg"
"github.com/coreos/coreos-cloudinit/system"
2015-02-20 03:05:17 +00:00
rancherConfig "github.com/rancherio/os/config"
2015-02-19 03:05:23 +00:00
"gopkg.in/yaml.v2"
)
const (
datasourceInterval = 100 * time.Millisecond
datasourceMaxInterval = 30 * time.Second
datasourceTimeout = 5 * time.Minute
)
var (
2015-02-20 03:05:17 +00:00
outputDir string
outputFile string
save bool
2015-02-23 19:00:24 +00:00
execute bool
2015-02-20 03:05:17 +00:00
sshKeyName string
2015-02-20 16:18:55 +00:00
flags *flag.FlagSet
2015-02-19 03:05:23 +00:00
)
func init() {
2015-02-20 16:18:55 +00:00
flags = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
flags.StringVar(&outputDir, "dir", "/var/lib/rancher/conf", "working directory")
2015-02-23 19:00:24 +00:00
flags.StringVar(&outputFile, "file", "cloud-config.yml", "output cloud config file name")
2015-02-20 16:18:55 +00:00
flags.StringVar(&sshKeyName, "ssh-key-name", "rancheros-cloud-config", "SSH key name")
flags.BoolVar(&save, "save", false, "save cloud config and exit")
2015-02-23 19:00:24 +00:00
flags.BoolVar(&execute, "execute", false, "execute saved cloud config")
2015-02-19 03:05:23 +00:00
}
2015-02-19 21:43:37 +00:00
func Main() {
2015-02-23 19:00:24 +00:00
flags.Parse(rancherConfig.FilterGlobalConfig(os.Args[1:]))
2015-02-19 03:05:23 +00:00
2015-02-20 03:05:17 +00:00
cfg, err := rancherConfig.LoadConfig()
if err != nil {
log.Fatalf("Failed to read rancher config %v", err)
2015-02-19 03:05:23 +00:00
}
2015-02-20 03:05:17 +00:00
dss := getDatasources(cfg)
2015-02-19 03:05:23 +00:00
if len(dss) == 0 {
2015-02-20 16:18:55 +00:00
log.Infof("No datasources available %v", cfg.CloudInit.Datasources)
2015-02-20 03:05:17 +00:00
os.Exit(0)
2015-02-19 03:05:23 +00:00
}
ds := selectDatasource(dss)
if ds == nil {
2015-02-20 03:05:17 +00:00
log.Info("No datasources found")
os.Exit(0)
2015-02-19 03:05:23 +00:00
}
2015-02-20 16:18:55 +00:00
log.Infof("Fetching user-data from datasource %v", ds.Type())
2015-02-19 03:05:23 +00:00
userdataBytes, err := ds.FetchUserdata()
if err != nil {
2015-02-20 03:05:17 +00:00
log.Fatalf("Failed fetching user-data from datasource: %v", err)
2015-02-19 03:05:23 +00:00
}
if report, err := validate.Validate(userdataBytes); err == nil {
2015-02-20 03:05:17 +00:00
fail := false
2015-02-19 03:05:23 +00:00
for _, e := range report.Entries() {
2015-02-20 03:05:17 +00:00
log.Error(e)
fail = true
2015-02-19 03:05:23 +00:00
}
2015-02-20 03:05:17 +00:00
if fail {
2015-02-23 19:00:24 +00:00
log.Info("failed validation")
2015-02-19 03:05:23 +00:00
os.Exit(1)
}
2015-02-20 03:05:17 +00:00
} else {
log.Fatalf("Failed while validating user_data (%v)", err)
2015-02-19 03:05:23 +00:00
}
2015-02-23 19:00:24 +00:00
log.Infof("Fetching meta-data from datasource of type %v", ds.Type())
2015-02-19 03:05:23 +00:00
metadata, err := ds.FetchMetadata()
if err != nil {
2015-02-23 19:00:24 +00:00
log.Infof("Failed fetching meta-data from datasource: %v", err)
2015-02-19 03:05:23 +00:00
os.Exit(1)
}
// Apply environment to user-data
2015-02-20 03:05:17 +00:00
env := initialize.NewEnvironment("/", ds.ConfigRoot(), outputDir, sshKeyName, metadata)
2015-02-19 03:05:23 +00:00
userdata := env.Apply(string(userdataBytes))
var ccu *config.CloudConfig
var script *config.Script
if ud, err := initialize.ParseUserData(userdata); err != nil {
2015-02-20 03:05:17 +00:00
log.Fatalf("Failed to parse user-data: %v\n", err)
2015-02-19 03:05:23 +00:00
} else {
switch t := ud.(type) {
case *config.CloudConfig:
ccu = t
case *config.Script:
script = t
}
}
2015-02-23 19:00:24 +00:00
log.Info("Merging cloud-config from meta-data and user-data")
2015-02-19 03:05:23 +00:00
cc := mergeConfigs(ccu, metadata)
2015-02-20 03:05:17 +00:00
if save {
2015-02-19 03:05:23 +00:00
var fileData []byte
if script != nil {
fileData = userdataBytes
} else {
if data, err := yaml.Marshal(cc); err != nil {
2015-02-20 03:05:17 +00:00
log.Fatalf("Error while marshalling cloud config %v", err)
2015-02-19 03:05:23 +00:00
} else {
2015-02-23 19:00:24 +00:00
fileData = append([]byte("#cloud-config\n"), data...)
2015-02-19 03:05:23 +00:00
}
}
2015-02-20 16:18:55 +00:00
output := path.Join(outputDir, outputFile)
2015-02-23 19:00:24 +00:00
log.Infof("Writing merged cloud-config to %s", output)
2015-02-20 16:18:55 +00:00
if err := ioutil.WriteFile(output, fileData, 400); err != nil {
2015-02-20 03:05:17 +00:00
log.Fatalf("Error while writing file %v", err)
2015-02-19 03:05:23 +00:00
}
2015-02-19 20:47:06 +00:00
2015-02-19 03:05:23 +00:00
os.Exit(0)
}
if script != nil {
if ds.Type() != "local-file" {
2015-02-23 19:00:24 +00:00
log.Info("can only execute local files")
}
cmdPath := reflect.ValueOf(ds).Elem().Field(0).String()
2015-02-23 19:00:24 +00:00
if err := os.Chmod(cmdPath, 0500); err != nil {
log.Fatalf("Failed to set %s to executable : %v", cmdPath, err)
}
cmd := exec.Command(cmdPath)
2015-02-23 19:00:24 +00:00
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Info("Running ", cmdPath)
if err := cmd.Run(); err != nil {
2015-02-23 19:00:24 +00:00
log.Infof("Failed to run script: %v\n", err)
os.Exit(1)
}
}
if &cc == nil {
2015-02-23 19:00:24 +00:00
log.Fatal("no config or script found")
}
if len(cc.SSHAuthorizedKeys) > 0 {
authorizeSSHKeys("rancher", cc.SSHAuthorizedKeys, env.SSHKeyName())
2015-02-19 03:05:23 +00:00
}
for _, user := range cc.Users {
if user.Name == "" {
continue
2015-02-19 03:05:23 +00:00
}
if len(user.SSHAuthorizedKeys) > 0 {
authorizeSSHKeys(user.Name, user.SSHAuthorizedKeys, env.SSHKeyName())
}
}
2015-02-23 19:00:24 +00:00
for _, file := range cc.WriteFiles {
f := system.File{File: file}
fullPath, err := system.WriteFile(&f, env.Root())
if err != nil {
log.Fatalf("%v", err)
}
log.Printf("Wrote file %s to filesystem", fullPath)
2015-02-19 03:05:23 +00:00
}
2015-02-19 03:05:23 +00:00
}
// mergeConfigs merges certain options from md (meta-data from the datasource)
// onto cc (a CloudConfig derived from user-data), if they are not already set
// on cc (i.e. user-data always takes precedence)
func mergeConfigs(cc *config.CloudConfig, md datasource.Metadata) (out config.CloudConfig) {
if cc != nil {
out = *cc
}
if md.Hostname != "" {
if out.Hostname != "" {
2015-02-23 19:00:24 +00:00
log.Infof("Warning: user-data hostname (%s) overrides metadata hostname (%s)\n", out.Hostname, md.Hostname)
2015-02-19 03:05:23 +00:00
} else {
out.Hostname = md.Hostname
}
}
for _, key := range md.SSHPublicKeys {
out.SSHAuthorizedKeys = append(out.SSHAuthorizedKeys, key)
}
return
}
// getDatasources creates a slice of possible Datasources for cloudinit based
// on the different source command-line flags.
2015-02-20 03:05:17 +00:00
func getDatasources(cfg *rancherConfig.Config) []datasource.Datasource {
2015-02-19 03:05:23 +00:00
dss := make([]datasource.Datasource, 0, 5)
2015-02-20 03:05:17 +00:00
2015-02-23 19:00:24 +00:00
if execute {
cloudConfig := path.Join(outputDir, outputFile)
if _, err := os.Stat(cloudConfig); os.IsNotExist(err) {
return dss
}
dss = append(dss, file.NewDatasource(cloudConfig))
return dss
}
2015-02-20 03:05:17 +00:00
for _, ds := range cfg.CloudInit.Datasources {
2015-02-20 16:18:55 +00:00
parts := strings.SplitN(ds, ":", 2)
2015-02-20 03:05:17 +00:00
switch parts[0] {
case "ec2":
if len(parts) == 1 {
dss = append(dss, ec2.NewDatasource(ec2.DefaultAddress))
} else {
dss = append(dss, ec2.NewDatasource(parts[1]))
}
case "file":
if len(parts) == 2 {
dss = append(dss, file.NewDatasource(parts[1]))
}
case "url":
if len(parts) == 2 {
dss = append(dss, url.NewDatasource(parts[1]))
}
case "cmdline":
if len(parts) == 2 {
dss = append(dss, proc_cmdline.NewDatasource())
}
case "configdrive":
if len(parts) == 2 {
dss = append(dss, configdrive.NewDatasource(parts[1]))
}
}
2015-02-19 03:05:23 +00:00
}
2015-02-20 03:05:17 +00:00
2015-02-19 03:05:23 +00:00
return dss
}
// selectDatasource attempts to choose a valid Datasource to use based on its
// current availability. The first Datasource to report to be available is
// returned. Datasources will be retried if possible if they are not
// immediately available. If all Datasources are permanently unavailable or
// datasourceTimeout is reached before one becomes available, nil is returned.
func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
ds := make(chan datasource.Datasource)
stop := make(chan struct{})
var wg sync.WaitGroup
for _, s := range sources {
wg.Add(1)
go func(s datasource.Datasource) {
defer wg.Done()
duration := datasourceInterval
for {
2015-02-23 19:00:24 +00:00
log.Infof("Checking availability of %q\n", s.Type())
2015-02-19 03:05:23 +00:00
if s.IsAvailable() {
ds <- s
return
} else if !s.AvailabilityChanges() {
return
}
select {
case <-stop:
return
case <-time.After(duration):
duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
}
}
}(s)
}
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
var s datasource.Datasource
select {
case s = <-ds:
case <-done:
case <-time.After(datasourceTimeout):
}
close(stop)
return s
}