forked from taoh/docker-machine-linode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linode.go
419 lines (361 loc) · 9.58 KB
/
linode.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package linode
import (
"errors"
"fmt"
"io/ioutil"
"time"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/ssh"
"github.com/docker/machine/libmachine/state"
"github.com/taoh/linodego"
)
// Driver is the implementation of BaseDriver interface
type Driver struct {
*drivers.BaseDriver
client *linodego.Client
APIKey string
IPAddress string
DockerPort int
LinodeId int
LinodeLabel string
DataCenterId int
PlanId int
PaymentTerm int
RootPassword string
SSHPort int
DistributionId int
KernelId int
}
// NewDriver
func NewDriver(hostName, storePath string) *Driver {
return &Driver{
BaseDriver: &drivers.BaseDriver{
MachineName: hostName,
StorePath: storePath,
},
}
}
// Get Linode Client
func (d *Driver) getClient() *linodego.Client {
if d.client == nil {
d.client = linodego.NewClient(d.APIKey, nil)
}
return d.client
}
func (d *Driver) DriverName() string {
return "linode"
}
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
// Get IP Address for the Linode. Note that currently the IP Address
// is cached
func (d *Driver) GetIP() (string, error) {
if d.IPAddress == "" {
return "", fmt.Errorf("IP address is not set")
}
return d.IPAddress, nil
}
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.StringFlag{
Name: "linode-api-key",
Usage: "Linode API Key",
Value: "",
EnvVar: "LINODE_API_KEY",
},
mcnflag.StringFlag{
EnvVar: "LINODE_ROOT_PASSWORD",
Name: "linode-root-pass",
Usage: "Root password",
},
mcnflag.StringFlag{
EnvVar: "LINODE_LABEL",
Name: "linode-label",
Usage: "Linode label",
},
mcnflag.IntFlag{
EnvVar: "LINODE_DATACENTER_ID",
Name: "linode-datacenter-id",
Usage: "Linode Data Center Id",
Value: 2,
},
mcnflag.IntFlag{
EnvVar: "LINODE_PLAN_ID",
Name: "linode-plan-id",
Usage: "Linode plan id",
Value: 1,
},
mcnflag.IntFlag{
EnvVar: "LINODE_PAYMENT_TERM",
Name: "linode-payment-term",
Usage: "Linode Payment term",
Value: 1, // valid values: 1, 12, 24
},
mcnflag.IntFlag{
EnvVar: "LINODE_SSH_PORT",
Name: "linode-ssh-port",
Usage: "Linode SSH Port",
Value: 22,
},
mcnflag.IntFlag{
EnvVar: "LINODE_DISTRIBUTION_ID",
Name: "linode-distribution-id",
Usage: "Linode Distribution Id",
Value: 140, // Debian 8 (Ubuntu 16.04 LTD = 146)
},
mcnflag.IntFlag{
EnvVar: "LINODE_KERNEL_ID",
Name: "linode-kernel-id",
Usage: "Linode Kernel Id",
Value: 210, // default kernel, GRUB 2,
},
mcnflag.IntFlag{
EnvVar: "LINODE_DOCKER_PORT",
Name: "linode-docker-port",
Usage: "Docker Port",
Value: 2376,
},
}
}
func (d *Driver) GetSSHUsername() string {
if d.SSHUser == "" {
d.SSHUser = "root"
}
return d.SSHUser
}
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
d.APIKey = flags.String("linode-api-key")
d.DataCenterId = flags.Int("linode-datacenter-id")
d.PlanId = flags.Int("linode-plan-id")
d.PaymentTerm = flags.Int("linode-payment-term")
d.RootPassword = flags.String("linode-root-pass")
d.SSHPort = flags.Int("linode-ssh-port")
d.DistributionId = flags.Int("linode-distribution-id")
d.KernelId = flags.Int("linode-kernel-id")
d.LinodeLabel = flags.String("linode-label")
d.DockerPort = flags.Int("linode-docker-port")
if d.APIKey == "" {
return fmt.Errorf("linode driver requires the --linode-api-key option")
}
if d.RootPassword == "" {
return fmt.Errorf("linode driver requires the --linode-root-pass option")
}
return nil
}
func (d *Driver) PreCreateCheck() error {
return nil
}
func (d *Driver) Create() error {
log.Debug("Creating Linode machine instance...")
publicKey, err := d.createSSHKey()
if err != nil {
return err
}
client := d.getClient()
// Create a linode
log.Debug("Creating linode instance")
linodeResponse, err := client.Linode.Create(
d.DataCenterId,
d.PlanId,
d.PaymentTerm,
)
if err != nil {
return err
}
d.LinodeId = linodeResponse.LinodeId.LinodeId
log.Debugf("Linode created: %d", d.LinodeId)
if d.LinodeLabel != "" {
log.Debugf("Updating linode label to %s", d.LinodeLabel)
_, err := client.Linode.Update(d.LinodeId, map[string]interface{}{"Label": d.LinodeLabel})
if err != nil {
return err
}
}
linodeIPListResponse, err := client.Ip.List(d.LinodeId, -1)
if err != nil {
return err
}
for _, fullIpAddress := range linodeIPListResponse.FullIPAddresses {
if fullIpAddress.IsPublic == 1 {
d.IPAddress = fullIpAddress.IPAddress
}
}
if d.IPAddress == "" {
return errors.New("Linode IP Address is not found.")
}
log.Debugf("Created linode ID %d, IP address %s",
d.LinodeId,
d.IPAddress)
// Deploy distribution
args := make(map[string]string)
args["rootPass"] = d.RootPassword
args["rootSSHKey"] = publicKey
distributionId := d.DistributionId
log.Debug("Create disk")
createDiskJobResponse, err := d.client.Disk.CreateFromDistribution(distributionId, d.LinodeId, "Primary Disk", 24576-256, args)
if err != nil {
return err
}
jobId := createDiskJobResponse.DiskJob.JobId
diskId := createDiskJobResponse.DiskJob.DiskId
log.Debugf("Linode create disk task :%d.", jobId)
// wait until the creation is finished
err = d.waitForJob(jobId, "Create Disk Task", 60)
if err != nil {
return err
}
// create swap
log.Debug("Create swap disk")
createDiskJobResponse, err = d.client.Disk.Create(d.LinodeId, "swap", "Swap Disk", 256, nil)
if err != nil {
return err
}
jobId = createDiskJobResponse.DiskJob.JobId
swapDiskId := createDiskJobResponse.DiskJob.DiskId
log.Debugf("Linode create swap disk task :%d.", jobId)
// wait until the creation is finished
err = d.waitForJob(jobId, "Create Swap Disk Task", 60)
if err != nil {
return err
}
// create config
log.Debug("Create configuration")
args2 := make(map[string]string)
args2["DiskList"] = fmt.Sprintf("%d,%d", diskId, swapDiskId)
args2["RootDeviceNum"] = "1"
args2["RootDeviceRO"] = "true"
args2["helper_distro"] = "true"
kernelId := d.KernelId
_, err = d.client.Config.Create(d.LinodeId, kernelId, "My Docker Machine Configuration", args2)
if err != nil {
return err
}
log.Debugf("Linode configuration created.")
// Boot
log.Debug("Booting")
jobResponse, err := d.client.Linode.Boot(d.LinodeId, -1)
if err != nil {
return err
}
jobId = jobResponse.JobId.JobId
log.Debugf("Booting linode, job id: %v", jobId)
// wait for boot
err = d.waitForJob(jobId, "Booting linode", 60)
if err != nil {
return err
}
log.Debug("Waiting for Machine Running...")
if err := mcnutils.WaitForSpecific(drivers.MachineInState(d, state.Running), 120, 3*time.Second); err != nil {
return fmt.Errorf("wait for machine running failed: %s", err)
}
return nil
}
func (d *Driver) GetURL() (string, error) {
ip, err := d.GetIP()
if err != nil {
return "", err
}
if ip == "" {
return "", nil
}
return fmt.Sprintf("tcp://%s:%d", ip, d.DockerPort), nil
}
func (d *Driver) GetState() (state.State, error) {
linodes, err := d.getClient().Linode.List(d.LinodeId)
if err != nil {
return state.Error, err
}
// Status flag values:
// -2: Boot Failed
// -1: Being Created
// 0: Brand New
// 1: Running
// 2: Powered Off
// 3: Shutting Down
// 4: Saved to Disk
//
switch linodes.Linodes[0].Status {
case -1, 0:
return state.Starting, nil
case 1:
return state.Running, nil
case -2, 2, 4:
return state.Stopped, nil
case 3:
return state.Stopping, nil
}
return state.None, nil
}
func (d *Driver) Start() error {
log.Debug("Start...")
_, err := d.getClient().Linode.Boot(d.LinodeId, -1)
return err
}
func (d *Driver) Stop() error {
log.Debug("Stop...")
_, err := d.getClient().Linode.Shutdown(d.LinodeId)
return err
}
func (d *Driver) Remove() error {
client := d.getClient()
log.Debugf("Removing linode: %d", d.LinodeId)
if _, err := client.Linode.Delete(d.LinodeId, true); err != nil {
return err
}
return nil
}
func (d *Driver) Restart() error {
log.Debug("Restarting...")
_, err := d.getClient().Linode.Reboot(d.LinodeId, -1)
return err
}
func (d *Driver) Kill() error {
log.Debug("Killing...")
_, err := d.getClient().Linode.Shutdown(d.LinodeId)
return err
}
func (d *Driver) createSSHKey() (string, error) {
if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
return "", err
}
publicKey, err := ioutil.ReadFile(d.publicSSHKeyPath())
if err != nil {
return "", err
}
return string(publicKey), nil
}
// waitForJob checks job status every 1 second until timeout
func (d *Driver) waitForJob(jobId int, jobName string, timeOutSeconds int) error {
log.Debugf("Wait for job %s completion...", jobName)
timeout := time.After(time.Duration(timeOutSeconds) * time.Second)
tick := time.Tick(1000 * time.Millisecond)
for {
select {
case <-timeout:
return fmt.Errorf("Job %s timed out after %d seconds.", jobName, timeOutSeconds)
case <-tick:
{
clientJobResponse, err := d.getClient().Job.List(d.LinodeId, jobId, false)
if err != nil {
return err
}
if len(clientJobResponse.Jobs) < 0 || clientJobResponse.Jobs[0].JobId != jobId {
return fmt.Errorf("Job %s is not found.", jobName)
}
if clientJobResponse.Jobs[0].HostSuccess.String() == "1" {
log.Debugf("Linode job %s completed.", jobName)
return nil
}
// if not success, wait for next check
}
}
}
}
// publicSSHKeyPath is always SSH Key Path appended with ".pub"
func (d *Driver) publicSSHKeyPath() string {
return d.GetSSHKeyPath() + ".pub"
}