This repository has been archived by the owner on May 8, 2021. It is now read-only.
/
main.go
278 lines (237 loc) · 8.44 KB
/
main.go
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// The MIT License (MIT)
// Copyright (c) 2016 Christian Parpart <trapni@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/gorilla/mux"
flag "github.com/ogier/pflag"
)
const appVersion = "0.1.0"
var (
errUserOrPasswordEmpty = errors.New("Username or password empty.")
)
type awsFund struct {
httpPort int
awsImageID string
awsAccessKeyID string
awsSecretAccessKey string
awsSecurityGroupName string
awsKeyName string
awsInstanceType string
awsRegion string
svc *ec2.EC2
}
func (fund *awsFund) initialize() {
if fund.awsAccessKeyID != "" {
os.Setenv("AWS_ACCESS_KEY_ID", fund.awsAccessKeyID)
}
if fund.awsSecretAccessKey != "" {
os.Setenv("AWS_SECRET_ACCESS_KEY", fund.awsSecretAccessKey)
}
fund.svc = ec2.New(session.New(), &aws.Config{Region: aws.String(fund.awsRegion)})
}
func (fund *awsFund) Run() {
fund.initialize()
// setting up HTTP router
router := mux.NewRouter()
router.HandleFunc("/ping", fund.v0Ping)
router.HandleFunc("/version", fund.v0Version)
v1 := router.PathPrefix("/v1").Subrouter()
v1.HandleFunc("/instances", fund.v1Instances).Methods("GET")
v1.HandleFunc("/instances/create", fund.v1CreateInstance).Methods("POST")
// start listening and serving on incoming HTTP requests
httpAddr := fmt.Sprintf("%v:%v", "0.0.0.0", fund.httpPort)
log.Printf("Listening for backend API requests on http://%v", httpAddr)
err := http.ListenAndServe(httpAddr, router)
if err != nil {
panic(err)
}
}
// ===========================================================================
// AWS helpers
func (fund *awsFund) awsCreateInstance(username, password string) (*ec2.Reservation, error) {
if username == "" || password == "" {
return nil, errUserOrPasswordEmpty
}
// create new local user and whitelist that user for SSH password auth
//
// XXX it would be better to use a customized AMI image instead of hacking
// into the sshd_config here.
// XXX we may want to add him to the sudoers group here, so he can root.
// But this is discouraged. Use the passwd key-pair for that instead.
awsUserData := fmt.Sprintf("#! /bin/bash\n"+
"set -ex\n"+
"useradd -m %v\n"+
"echo %v:%v | chpasswd\n"+
"echo \"Match User %v\" >> /etc/ssh/sshd_config\n"+
"echo \" PasswordAuthentication yes\" >> /etc/ssh/sshd_config\n"+
"restart ssh\n",
username, username, password, username)
// base64-encode
awsUserData = base64.StdEncoding.EncodeToString([]byte(awsUserData))
params := &ec2.RunInstancesInput{
ImageId: aws.String(fund.awsImageID),
MaxCount: aws.Int64(1),
MinCount: aws.Int64(1),
KeyName: aws.String(fund.awsKeyName),
UserData: aws.String(awsUserData),
InstanceType: aws.String(fund.awsInstanceType),
InstanceInitiatedShutdownBehavior: aws.String("terminate"),
SecurityGroupIds: []*string{
aws.String(fund.awsSecurityGroupName),
},
Monitoring: &ec2.RunInstancesMonitoringEnabled{
Enabled: aws.Bool(true),
},
}
// XXX usually it's not a wise choice to log passwords
log.Printf("Creating instance with username %q and password %q.\n", username, password)
reservation, err := fund.svc.RunInstances(params)
if err != nil {
return nil, err
}
return reservation, nil
}
func (fund *awsFund) awsInstanceByID(id *string) (*ec2.Instance, error) {
input := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("instance-id"),
Values: []*string{id},
},
},
}
resp, err := fund.svc.DescribeInstances(input)
if err != nil {
return nil, err
}
return resp.Reservations[0].Instances[0], nil
}
func (fund *awsFund) awsWaitForInstanceToRun(id *string) error {
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("instance-id"),
Values: []*string{id},
},
},
}
log.Printf("Waiting for instance to run: %v\n", *id)
return fund.svc.WaitUntilInstanceRunning(params)
}
// ===========================================================================
// HTTP API
func (fund *awsFund) v0Ping(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "pong\n")
}
func (fund *awsFund) v0Version(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "awsfund %v\n", appVersion)
}
func (fund *awsFund) v1Instances(w http.ResponseWriter, r *http.Request) {
input := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("instance-state-name"),
Values: []*string{
aws.String("running"),
aws.String("terminated"),
aws.String("pending"),
},
},
},
}
resp, err := fund.svc.DescribeInstances(input)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s\n", err)
return
}
w.Header().Set("content-type", "text/csv")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "reservation-id instance-id instance-state key-name, public-ip")
for _, res := range resp.Reservations {
for _, inst := range res.Instances {
fmt.Fprint(w, *res.ReservationId)
fmt.Fprint(w, " ", *inst.InstanceId)
fmt.Fprint(w, " ", *inst.State.Name)
fmt.Fprint(w, " ", *inst.KeyName)
if inst.PublicIpAddress != nil {
fmt.Fprint(w, " ", *inst.PublicIpAddress)
} else {
fmt.Fprint(w, " -")
}
fmt.Fprintln(w)
}
}
}
func (fund *awsFund) v1CreateInstance(w http.ResponseWriter, r *http.Request) {
username := r.URL.Query().Get("username")
password := r.URL.Query().Get("password")
reservation, err := fund.awsCreateInstance(username, password)
if err != nil {
if err == errUserOrPasswordEmpty {
w.WriteHeader(http.StatusBadRequest)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
fmt.Fprintf(w, "%v\n", err)
return
}
fund.awsWaitForInstanceToRun(reservation.Instances[0].InstanceId)
i, err := fund.awsInstanceByID(reservation.Instances[0].InstanceId)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%v\n", err)
return
}
// provide some additional information as HTTP response headers (easy to
// parse in client APIs)
w.Header().Add("public-ip", *i.PublicIpAddress)
w.Header().Add("public-dns", *i.PublicDnsName)
w.Header().Add("instance-id", *i.InstanceId)
// set HTTP status code to: 201 (Created)
w.WriteHeader(http.StatusCreated)
// also provide public IP address via HTTP response body
fmt.Fprintf(w, "%v\n", *i.PublicIpAddress)
}
// ===========================================================================
// entrypoint
func main() {
fund := awsFund{}
flag.StringVar(&fund.awsAccessKeyID, "aws-access-key-id", "", "AWS access key ID")
flag.StringVar(&fund.awsImageID, "aws-image-id", "ami-26c43149", "AWS AMI image ID")
flag.StringVar(&fund.awsSecretAccessKey, "aws-secret-access-key", "", "AWS secret access key")
flag.StringVar(&fund.awsSecurityGroupName, "aws-sg-name", "default", "AWS security group")
flag.StringVar(&fund.awsKeyName, "aws-key-name", "", "AWS key name")
flag.StringVar(&fund.awsInstanceType, "aws-instance-type", "t2.micro", "AWS instance type")
flag.StringVar(&fund.awsRegion, "aws-region", "eu-central-1", "")
flag.IntVar(&fund.httpPort, "http-port", 8080, "HTTP port to accept backend API requests from")
flag.Parse()
fund.Run()
}