/
cinder.go
475 lines (431 loc) · 13.8 KB
/
cinder.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package openstack
import (
"math"
"net/url"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/utils"
"gopkg.in/goose.v1/cinder"
"gopkg.in/goose.v1/identity"
"gopkg.in/goose.v1/nova"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/instance"
"github.com/juju/juju/storage"
)
const (
CinderProviderType = storage.ProviderType("cinder")
// autoAssignedMountPoint specifies the value to pass in when
// you'd like Cinder to automatically assign a mount point.
autoAssignedMountPoint = ""
volumeStatusAvailable = "available"
volumeStatusDeleting = "deleting"
volumeStatusError = "error"
volumeStatusInUse = "in-use"
)
type cinderProvider struct {
newStorageAdapter func(*config.Config) (openstackStorage, error)
}
var _ storage.Provider = (*cinderProvider)(nil)
var cinderAttempt = utils.AttemptStrategy{
Total: 1 * time.Minute,
Delay: 5 * time.Second,
}
// VolumeSource implements storage.Provider.
func (p *cinderProvider) VolumeSource(environConfig *config.Config, providerConfig *storage.Config) (storage.VolumeSource, error) {
if err := p.ValidateConfig(providerConfig); err != nil {
return nil, err
}
storageAdapter, err := p.newStorageAdapter(environConfig)
if err != nil {
return nil, err
}
source := &cinderVolumeSource{
storageAdapter: storageAdapter,
envName: environConfig.Name(),
modelUUID: environConfig.UUID(),
}
return source, nil
}
// FilesystemSource implements storage.Provider.
func (p *cinderProvider) FilesystemSource(environConfig *config.Config, providerConfig *storage.Config) (storage.FilesystemSource, error) {
return nil, errors.NotSupportedf("filesystems")
}
// Supports implements storage.Provider.
func (p *cinderProvider) Supports(kind storage.StorageKind) bool {
switch kind {
case storage.StorageKindBlock:
return true
}
return false
}
// Scope implements storage.Provider.
func (s *cinderProvider) Scope() storage.Scope {
return storage.ScopeEnviron
}
// ValidateConfig implements storage.Provider.
func (p *cinderProvider) ValidateConfig(cfg *storage.Config) error {
// TODO(axw) 2015-05-01 #1450737
// Reject attempts to create non-persistent volumes.
return nil
}
// Dynamic implements storage.Provider.
func (p *cinderProvider) Dynamic() bool {
return true
}
type cinderVolumeSource struct {
storageAdapter openstackStorage
envName string // non unique, informational only
modelUUID string
}
var _ storage.VolumeSource = (*cinderVolumeSource)(nil)
// CreateVolumes implements storage.VolumeSource.
func (s *cinderVolumeSource) CreateVolumes(args []storage.VolumeParams) ([]storage.CreateVolumesResult, error) {
results := make([]storage.CreateVolumesResult, len(args))
for i, arg := range args {
volume, err := s.createVolume(arg)
if err != nil {
results[i].Error = errors.Trace(err)
continue
}
results[i].Volume = volume
}
return results, nil
}
func (s *cinderVolumeSource) createVolume(arg storage.VolumeParams) (*storage.Volume, error) {
var metadata interface{}
if len(arg.ResourceTags) > 0 {
metadata = arg.ResourceTags
}
cinderVolume, err := s.storageAdapter.CreateVolume(cinder.CreateVolumeVolumeParams{
// The Cinder documentation incorrectly states the
// size parameter is in GB. It is actually GiB.
Size: int(math.Ceil(float64(arg.Size / 1024))),
Name: resourceName(arg.Tag, s.envName),
// TODO(axw) use the AZ of the initially attached machine.
AvailabilityZone: "",
Metadata: metadata,
})
if err != nil {
return nil, errors.Trace(err)
}
// The response may (will?) come back before the volume transitions to
// "creating", in which case it will not have a size or status. Wait for
// the volume to transition, so we can record its actual size.
volumeId := cinderVolume.ID
cinderVolume, err = s.waitVolume(volumeId, func(v *cinder.Volume) (bool, error) {
return v.Status != "", nil
})
if err != nil {
if err := s.storageAdapter.DeleteVolume(volumeId); err != nil {
logger.Warningf("destroying volume %s: %s", volumeId, err)
}
return nil, errors.Errorf("waiting for volume to be provisioned: %s", err)
}
logger.Debugf("created volume: %+v", cinderVolume)
return &storage.Volume{arg.Tag, cinderToJujuVolumeInfo(cinderVolume)}, nil
}
// ListVolumes is specified on the storage.VolumeSource interface.
func (s *cinderVolumeSource) ListVolumes() ([]string, error) {
cinderVolumes, err := s.storageAdapter.GetVolumesDetail()
if err != nil {
return nil, err
}
volumeIds := make([]string, 0, len(cinderVolumes))
for _, volume := range cinderVolumes {
modelUUID, ok := volume.Metadata[tags.JujuModel]
if !ok || modelUUID != s.modelUUID {
continue
}
volumeIds = append(volumeIds, cinderToJujuVolumeInfo(&volume).VolumeId)
}
return volumeIds, nil
}
// DescribeVolumes implements storage.VolumeSource.
func (s *cinderVolumeSource) DescribeVolumes(volumeIds []string) ([]storage.DescribeVolumesResult, error) {
// In most cases, it is quicker to get all volumes and loop
// locally than to make several round-trips to the provider.
cinderVolumes, err := s.storageAdapter.GetVolumesDetail()
if err != nil {
return nil, errors.Trace(err)
}
volumesById := make(map[string]*cinder.Volume)
for i, volume := range cinderVolumes {
volumesById[volume.ID] = &cinderVolumes[i]
}
results := make([]storage.DescribeVolumesResult, len(volumeIds))
for i, volumeId := range volumeIds {
cinderVolume, ok := volumesById[volumeId]
if !ok {
results[i].Error = errors.NotFoundf("volume %q", volumeId)
continue
}
info := cinderToJujuVolumeInfo(cinderVolume)
results[i].VolumeInfo = &info
}
return results, nil
}
// DestroyVolumes implements storage.VolumeSource.
func (s *cinderVolumeSource) DestroyVolumes(volumeIds []string) ([]error, error) {
var wg sync.WaitGroup
wg.Add(len(volumeIds))
results := make([]error, len(volumeIds))
for i, volumeId := range volumeIds {
go func(i int, volumeId string) {
defer wg.Done()
results[i] = s.destroyVolume(volumeId)
}(i, volumeId)
}
wg.Wait()
return results, nil
}
func (s *cinderVolumeSource) destroyVolume(volumeId string) error {
logger.Debugf("destroying volume %q", volumeId)
// Volumes must not be in-use when destroying. A volume may
// still be in-use when the instance it is attached to is
// in the process of being terminated.
var issuedDetach bool
volume, err := s.waitVolume(volumeId, func(v *cinder.Volume) (bool, error) {
switch v.Status {
default:
// Not ready for deletion; keep waiting.
return false, nil
case volumeStatusAvailable, volumeStatusDeleting, volumeStatusError:
return true, nil
case volumeStatusInUse:
// Detach below.
break
}
// Volume is still attached, so detach it.
if !issuedDetach {
args := make([]storage.VolumeAttachmentParams, len(v.Attachments))
for i, a := range v.Attachments {
args[i].VolumeId = volumeId
args[i].InstanceId = instance.Id(a.ServerId)
}
if len(args) > 0 {
results, err := s.DetachVolumes(args)
if err != nil {
return false, errors.Trace(err)
}
for _, err := range results {
if err != nil {
return false, errors.Trace(err)
}
}
}
issuedDetach = true
}
return false, nil
})
if err != nil {
return errors.Trace(err)
}
if volume.Status == volumeStatusDeleting {
// Already being deleted, nothing to do.
return nil
}
if err := s.storageAdapter.DeleteVolume(volumeId); err != nil {
return errors.Trace(err)
}
return nil
}
// ValidateVolumeParams implements storage.VolumeSource.
func (s *cinderVolumeSource) ValidateVolumeParams(params storage.VolumeParams) error {
return nil
}
// AttachVolumes implements storage.VolumeSource.
func (s *cinderVolumeSource) AttachVolumes(args []storage.VolumeAttachmentParams) ([]storage.AttachVolumesResult, error) {
results := make([]storage.AttachVolumesResult, len(args))
for i, arg := range args {
attachment, err := s.attachVolume(arg)
if err != nil {
results[i].Error = errors.Trace(err)
continue
}
results[i].VolumeAttachment = attachment
}
return results, nil
}
func (s *cinderVolumeSource) attachVolume(arg storage.VolumeAttachmentParams) (*storage.VolumeAttachment, error) {
// Check to see if the volume is already attached.
existingAttachments, err := s.storageAdapter.ListVolumeAttachments(string(arg.InstanceId))
if err != nil {
return nil, err
}
novaAttachment := findAttachment(arg.VolumeId, existingAttachments)
if novaAttachment == nil {
// A volume must be "available" before it can be attached.
if _, err := s.waitVolume(arg.VolumeId, func(v *cinder.Volume) (bool, error) {
return v.Status == "available", nil
}); err != nil {
return nil, errors.Annotate(err, "waiting for volume to become available")
}
novaAttachment, err = s.storageAdapter.AttachVolume(
string(arg.InstanceId),
arg.VolumeId,
autoAssignedMountPoint,
)
if err != nil {
return nil, err
}
}
return &storage.VolumeAttachment{
arg.Volume,
arg.Machine,
storage.VolumeAttachmentInfo{
DeviceName: novaAttachment.Device[len("/dev/"):],
},
}, nil
}
func (s *cinderVolumeSource) waitVolume(
volumeId string,
pred func(*cinder.Volume) (bool, error),
) (*cinder.Volume, error) {
for a := cinderAttempt.Start(); a.Next(); {
volume, err := s.storageAdapter.GetVolume(volumeId)
if err != nil {
return nil, errors.Annotate(err, "getting volume")
}
ok, err := pred(volume)
if err != nil {
return nil, errors.Trace(err)
}
if ok {
return volume, nil
}
}
return nil, errors.New("timed out")
}
// DetachVolumes implements storage.VolumeSource.
func (s *cinderVolumeSource) DetachVolumes(args []storage.VolumeAttachmentParams) ([]error, error) {
results := make([]error, len(args))
for i, arg := range args {
// Check to see if the volume is already detached.
attachments, err := s.storageAdapter.ListVolumeAttachments(string(arg.InstanceId))
if err != nil {
results[i] = errors.Annotate(err, "listing volume attachments")
continue
}
if err := detachVolume(
string(arg.InstanceId),
arg.VolumeId,
attachments,
s.storageAdapter,
); err != nil {
results[i] = errors.Annotatef(
err, "detaching volume %s from server %s",
arg.VolumeId, arg.InstanceId,
)
continue
}
}
return results, nil
}
func cinderToJujuVolumeInfo(volume *cinder.Volume) storage.VolumeInfo {
return storage.VolumeInfo{
VolumeId: volume.ID,
Size: uint64(volume.Size * 1024),
Persistent: true,
}
}
func detachVolume(instanceId, volumeId string, attachments []nova.VolumeAttachment, storageAdapter openstackStorage) error {
// TODO(axw) verify whether we need to do this find step. From looking at the example
// responses in the OpenStack docs, the "attachment ID" is always the same as the
// volume ID. So we should just be able to issue a blind detach request, and then
// ignore errors that indicate the volume is already detached.
if findAttachment(volumeId, attachments) == nil {
return nil
}
return storageAdapter.DetachVolume(instanceId, volumeId)
}
func findAttachment(volId string, attachments []nova.VolumeAttachment) *nova.VolumeAttachment {
for _, attachment := range attachments {
if attachment.VolumeId == volId {
return &attachment
}
}
return nil
}
type openstackStorage interface {
GetVolume(volumeId string) (*cinder.Volume, error)
GetVolumesDetail() ([]cinder.Volume, error)
DeleteVolume(volumeId string) error
CreateVolume(cinder.CreateVolumeVolumeParams) (*cinder.Volume, error)
AttachVolume(serverId, volumeId, mountPoint string) (*nova.VolumeAttachment, error)
DetachVolume(serverId, attachmentId string) error
ListVolumeAttachments(serverId string) ([]nova.VolumeAttachment, error)
}
type endpointResolver interface {
EndpointsForRegion(region string) identity.ServiceURLs
}
func getVolumeEndpointURL(client endpointResolver, region string) (*url.URL, error) {
endpointMap := client.EndpointsForRegion(region)
// The cinder openstack charm appends 'v2' to the type for the v2 api.
endpoint, ok := endpointMap["volumev2"]
if !ok {
logger.Debugf(`endpoint "volumev2" not found for %q region, trying "volume"`, region)
endpoint, ok = endpointMap["volume"]
if !ok {
return nil, errors.Errorf(`endpoint "volume" not found for %q region`, region)
}
}
return url.Parse(endpoint)
}
func newOpenstackStorageAdapter(environConfig *config.Config) (openstackStorage, error) {
ecfg, err := providerInstance.newConfig(environConfig)
if err != nil {
return nil, errors.Trace(err)
}
client, err := authClient(ecfg)
if err != nil {
return nil, errors.Trace(err)
} else if err := client.Authenticate(); err != nil {
return nil, errors.Trace(err)
}
endpointUrl, err := getVolumeEndpointURL(client, ecfg.region())
if err != nil {
return nil, errors.Annotate(err, "getting volume endpoint")
}
return &openstackStorageAdapter{
cinderClient{cinder.Basic(endpointUrl, client.TenantId(), client.Token)},
novaClient{nova.New(client)},
}, nil
}
type openstackStorageAdapter struct {
cinderClient
novaClient
}
type cinderClient struct {
*cinder.Client
}
type novaClient struct {
*nova.Client
}
// CreateVolume is part of the openstackStorage interface.
func (ga *openstackStorageAdapter) CreateVolume(args cinder.CreateVolumeVolumeParams) (*cinder.Volume, error) {
resp, err := ga.cinderClient.CreateVolume(args)
if err != nil {
return nil, err
}
return &resp.Volume, nil
}
// GetVolumesDetail is part of the openstackStorage interface.
func (ga *openstackStorageAdapter) GetVolumesDetail() ([]cinder.Volume, error) {
resp, err := ga.cinderClient.GetVolumesDetail()
if err != nil {
return nil, err
}
return resp.Volumes, nil
}
// GetVolume is part of the openstackStorage interface.
func (ga *openstackStorageAdapter) GetVolume(volumeId string) (*cinder.Volume, error) {
resp, err := ga.cinderClient.GetVolume(volumeId)
if err != nil {
return nil, err
}
return &resp.Volume, nil
}