github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/provider/maas/util.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package maas 5 6 import ( 7 "net/url" 8 "path" 9 "strings" 10 11 "github.com/juju/utils" 12 goyaml "gopkg.in/yaml.v1" 13 14 "github.com/juju/juju/cloudinit" 15 "github.com/juju/juju/environs/config" 16 "github.com/juju/juju/instance" 17 "github.com/juju/juju/juju/paths" 18 ) 19 20 // extractSystemId extracts the 'system_id' part from an InstanceId. 21 // "/MAAS/api/1.0/nodes/system_id/" => "system_id" 22 func extractSystemId(instanceId instance.Id) string { 23 trimmed := strings.TrimRight(string(instanceId), "/") 24 split := strings.Split(trimmed, "/") 25 return split[len(split)-1] 26 } 27 28 // getSystemIdValues returns a url.Values object with all the 'system_ids' 29 // from the given instanceIds stored under the specified key. This is used 30 // to filter out instances when listing the nodes objects. 31 func getSystemIdValues(key string, instanceIds []instance.Id) url.Values { 32 values := url.Values{} 33 for _, instanceId := range instanceIds { 34 values.Add(key, extractSystemId(instanceId)) 35 } 36 return values 37 } 38 39 // machineInfo is the structure used to pass information between the provider 40 // and the agent running on a node. 41 // When a node is started, the provider code creates a machineInfo object 42 // containing information about the node being started and configures 43 // cloudinit to get a YAML representation of that object written on the node's 44 // filesystem during its first startup. That file is then read by the juju 45 // agent running on the node and converted back into a machineInfo object. 46 type machineInfo struct { 47 Hostname string `yaml:,omitempty` 48 } 49 50 var maasDataDir = paths.MustSucceed(paths.DataDir(config.LatestLtsSeries())) 51 var _MAASInstanceFilename = path.Join(maasDataDir, "MAASmachine.txt") 52 53 // cloudinitRunCmd returns the shell command that, when run, will create the 54 // "machine info" file containing the hostname of a machine. 55 // That command is destined to be used by cloudinit. 56 func (info *machineInfo) cloudinitRunCmd(series string) (string, error) { 57 dataDir, err := paths.DataDir(series) 58 if err != nil { 59 return "", err 60 } 61 renderer, err := cloudinit.NewRenderer(series) 62 if err != nil { 63 return "", err 64 } 65 66 yaml, err := goyaml.Marshal(info) 67 if err != nil { 68 return "", err 69 } 70 fileName := renderer.PathJoin(renderer.FromSlash(dataDir), "MAASmachine.txt") 71 script := renderer.Mkdir(dataDir) 72 contents := utils.ShQuote(string(yaml)) 73 script = append(script, renderer.WriteFile(fileName, contents, 0755)...) 74 return strings.Join(script, "\n"), nil 75 } 76 77 // load loads the "machine info" file and parse the content into the info 78 // object. 79 func (info *machineInfo) load() error { 80 return utils.ReadYaml(_MAASInstanceFilename, info) 81 }