forked from yadutaf/docker-machine-driver-ovh
/
driver.go
437 lines (372 loc) · 10.4 KB
/
driver.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"strings"
"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"
)
const (
statusTimeout = 200
)
// Driver is a machine driver for OVH.
type Driver struct {
*drivers.BaseDriver
// Command line parameters
ProjectName string
FlavorName string
RegionName string
// Internal ids
ProjectID string
FlavorID string
ImageID string
InstanceID string
KeyPairName string
KeyPairID string
// Overloaded credentials
ApplicationKey string
ApplicationSecret string
ConsumerKey string
// internal
client *API
}
// GetCreateFlags registers the "machine create" flags recognized by this driver, including
// their help text and defaults.
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.StringFlag{
EnvVar: "OVH_APPLICATION_KEY",
Name: "ovh-application-key",
Usage: "OVH API application key. May be stored in ovh.conf",
Value: "",
},
mcnflag.StringFlag{
EnvVar: "OVH_APPLICATION_SECRET",
Name: "ovh-application-secret",
Usage: "OVH API application secret. May be stored in ovh.conf",
Value: "",
},
mcnflag.StringFlag{
EnvVar: "OVH_APPLICATION_KEY",
Name: "ovh-consumer-key",
Usage: "OVH API consumer key. May be stored in ovh.conf",
Value: "",
},
mcnflag.StringFlag{
Name: "ovh-project",
Usage: "OVH Cloud project name or id",
Value: "",
},
mcnflag.StringFlag{
Name: "ovh-region",
Usage: "OVH Cloud region name",
Value: DefaultRegionName,
},
mcnflag.StringFlag{
Name: "ovh-flavor",
Usage: "OVH Cloud flavor name or id. Default: vps-ssd-1",
Value: DefaultFlavorName,
},
mcnflag.StringFlag{
Name: "ovh-ssh-key",
Usage: "OVH Cloud ssh key name or id to use. Default: generate a random name",
Value: "",
},
}
}
// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
return "ovh"
}
// getClient returns an OVH API client
func (d *Driver) getClient() (api *API) {
if d.client == nil {
client, err := NewAPI("ovh-eu", d.ApplicationKey, d.ApplicationSecret, d.ConsumerKey)
if err != nil {
return nil
}
d.client = client
}
return d.client
}
// SetConfigFromFlags assigns and verifies the command-line arguments presented to the driver.
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
d.ApplicationKey = flags.String("ovh-application-key")
d.ApplicationSecret = flags.String("ovh-application-secret")
d.ConsumerKey = flags.String("ovh-consumer-key")
// Store configuration parameters as-is
d.ProjectName = flags.String("ovh-project")
d.RegionName = flags.String("ovh-region")
d.FlavorName = flags.String("ovh-flavor")
d.KeyPairName = flags.String("ovh-ssh-key")
// Swarm configuration, must be in each driver
d.SwarmMaster = flags.Bool("swarm-master")
d.SwarmHost = flags.String("swarm-host")
d.SwarmDiscovery = flags.String("swarm-discovery")
d.SSHUser = "admin"
return nil
}
// PreCreateCheck does the network side validation
func (d *Driver) PreCreateCheck() error {
client := d.getClient()
// Validate project id
log.Debug("Validating project")
if d.ProjectName != "" {
project, err := client.GetProjectByName(d.ProjectName)
if err != nil {
return err
}
d.ProjectID = project.Id
} else {
projects, err := client.GetProjects()
if err != nil {
return err
}
// If there is only one project, take it
if len(projects) == 1 {
d.ProjectID = projects[0]
} else if len(projects) == 0 {
return fmt.Errorf("No Cloud project could be found. To create a new one, please visit %s", CustomerInterface)
} else {
return fmt.Errorf("Multiple Cloud project found, to select one, use '--ovh-project' option")
}
}
log.Debug("Found project id ", d.ProjectID)
// Validate region
log.Debug("Validating region")
regions, err := client.GetRegions(d.ProjectID)
if err != nil {
return err
}
var ok bool
for _, region := range regions {
if region == d.RegionName {
ok = true
break
}
}
if ok != true {
return fmt.Errorf("Invalid region %s. For a list of valid ovh regions, please visis %s", d.RegionName, CustomerInterface)
}
// Validate flavor
log.Debug("Validating flavor")
flavor, err := client.GetFlavorByName(d.ProjectID, d.RegionName, d.FlavorName)
if err != nil {
return err
}
d.FlavorID = flavor.Id
log.Debug("Found flavor id ", d.FlavorID)
// Validate image
log.Debug("Validating image")
image, err := client.GetImageByName(d.ProjectID, d.RegionName, ImageName)
if err != nil {
return err
}
d.ImageID = image.Id
log.Debug("Found image id ", d.ImageID)
// Use a common key or create a machine specific one
if len(d.KeyPairName) != 0 {
d.SSHKeyPath = filepath.Join(d.StorePath, "sshkeys", d.KeyPairName)
} else {
d.KeyPairName = fmt.Sprintf("%s-%s", d.MachineName, mcnutils.GenerateRandomID())
}
return nil
}
// ensureSSHKey makes sure an SSH key for the machine exists with requested name
func (d *Driver) ensureSSHKey() error {
client := d.getClient()
// Attempt to get an existing key
log.WithField("Name", d.KeyPairName).Debug("Checking Key Pair...")
sshKey, _ := client.GetSshkeyByName(d.ProjectID, d.RegionName, d.KeyPairName)
if sshKey != nil {
d.KeyPairID = sshKey.Id
log.Debug("Found key id ", d.KeyPairID)
return nil
}
// Generate key and parent dir if needed
log.WithField("Name", d.KeyPairName).Debug("Creating Key Pair...")
keyfile := d.GetSSHKeyPath()
keypath := filepath.Dir(keyfile)
err := os.MkdirAll(keypath, 0700)
if err != nil {
return err
}
err = ssh.GenerateSSHKey(d.GetSSHKeyPath())
if err != nil {
return err
}
publicKey, err := ioutil.ReadFile(d.publicSSHKeyPath())
if err != nil {
return err
}
// Upload key
sshKey, err = client.CreateSshkey(d.ProjectID, d.KeyPairName, string(publicKey))
if err != nil {
return err
}
d.KeyPairID = sshKey.Id
log.Debug("Created key id ", d.KeyPairID)
return nil
}
// waitForInstanceStatus waits until instance reaches status. Copied from openstack Driver
func (d *Driver) waitForInstanceStatus(status string) (instance *Instance, err error) {
return instance, mcnutils.WaitForSpecificOrError(func() (bool, error) {
instance, err = d.client.GetInstance(d.ProjectID, d.InstanceID)
if err != nil {
return true, err
}
log.WithField("MachineId", d.InstanceID).Debugf("Machine state: %s", instance.Status)
if instance.Status == "ERROR" {
return true, fmt.Errorf("Instance creation failed. Instance is in ERROR state")
}
if instance.Status == status {
return true, nil
}
return false, nil
}, (statusTimeout / 4), 4*time.Second)
}
// GetSSHHostname returns the hostname for SSH
func (d *Driver) GetSSHHostname() (string, error) {
return d.IPAddress, nil
}
// Create a new docker machine instance on OVH Cloud
func (d *Driver) Create() error {
client := d.getClient()
// Ensure ssh key
err := d.ensureSSHKey()
if err != nil {
return err
}
// Create instance
log.Debug("Creating OVH instance...")
instance, err := client.CreateInstance(
d.ProjectID,
d.MachineName,
d.KeyPairID,
d.FlavorID,
d.ImageID,
d.RegionName,
false,
)
if err != nil {
return err
}
d.InstanceID = instance.Id
// Wait until instance is ACTIVE
log.WithField("MachineId", d.InstanceID).Debug("Waiting for OVH instance...")
instance, err = d.waitForInstanceStatus("ACTIVE")
if err != nil {
return err
}
// Save Ip address
d.IPAddress = ""
for _, ip := range instance.IpAddresses {
if ip.Type == "public" {
d.IPAddress = ip.Ip
break
}
}
if d.IPAddress == "" {
return fmt.Errorf("No IP found for instance %s", instance.Id)
}
log.WithFields(log.Fields{
"IP": d.IPAddress,
"MachineId": d.InstanceID,
}).Debug("IP address found")
// All done !
return nil
}
func (d *Driver) publicSSHKeyPath() string {
return d.GetSSHKeyPath() + ".pub"
}
// GetState return instance status
func (d *Driver) GetState() (state.State, error) {
log.WithField("MachineId", d.InstanceID).Debug("Get status for OVH instance...")
client := d.getClient()
instance, err := client.GetInstance(d.ProjectID, d.InstanceID)
if err != nil {
return state.None, err
}
log.WithFields(log.Fields{
"MachineId": d.InstanceID,
"State": instance.Status,
}).Debug("State for OVH instance")
switch instance.Status {
case "ACTIVE":
return state.Running, nil
case "PAUSED":
return state.Paused, nil
case "SUSPENDED":
return state.Saved, nil
case "SHUTOFF":
return state.Stopped, nil
case "BUILDING":
return state.Starting, nil
case "ERROR":
return state.Error, nil
}
return state.None, nil
}
// GetURL returns docker daemon URL on this machine
func (d *Driver) GetURL() (string, error) {
if d.IPAddress == "" {
return "", nil
}
return fmt.Sprintf("tcp://%s", net.JoinHostPort(d.IPAddress, "2376")), nil
}
// Remove deletes a machine and it's SSH keys from OVH Cloud
func (d *Driver) Remove() error {
log.WithField("MachineId", d.InstanceID).Debug("deleting instance...")
log.Info("Deleting OVH instance...")
client := d.getClient()
// Deletes instance
err := client.DeleteInstance(d.ProjectID, d.InstanceID)
if err != nil {
return err
}
// If key name does not starts with the machine ID, this is a pre-existing key, keep it
if !strings.HasPrefix(d.KeyPairName, d.MachineName) {
log.WithField("KeyPairID", d.KeyPairID).Debug("keeping key pair...")
return nil
}
// Deletes ssh key
log.WithField("KeyPairID", d.KeyPairID).Debug("deleting key pair...")
err = client.DeleteSshkey(d.ProjectID, d.KeyPairID)
if err != nil {
return err
}
return nil
}
// Restart this docker-machine
func (d *Driver) Restart() error {
log.WithField("MachineId", d.InstanceID).Info("Restarting OVH instance...")
client := d.getClient()
err := client.RebootInstance(d.ProjectID, d.InstanceID, false)
if err != nil {
return err
}
return nil
}
//
// STUBS
//
// Kill (STUB) kill machine
func (d *Driver) Kill() (err error) {
return fmt.Errorf("Killing machines is not possible on OVH Cloud")
}
// Start (STUB) start machine
func (d *Driver) Start() (err error) {
return fmt.Errorf("Starting machines is not possible on OVH Cloud")
}
// Stop (STUB) stop machine
func (d *Driver) Stop() (err error) {
return fmt.Errorf("Stopping machines is not possible on OVH Cloud")
}