~kirkland/+junk/myFirstGo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/gorun
//
//    ubuntu-run-instances: ec2-run-instances that support human readable aliases for AMI's
//
//    Copyright (C) 2011 Dustin Kirkland <kirkland@ubuntu.com>
//
//    Authors: Dustin Kirkland <kirkland@ubuntu.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, version 3 of the License.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"exec"
	"fmt"
	"http"
	"io/ioutil"
	"os"
	"strings"
)

func parseAlias(word string) map[string]string {
	// BUG: cloud-images.ubuntu.com should maintain a current->oneiric symlink
	// BUG: shall we debate these defaults?
	alias := map[string]string{"release": "oneiric", "flavor": "server", "age": "daily", "rootstore": "ebs"}
	parts := strings.Split(word, ",", -1)
	// Autodetct the alias parts; allows for arbitrary ordering of options
	for _, p := range parts {
		switch p {
		case "server", "desktop":
			alias["flavor"] = p
		case "daily", "released":
			alias["age"] = p
		case "ebs", "instance-store":
			alias["rootstore"] = p
		default:
			alias["release"] = p
		}
	}
	return alias
}

func isAlias(aliases []string, word string) bool {
	// An alias word is of the form:
	//     release[,flavor[,age[,rootstore]]]
	//  where:
	//     - release is one of [hardy|karmic|lucid|maverick|natty|oneiric], defaults to 'oneiric'
	//     - flavor is one of [server|desktop], defaults to 'server'
	//     - age is one of [daily|released], defaults to 'daily'
	//     - rootstore is one of [ebs|instance-store], defaults to 'ebs'
	// Note that they can be in ANY comma-separated order!
	alias := parseAlias(word)
	for _, a := range aliases {
		parts := strings.Fields(a)
		if len(parts) > 3 && parts[0] == alias["release"] && parts[1] == alias["flavor"] && parts[2] == alias["age"] {
			return true
		}
	}
	return false
}

func getRegion(args []string) string {
	// Default to us-east-1 (least expensive option)
	region := "us-east-1"
	// Look for a region option
	bingo := 0
	for _, v := range args {
		if bingo == 1 {
			region = v
		} else if v == "--region" {
			bingo = 1
		}
	}
	return region
}

func getInstanceType(args []string) string {
	// Default to t1.micro (least expensive option)
	instance_type := "t1.micro"
	// Look for an instance type option
	bingo := 0
	for _, v := range args {
		if bingo == 1 {
			instanceType = v
		} else if v == "--instance-type" || v == "-t" {
			bingo = 1
		}
	}
	return instance_type
}

func getArch(instance_type string) string {
	// Default to amd64 wherever possible
	arch := "amd64"
	switch instance_type {
	case "c1.medium", "m1.small":
		arch = "i386"
	default:
		arch = "amd64"
	}
	return arch
}

func getVirt(instance_type string) string {
	// Default to paravirtual
	virt := "paravirtual"
	switch instance_type {
	case "cc1.4xlarge", "cg1.4xlarge":
		virt = "hvm"
	default:
		virt = "paravirtual"
	}
	return virt
}

func getAmi(region string, instance_type string, alias map[string]string) string {
	arch := getArch(instance_type)
	virt := getVirt(instance_type)
	url := fmt.Sprintf("https://cloud-images.ubuntu.com/query/%s/%s/%s.current.txt", alias["release"], alias["flavor"], alias["age"])
	response, err := http.Get(url)
	if err != nil {
		fmt.Printf("%s", err)
		os.Exit(1)
	}
	defer response.Body.Close()
	contents, _ := ioutil.ReadAll(response.Body)
	if len(contents) > 0 {
		lines := strings.Split(string(contents), "\n", -1)
		for _, line := range lines {
			if len(line) > 0 {
				parts := strings.Fields(line)
				if len(parts) > 9 && parts[0] == alias["release"] && parts[1] == alias["flavor"] && parts[2] == alias["age"] && parts[5] == arch && parts[4] == alias["rootstore"] && parts[6] == region && parts[9] == virt {
					return parts[7]
				}
			}
		}
	}
	return ""
}

func getAliases() []string {
	var image_aliases []string
	urls := map[int]string{0: "https://cloud-images.ubuntu.com/query/daily.latest.txt", 1: "https://cloud-images.ubuntu.com/query/released.latest.txt"}
	for _, v := range urls {
		response, err := http.Get(v)
		if err != nil {
			fmt.Printf("%s\n", err)
			os.Exit(1)
		}
		defer response.Body.Close()
		contents, _ := ioutil.ReadAll(response.Body)
		if (len(contents)) > 0 {
			lines := strings.Split(string(contents), "\n", -1)
			for _, line := range lines {
				if len(line) > 0 {
					image_aliases = append(image_aliases, line)
				}
			}
		}
	}
	return image_aliases
}


////////////////////////////////////////////////////////////////////////////////
func main() {
	// 1) Obtain the list of valid aliases
	image_aliases := getAliases()
	// 2) Search and replace valid aliases in argv with ami-* values
	for i, v := range os.Args {
		if isAlias(image_aliases, v) {
			a := parseAlias(v)
			r := getRegion(os.Args)
			t := getInstanceType(os.Args)
			ami := getAmi(r, t, a)
			if len(ami) > 0 {
				os.Args[i] = ami
			} else {
				fmt.Println("Invalid AMI Alias\n")
				os.Exit(1)
			}
		}
	}
	// 3) Execute
	//cmd := exec.Command("/bin/echo", argv[0:]...) 
	cmd := exec.Command("ec2-run-instances", os.Args[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
	}
	fmt.Println(string(r))
}
////////////////////////////////////////////////////////////////////////////////