forked from play-with-docker/play-with-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
windows.go
320 lines (272 loc) · 8.95 KB
/
windows.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package provisioner
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"sort"
"golang.org/x/net/websocket"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/play-with-docker/play-with-docker/docker"
"github.com/play-with-docker/play-with-docker/pwd/types"
"github.com/play-with-docker/play-with-docker/router"
"github.com/play-with-docker/play-with-docker/storage"
)
var asgService *autoscaling.AutoScaling
var ec2Service *ec2.EC2
func init() {
// Create a session to share configuration, and load external configuration.
sess := session.Must(session.NewSession())
//
// // Create the service's client with the session.
asgService = autoscaling.New(sess)
ec2Service = ec2.New(sess)
}
type windows struct {
factory docker.FactoryApi
storage storage.StorageApi
}
type instanceInfo struct {
publicIP string
privateIP string
id string
}
func NewWindowsASG(f docker.FactoryApi, st storage.StorageApi) *windows {
return &windows{factory: f, storage: st}
}
func (d *windows) InstanceNew(session *types.Session, conf types.InstanceConfig) (*types.Instance, error) {
winfo, err := d.getWindowsInstanceInfo(session.Id)
if err != nil {
return nil, err
}
labels := map[string]string{
"io.tutorius.networkid": session.Id,
"io.tutorius.networking.remote.ip": winfo.privateIP,
}
instanceName := fmt.Sprintf("%s_%s", session.Id[:8], winfo.id)
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
d.releaseInstance(winfo.id)
return nil, err
}
if err = dockerClient.ConfigCreate(instanceName, labels, []byte(instanceName)); err != nil {
d.releaseInstance(winfo.id)
return nil, err
}
instance := &types.Instance{}
instance.Name = instanceName
instance.Image = ""
instance.IP = winfo.privateIP
instance.RoutableIP = instance.IP
instance.SessionId = session.Id
instance.WindowsId = winfo.id
instance.Cert = conf.Cert
instance.Key = conf.Key
instance.Type = conf.Type
instance.ServerCert = conf.ServerCert
instance.ServerKey = conf.ServerKey
instance.CACert = conf.CACert
instance.Tls = conf.Tls
instance.ProxyHost = router.EncodeHost(session.Id, instance.RoutableIP, router.HostOpts{})
instance.SessionHost = session.Host
return instance, nil
}
func (d *windows) InstanceDelete(session *types.Session, instance *types.Instance) error {
dockerClient, err := d.factory.GetForSession(session)
if err != nil {
return err
}
_, err = asgService.DetachInstances(&autoscaling.DetachInstancesInput{
AutoScalingGroupName: aws.String("pwd-windows"),
InstanceIds: []*string{aws.String(instance.WindowsId)},
ShouldDecrementDesiredCapacity: aws.Bool(false),
})
if err != nil {
return err
}
//return error and don't do anything else
if _, err := ec2Service.TerminateInstances(&ec2.TerminateInstancesInput{InstanceIds: []*string{aws.String(instance.WindowsId)}}); err != nil {
return err
}
err = dockerClient.ConfigDelete(instance.Name)
if err != nil {
return err
}
return d.releaseInstance(instance.WindowsId)
}
type execRes struct {
ExitCode int `json:"exit_code"`
Error string `json:"error"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
}
func (d *windows) InstanceExec(instance *types.Instance, cmd []string) (int, error) {
execBody := struct {
Cmd []string `json:"cmd"`
}{Cmd: cmd}
b, err := json.Marshal(execBody)
if err != nil {
return -1, err
}
resp, err := http.Post(fmt.Sprintf("http://%s:222/exec", instance.IP), "application/json", bytes.NewReader(b))
if err != nil {
log.Println(err)
return -1, err
}
if resp.StatusCode != 200 {
log.Printf("Error exec on instance %s. Got %d\n", instance.Name, resp.StatusCode)
return -1, fmt.Errorf("Error exec on instance %s. Got %d\n", instance.Name, resp.StatusCode)
}
var ex execRes
err = json.NewDecoder(resp.Body).Decode(&ex)
if err != nil {
return -1, err
}
return ex.ExitCode, nil
}
func (d *windows) InstanceFSTree(instance *types.Instance) (io.Reader, error) {
//TODO implement
return nil, nil
}
func (d *windows) InstanceFile(instance *types.Instance, filePath string) (io.Reader, error) {
//TODO implement
return nil, nil
}
func (d *windows) releaseInstance(instanceId string) error {
return d.storage.WindowsInstanceDelete(instanceId)
}
func (d *windows) InstanceResizeTerminal(instance *types.Instance, rows, cols uint) error {
resp, err := http.Post(fmt.Sprintf("http://%s:222/terminals/1/size?cols=%d&rows=%d", instance.IP, cols, rows), "application/json", nil)
if err != nil {
log.Println(err)
return err
}
if resp.StatusCode != 200 {
log.Printf("Error resizing terminal of instance %s. Got %d\n", instance.Name, resp.StatusCode)
return fmt.Errorf("Error resizing terminal got %d\n", resp.StatusCode)
}
return nil
}
func (d *windows) InstanceGetTerminal(instance *types.Instance) (net.Conn, error) {
resp, err := http.Post(fmt.Sprintf("http://%s:222/terminals/1", instance.IP), "application/json", nil)
if err != nil {
log.Printf("Error creating terminal for instance %s. Got %v\n", instance.Name, err)
return nil, err
}
if resp.StatusCode != 200 {
log.Printf("Error creating terminal for instance %s. Got %d\n", instance.Name, resp.StatusCode)
return nil, fmt.Errorf("Creating terminal got %d\n", resp.StatusCode)
}
url := fmt.Sprintf("ws://%s:222/terminals/1", instance.IP)
ws, err := websocket.Dial(url, "", url)
if err != nil {
log.Println(err)
return nil, err
}
return ws, nil
}
func (d *windows) InstanceUploadFromUrl(instance *types.Instance, fileName, dest, u string) error {
log.Printf("Downloading file [%s]\n", u)
resp, err := http.Get(u)
if err != nil {
return fmt.Errorf("Could not download file [%s]. Error: %s\n", u, err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("Could not download file [%s]. Status code: %d\n", u, resp.StatusCode)
}
uploadResp, err := http.Post(fmt.Sprintf("http://%s:222/terminals/1/uploads?dest=%s&file_name=%s", instance.IP, url.QueryEscape(dest), url.QueryEscape(fileName)), "", resp.Body)
if err != nil {
return err
}
if uploadResp.StatusCode != 200 {
return fmt.Errorf("Could not upload file [%s]. Status code: %d\n", fileName, uploadResp.StatusCode)
}
return nil
}
func (d *windows) InstanceUploadFromReader(instance *types.Instance, fileName, dest string, reader io.Reader) error {
uploadResp, err := http.Post(fmt.Sprintf("http://%s:222/terminals/1/uploads?dest=%s&file_name=%s", instance.IP, url.QueryEscape(dest), url.QueryEscape(fileName)), "", reader)
if err != nil {
return err
}
if uploadResp.StatusCode != 200 {
return fmt.Errorf("Could not upload file [%s]. Status code: %d\n", fileName, uploadResp.StatusCode)
}
return nil
}
func (d *windows) getWindowsInstanceInfo(sessionId string) (*instanceInfo, error) {
input := &autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{aws.String("pwd-windows")},
}
out, err := asgService.DescribeAutoScalingGroups(input)
if err != nil {
return nil, err
}
// there should always be one asg
instances := out.AutoScalingGroups[0].Instances
availInstances := make([]string, len(instances))
// reverse order so older instances are first served
sort.Sort(sort.Reverse(sort.StringSlice(availInstances)))
for i, inst := range instances {
if *inst.LifecycleState == "InService" {
availInstances[i] = *inst.InstanceId
}
}
assignedInstances, err := d.storage.WindowsInstanceGetAll()
assignedInstancesIds := []string{}
for _, ai := range assignedInstances {
assignedInstancesIds = append(assignedInstancesIds, ai.Id)
}
if err != nil {
return nil, err
}
avInstanceId := d.pickFreeInstance(sessionId, availInstances, assignedInstancesIds)
if len(avInstanceId) == 0 {
return nil, OutOfCapacityError
}
iout, err := ec2Service.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(avInstanceId)},
})
if err != nil {
// TODO retry x times and free the instance that was picked?
d.releaseInstance(avInstanceId)
return nil, err
}
instance := iout.Reservations[0].Instances[0]
instanceInfo := &instanceInfo{
publicIP: *instance.PublicIpAddress,
privateIP: *instance.PrivateIpAddress,
id: avInstanceId,
}
//TODO check for free instance, ASG capacity and return
return instanceInfo, nil
}
// select free instance and lock it into db.
// additionally check if ASG needs to be resized
func (d *windows) pickFreeInstance(sessionId string, availInstances, assignedInstances []string) string {
for _, av := range availInstances {
found := false
for _, as := range assignedInstances {
if av == as {
found = true
break
}
}
if !found {
err := d.storage.WindowsInstancePut(&types.WindowsInstance{SessionId: sessionId, Id: av})
if err != nil {
// TODO either storage error or instance is already assigned (race condition)
}
return av
}
}
// all availalbe instances are assigned
return ""
}