forked from docker/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
digitalocean.go
360 lines (313 loc) · 8.43 KB
/
digitalocean.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
package digitalocean
import (
"fmt"
"io/ioutil"
"net"
"os"
"time"
"github.com/digitalocean/godo"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/ssh"
"github.com/docker/machine/libmachine/state"
"golang.org/x/oauth2"
)
type Driver struct {
*drivers.BaseDriver
AccessToken string
DropletID int
DropletName string
Image string
Region string
SSHKeyID int
SSHKeyFingerprint string
Size string
IPv6 bool
Backups bool
PrivateNetworking bool
UserDataFile string
}
const (
defaultSSHPort = 22
defaultSSHUser = "root"
defaultImage = "ubuntu-15-10-x64"
defaultRegion = "nyc3"
defaultSize = "512mb"
)
// GetCreateFlags registers the flags this driver adds to
// "docker hosts create"
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.StringFlag{
EnvVar: "DIGITALOCEAN_ACCESS_TOKEN",
Name: "digitalocean-access-token",
Usage: "Digital Ocean access token",
},
mcnflag.StringFlag{
EnvVar: "DIGITALOCEAN_SSH_USER",
Name: "digitalocean-ssh-user",
Usage: "SSH username",
Value: defaultSSHUser,
},
mcnflag.StringFlag{
EnvVar: "DIGITALOCEAN_SSH_KEY_FINGERPRINT",
Name: "digitalocean-ssh-key-fingerprint",
Usage: "SSH key fingerprint",
},
mcnflag.IntFlag{
EnvVar: "DIGITALOCEAN_SSH_PORT",
Name: "digitalocean-ssh-port",
Usage: "SSH port",
Value: defaultSSHPort,
},
mcnflag.StringFlag{
EnvVar: "DIGITALOCEAN_IMAGE",
Name: "digitalocean-image",
Usage: "Digital Ocean Image",
Value: defaultImage,
},
mcnflag.StringFlag{
EnvVar: "DIGITALOCEAN_REGION",
Name: "digitalocean-region",
Usage: "Digital Ocean region",
Value: defaultRegion,
},
mcnflag.StringFlag{
EnvVar: "DIGITALOCEAN_SIZE",
Name: "digitalocean-size",
Usage: "Digital Ocean size",
Value: defaultSize,
},
mcnflag.BoolFlag{
EnvVar: "DIGITALOCEAN_IPV6",
Name: "digitalocean-ipv6",
Usage: "enable ipv6 for droplet",
},
mcnflag.BoolFlag{
EnvVar: "DIGITALOCEAN_PRIVATE_NETWORKING",
Name: "digitalocean-private-networking",
Usage: "enable private networking for droplet",
},
mcnflag.BoolFlag{
EnvVar: "DIGITALOCEAN_BACKUPS",
Name: "digitalocean-backups",
Usage: "enable backups for droplet",
},
mcnflag.StringFlag{
EnvVar: "DIGITALOCEAN_USERDATA",
Name: "digitalocean-userdata",
Usage: "path to file with cloud-init user-data",
},
}
}
func NewDriver(hostName, storePath string) *Driver {
return &Driver{
Image: defaultImage,
Size: defaultSize,
Region: defaultRegion,
BaseDriver: &drivers.BaseDriver{
MachineName: hostName,
StorePath: storePath,
},
}
}
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
return "digitalocean"
}
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
d.AccessToken = flags.String("digitalocean-access-token")
d.Image = flags.String("digitalocean-image")
d.Region = flags.String("digitalocean-region")
d.Size = flags.String("digitalocean-size")
d.IPv6 = flags.Bool("digitalocean-ipv6")
d.PrivateNetworking = flags.Bool("digitalocean-private-networking")
d.Backups = flags.Bool("digitalocean-backups")
d.UserDataFile = flags.String("digitalocean-userdata")
d.SSHUser = flags.String("digitalocean-ssh-user")
d.SSHPort = flags.Int("digitalocean-ssh-port")
d.SSHKeyFingerprint = flags.String("digitalocean-ssh-key-fingerprint")
d.SetSwarmConfigFromFlags(flags)
if d.AccessToken == "" {
return fmt.Errorf("digitalocean driver requires the --digitalocean-access-token option")
}
return nil
}
func (d *Driver) PreCreateCheck() error {
if d.UserDataFile != "" {
if _, err := os.Stat(d.UserDataFile); os.IsNotExist(err) {
return fmt.Errorf("user-data file %s could not be found", d.UserDataFile)
}
}
client := d.getClient()
regions, _, err := client.Regions.List(nil)
if err != nil {
return err
}
for _, region := range regions {
if region.Slug == d.Region {
return nil
}
}
return fmt.Errorf("digitalocean requires a valid region")
}
func (d *Driver) Create() error {
var userdata string
if d.UserDataFile != "" {
buf, err := ioutil.ReadFile(d.UserDataFile)
if err != nil {
return err
}
userdata = string(buf)
}
log.Infof("Creating SSH key...")
key, err := d.createSSHKey()
if err != nil {
return err
}
d.SSHKeyID = key.ID
log.Infof("Creating Digital Ocean droplet...")
client := d.getClient()
createRequest := &godo.DropletCreateRequest{
Image: godo.DropletCreateImage{Slug: d.Image},
Name: d.MachineName,
Region: d.Region,
Size: d.Size,
IPv6: d.IPv6,
PrivateNetworking: d.PrivateNetworking,
Backups: d.Backups,
UserData: userdata,
SSHKeys: []godo.DropletCreateSSHKey{{ID: d.SSHKeyID}},
}
newDroplet, _, err := client.Droplets.Create(createRequest)
if err != nil {
return err
}
d.DropletID = newDroplet.ID
log.Info("Waiting for IP address to be assigned to the Droplet...")
for {
newDroplet, _, err = client.Droplets.Get(d.DropletID)
if err != nil {
return err
}
for _, network := range newDroplet.Networks.V4 {
if network.Type == "public" {
d.IPAddress = network.IPAddress
}
}
if d.IPAddress != "" {
break
}
time.Sleep(1 * time.Second)
}
log.Debugf("Created droplet ID %d, IP address %s",
newDroplet.ID,
d.IPAddress)
return nil
}
func (d *Driver) createSSHKey() (*godo.Key, error) {
if d.SSHKeyFingerprint != "" {
key, resp, err := d.getClient().Keys.GetByFingerprint(d.SSHKeyFingerprint)
if err != nil && resp.StatusCode == 404 {
return nil, fmt.Errorf("Digital Ocean SSH key with fingerprint %s doesn't exist", d.SSHKeyFingerprint)
}
return key, err
}
if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
return nil, err
}
publicKey, err := ioutil.ReadFile(d.publicSSHKeyPath())
if err != nil {
return nil, err
}
createRequest := &godo.KeyCreateRequest{
Name: d.MachineName,
PublicKey: string(publicKey),
}
key, _, err := d.getClient().Keys.Create(createRequest)
if err != nil {
return key, err
}
return key, nil
}
func (d *Driver) GetURL() (string, error) {
if err := drivers.MustBeRunning(d); err != nil {
return "", err
}
ip, err := d.GetIP()
if err != nil {
return "", err
}
return fmt.Sprintf("tcp://%s", net.JoinHostPort(ip, "2376")), nil
}
func (d *Driver) GetState() (state.State, error) {
droplet, _, err := d.getClient().Droplets.Get(d.DropletID)
if err != nil {
return state.Error, err
}
switch droplet.Status {
case "new":
return state.Starting, nil
case "active":
return state.Running, nil
case "off":
return state.Stopped, nil
}
return state.None, nil
}
func (d *Driver) Start() error {
_, _, err := d.getClient().DropletActions.PowerOn(d.DropletID)
return err
}
func (d *Driver) Stop() error {
_, _, err := d.getClient().DropletActions.Shutdown(d.DropletID)
return err
}
func (d *Driver) Restart() error {
_, _, err := d.getClient().DropletActions.Reboot(d.DropletID)
return err
}
func (d *Driver) Kill() error {
_, _, err := d.getClient().DropletActions.PowerOff(d.DropletID)
return err
}
func (d *Driver) Remove() error {
client := d.getClient()
if d.SSHKeyFingerprint == "" {
if resp, err := client.Keys.DeleteByID(d.SSHKeyID); err != nil {
if resp.StatusCode == 404 {
log.Infof("Digital Ocean SSH key doesn't exist, assuming it is already deleted")
} else {
return err
}
}
}
if resp, err := client.Droplets.Delete(d.DropletID); err != nil {
if resp.StatusCode == 404 {
log.Infof("Digital Ocean droplet doesn't exist, assuming it is already deleted")
} else {
return err
}
}
return nil
}
func (d *Driver) getClient() *godo.Client {
token := &oauth2.Token{AccessToken: d.AccessToken}
tokenSource := oauth2.StaticTokenSource(token)
client := oauth2.NewClient(oauth2.NoContext, tokenSource)
return godo.NewClient(client)
}
func (d *Driver) GetSSHKeyPath() string {
// don't set SSHKeyPath when using an existing key fingerprint
if d.SSHKeyPath == "" && d.SSHKeyFingerprint == "" {
d.SSHKeyPath = d.ResolveStorePath("id_rsa")
}
return d.SSHKeyPath
}
func (d *Driver) publicSSHKeyPath() string {
return d.GetSSHKeyPath() + ".pub"
}