-
Notifications
You must be signed in to change notification settings - Fork 907
/
driver_powerflex_utils.go
1179 lines (974 loc) · 34.5 KB
/
driver_powerflex_utils.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package drivers
import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/sys/unix"
"github.com/canonical/lxd/lxd/locking"
"github.com/canonical/lxd/lxd/resources"
"github.com/canonical/lxd/lxd/util"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/revert"
)
// powerFlexBlockVolSuffix suffix used for block content type volumes.
const powerFlexBlockVolSuffix = ".b"
// powerFlexISOVolSuffix suffix used for iso content type volumes.
const powerFlexISOVolSuffix = ".i"
// powerFlexCodes are returned by the API in case of error.
const powerFlexCodeVolumeNotFound = 79
const powerFlexCodeDomainNotFound = 142
const powerFlexCodeNameTooLong = 226
type powerFlexVolumeType string
type powerFlexSnapshotMode string
const powerFlexVolumeThin powerFlexVolumeType = "ThinProvisioned"
const powerFlexVolumeThick powerFlexVolumeType = "ThickProvisioned"
const powerFlexSnapshotRW powerFlexSnapshotMode = "ReadWrite"
// powerFlexVolTypePrefixes maps volume type to storage volume name prefix.
// Use smallest possible prefixes since PowerFlex volume names are limited to 31 characters.
var powerFlexVolTypePrefixes = map[VolumeType]string{
VolumeTypeContainer: "c",
VolumeTypeVM: "v",
VolumeTypeImage: "i",
VolumeTypeCustom: "u",
}
// powerFlexError contains arbitrary error responses from PowerFlex.
// The maps values can be of various types.
// Reading of the actual values is performed by specific receiver
// functions which are implemented on the type itself.
type powerFlexError map[string]any
// Error tries to return all kinds of errors from the PowerFlex API in a nicely formatted way.
func (p *powerFlexError) Error() string {
var errorStrings []string
for k, v := range *p {
errorStrings = append(errorStrings, fmt.Sprintf("%s: %v", k, v))
}
return strings.Join(errorStrings, ", ")
}
// ErrorCode extracts the errorCode value from a PowerFlex response.
func (p *powerFlexError) ErrorCode() float64 {
// In case the errorCode value is returned from the PowerFlex API,
// the respective integer value gets unmarshalled as float64.
// See https://pkg.go.dev/encoding/json#Unmarshal for JSON numbers.
code, ok := (*p)["errorCode"].(float64)
if !ok {
return 0
}
return code
}
// HTTPStatusCode extracts the httpStatusCode value from a PowerFlex response.
func (p *powerFlexError) HTTPStatusCode() float64 {
// In case the httpStatusCode value is returned from the PowerFlex API,
// the respective integer value gets unmarshalled as float64.
// See https://pkg.go.dev/encoding/json#Unmarshal for JSON numbers.
code, ok := (*p)["httpStatusCode"].(float64)
if !ok {
return 0
}
return code
}
// powerFlexStoragePool represents a storage pool in PowerFlex.
type powerFlexStoragePool struct {
ID string `json:"id"`
Name string `json:"name"`
ProtectionDomainID string `json:"protectionDomainId"`
}
// powerFlexStoragePoolStatistics represents the statistics of a storage pool in PowerFlex.
type powerFlexStoragePoolStatistics struct {
MaxCapacityInKb uint64 `json:"maxCapacityInKb"`
CapacityInUseInKb uint64 `json:"capacityInUseInKb"`
}
// powerFlexProtectionDomain represents a protection domain in PowerFlex.
type powerFlexProtectionDomain struct {
ID string `json:"id"`
Name string `json:"name"`
SystemID string `json:"systemId"`
}
// powerFlexProtectionDomainStoragePool represents a storage pool related to a protection domain in PowerFlex.
type powerFlexProtectionDomainStoragePool struct {
ID string `json:"id"`
Name string `json:"name"`
}
// powerFlexProtectionDomainSDSRelation represents an SDS related to a protection domain in PowerFlex.
type powerFlexProtectionDomainSDTRelation struct {
ID string `json:"id"`
Name string `json:"name"`
IPList []struct {
IP string `json:"ip"`
} `json:"ipList"`
}
// powerFlexSDC represents a SDC in PowerFlex.
type powerFlexSDC struct {
ID string `json:"id"`
Name string `json:"name"`
HostType string `json:"hostType"`
NQN string `json:"nqn"`
}
// powerFlexVolume represents a volume in PowerFlex.
type powerFlexVolume struct {
ID string `json:"id"`
Name string `json:"name"`
VolumeType string `json:"volumeType"`
VTreeID string `json:"vtreeId"`
AncestorVolumeID string `json:"ancestorVolumeId"`
MappedSDCInfo []struct {
SDCID string `json:"sdcId"`
SDCName string `json:"sdcName"`
NQN string `json:"nqn"`
HostType string `json:"hostType"`
} `json:"mappedSdcInfo"`
}
// powerFlexClient holds the PowerFlex HTTP client and an access token factory.
type powerFlexClient struct {
driver *powerflex
token string
}
// newPowerFlexClient creates a new instance of the HTTP PowerFlex client.
func newPowerFlexClient(driver *powerflex) *powerFlexClient {
return &powerFlexClient{
driver: driver,
}
}
// createBodyReader creates a reader for the given request body contents.
func (p *powerFlexClient) createBodyReader(contents map[string]any) (io.Reader, error) {
body := &bytes.Buffer{}
encoder := json.NewEncoder(body)
err := encoder.Encode(contents)
if err != nil {
return nil, fmt.Errorf("Failed to write request body: %w", err)
}
return body, nil
}
// request issues a HTTP request against the PowerFlex gateway.
func (p *powerFlexClient) request(method string, path string, body io.Reader, response any) error {
url := fmt.Sprintf("%s%s", p.driver.config["powerflex.gateway"], path)
req, err := http.NewRequest(method, url, body)
if err != nil {
return fmt.Errorf("Failed to create request: %w", err)
}
req.Header.Add("Accept", "application/json")
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
if p.token != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", p.token))
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: shared.IsFalse(p.driver.config["powerflex.gateway.verify"]),
},
},
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("Failed to send request: %w", err)
}
defer resp.Body.Close()
// Exit right away if not authorized.
// We cannot parse the returned body since it's not in JSON format.
if resp.StatusCode == http.StatusUnauthorized && resp.Header.Get("Content-Type") != "application/json" {
return api.StatusErrorf(http.StatusUnauthorized, "Unauthorized request")
}
// Overwrite the response data type if an error is detected.
// Both HTTP status code and PowerFlex error code get mapped to the
// custom error struct from the response body.
if resp.StatusCode != http.StatusOK {
response = &powerFlexError{}
}
if response != nil {
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(response)
if err != nil {
return fmt.Errorf("Failed to read response body: %s: %w", path, err)
}
}
// Return the formatted error from the body
powerFlexErr, ok := response.(*powerFlexError)
if ok {
return powerFlexErr
}
return nil
}
// requestAuthenticated issues an authenticated HTTP request against the PowerFlex gateway.
func (p *powerFlexClient) requestAuthenticated(method string, path string, body io.Reader, response any) error {
retries := 0
for {
err := p.login()
if err != nil {
return err
}
err = p.request(method, path, body, response)
if err != nil {
if api.StatusErrorCheck(err, http.StatusUnauthorized) && retries == 0 {
// Access token seems to be expired.
// Reset the token and try one more time.
p.token = ""
retries++
continue
}
// Non unauthorized error or retries exceeded.
return err
}
return nil
}
}
// login creates a new access token and authenticates the client.
func (p *powerFlexClient) login() error {
if p.token != "" {
return nil
}
body, err := p.createBodyReader(map[string]any{
"username": p.driver.config["powerflex.user.name"],
"password": p.driver.config["powerflex.user.password"],
})
if err != nil {
return err
}
var actualResponse struct {
AccessToken string `json:"access_token"`
}
err = p.request(http.MethodPost, "/rest/auth/login", body, &actualResponse)
if err != nil {
return fmt.Errorf("Failed to login: %w", err)
}
p.token = actualResponse.AccessToken
return nil
}
// getStoragePool returns the storage pool behind poolID.
func (p *powerFlexClient) getStoragePool(poolID string) (*powerFlexStoragePool, error) {
var actualResponse powerFlexStoragePool
err := p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/StoragePool::%s", poolID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get storage pool: %q: %w", poolID, err)
}
return &actualResponse, nil
}
// getStoragePoolStatistics returns the storage pools statistics.
func (p *powerFlexClient) getStoragePoolStatistics(poolID string) (*powerFlexStoragePoolStatistics, error) {
var actualResponse powerFlexStoragePoolStatistics
err := p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/StoragePool::%s/relationships/Statistics", poolID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get storage pool statistics: %q: %w", poolID, err)
}
return &actualResponse, nil
}
// getProtectionDomainID returns the ID of the protection domain behind domainName.
func (p *powerFlexClient) getProtectionDomainID(domainName string) (string, error) {
body, err := p.createBodyReader(map[string]any{
"name": domainName,
})
if err != nil {
return "", err
}
var actualResponse string
err = p.requestAuthenticated(http.MethodPost, "/api/types/ProtectionDomain/instances/action/queryIdByKey", body, &actualResponse)
if err != nil {
powerFlexError, ok := err.(*powerFlexError)
if ok {
// API returns 500 if the volume does not exist.
// To not confuse it with other 500 that might occur check the error code too.
if powerFlexError.HTTPStatusCode() == http.StatusInternalServerError && powerFlexError.ErrorCode() == powerFlexCodeDomainNotFound {
return "", api.StatusErrorf(http.StatusNotFound, "PowerFlex protection domain not found: %q", domainName)
}
}
return "", fmt.Errorf("Failed to get protection domain ID for %q: %w", domainName, err)
}
return actualResponse, nil
}
// getProtectionDomain returns the protection domain behind domainID.
func (p *powerFlexClient) getProtectionDomain(domainID string) (*powerFlexProtectionDomain, error) {
var actualResponse powerFlexProtectionDomain
err := p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/ProtectionDomain::%s", domainID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get protection domain: %q: %w", domainID, err)
}
return &actualResponse, nil
}
// getProtectionDomainStoragePools returns the protection domains storage pools.
func (p *powerFlexClient) getProtectionDomainStoragePools(domainID string) ([]powerFlexProtectionDomainStoragePool, error) {
var actualResponse []powerFlexProtectionDomainStoragePool
err := p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/ProtectionDomain::%s/relationships/StoragePool", domainID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get protection domain storage pools: %q: %w", domainID, err)
}
return actualResponse, nil
}
// getProtectionDomainSDTRelations returns the protection domains SDT relations.
func (p *powerFlexClient) getProtectionDomainSDTRelations(domainID string) ([]powerFlexProtectionDomainSDTRelation, error) {
var actualResponse []powerFlexProtectionDomainSDTRelation
err := p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/ProtectionDomain::%s/relationships/Sdt", domainID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get protection domain SDT relations: %q: %w", domainID, err)
}
return actualResponse, nil
}
// getVolumeID returns the volume ID for the given name.
func (p *powerFlexClient) getVolumeID(name string) (string, error) {
body, err := p.createBodyReader(map[string]any{
"name": name,
})
if err != nil {
return "", err
}
var actualResponse string
err = p.requestAuthenticated(http.MethodPost, "/api/types/Volume/instances/action/queryIdByKey", body, &actualResponse)
if err != nil {
powerFlexError, ok := err.(*powerFlexError)
if ok {
// API returns 500 if the volume does not exist.
// To not confuse it with other 500 that might occur check the error code too.
if powerFlexError.HTTPStatusCode() == http.StatusInternalServerError && powerFlexError.ErrorCode() == powerFlexCodeVolumeNotFound {
return "", api.StatusErrorf(http.StatusNotFound, "PowerFlex volume not found: %q", name)
}
}
return "", fmt.Errorf("Failed to get volume ID: %q: %w", name, err)
}
return actualResponse, nil
}
// getVolume returns the volume behind volumeID.
func (p *powerFlexClient) getVolume(volumeID string) (*powerFlexVolume, error) {
var actualResponse powerFlexVolume
err := p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/Volume::%s", volumeID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get volume: %q: %w", volumeID, err)
}
return &actualResponse, nil
}
// createVolume creates a new volume.
// The size needs to be a number in multiples of 8.
// The unit used by PowerFlex is GiB.
// The returned string represents the ID of the volume.
func (p *powerFlexClient) createVolume(volumeName string, sizeGiB int64, volumeType powerFlexVolumeType, poolID string) (string, error) {
stringSize := strconv.FormatInt(sizeGiB, 10)
body, err := p.createBodyReader(map[string]any{
"name": volumeName,
"volumeSizeInGb": stringSize,
"volumeType": volumeType,
"storagePoolId": poolID,
})
if err != nil {
return "", err
}
var actualResponse struct {
ID string `json:"id"`
}
err = p.requestAuthenticated(http.MethodPost, "/api/types/Volume/instances", body, &actualResponse)
if err != nil {
powerFlexError, ok := err.(*powerFlexError)
if ok {
// API returns 500 if the volume name is too long.
// To not confuse it with other 500 that might occur check the error code too.
if powerFlexError.HTTPStatusCode() == http.StatusInternalServerError && powerFlexError.ErrorCode() == powerFlexCodeNameTooLong {
return "", api.StatusErrorf(http.StatusNotFound, "Volume name exceeds the allowed length of 31 characters: %q", volumeName)
}
}
return "", fmt.Errorf("Failed to create volume: %q: %w", volumeName, err)
}
return actualResponse.ID, nil
}
// setVolumeSize sets the size of the volume behind volumeID to size.
// The size needs to be a number in multiples of 8.
// The unit used by PowerFlex is GiB.
func (p *powerFlexClient) setVolumeSize(volumeID string, sizeGiB int64) error {
stringSize := strconv.FormatInt(sizeGiB, 10)
body, err := p.createBodyReader(map[string]any{
"sizeInGB": stringSize,
})
if err != nil {
return err
}
err = p.requestAuthenticated(http.MethodPost, fmt.Sprintf("/api/instances/Volume::%s/action/setVolumeSize", volumeID), body, nil)
if err != nil {
return fmt.Errorf("Failed to set volume size: %q: %w", volumeID, err)
}
return nil
}
// overwriteVolume overwrites the volumes contents behind volumeID with the given snapshot.
func (p *powerFlexClient) overwriteVolume(volumeID string, snapshotID string) error {
body, err := p.createBodyReader(map[string]any{
"srcVolumeId": snapshotID,
})
if err != nil {
return err
}
err = p.requestAuthenticated(http.MethodPost, fmt.Sprintf("/api/instances/Volume::%s/action/overwriteVolumeContent", volumeID), body, nil)
if err != nil {
return fmt.Errorf("Failed to overwrite volume: %q: %w", volumeID, err)
}
return nil
}
// createVolumeSnapshot creates a new volume snapshot under the given systemID for the volume behind volumeID.
// The accessMode can be either ReadWrite or ReadOnly.
// The returned string represents the ID of the snapshot.
func (p *powerFlexClient) createVolumeSnapshot(systemID string, volumeID string, snapshotName string, accessMode powerFlexSnapshotMode) (string, error) {
body, err := p.createBodyReader(map[string]any{
"snapshotDefs": []map[string]string{
{
"volumeId": volumeID,
"snapshotName": snapshotName,
},
},
"accessModeLimit": accessMode,
})
if err != nil {
return "", err
}
var actualResponse struct {
VolumeIDs []string `json:"volumeIdList"`
}
err = p.requestAuthenticated(http.MethodPost, fmt.Sprintf("/api/instances/System::%s/action/snapshotVolumes", systemID), body, &actualResponse)
if err != nil {
powerFlexError, ok := err.(*powerFlexError)
if ok {
// API returns 500 if the snapshot name is too long.
// To not confuse it with other 500 that might occur check the error code too.
if powerFlexError.HTTPStatusCode() == http.StatusInternalServerError && powerFlexError.ErrorCode() == powerFlexCodeNameTooLong {
return "", api.StatusErrorf(http.StatusNotFound, "Snapshot name exceeds the allowed length of 31 characters: %q", snapshotName)
}
}
return "", fmt.Errorf("Failed to create volume snapshot: %q: %w", snapshotName, err)
}
if len(actualResponse.VolumeIDs) == 0 {
return "", fmt.Errorf("Response does not contain a single snapshot ID")
}
return actualResponse.VolumeIDs[0], nil
}
// getVolumeSnapshots returns the snapshots of the volume behind volumeID.
func (p *powerFlexClient) getVolumeSnapshots(volumeID string) ([]powerFlexVolume, error) {
volume, err := p.getVolume(volumeID)
if err != nil {
return nil, err
}
var actualResponse []powerFlexVolume
err = p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/VTree::%s/relationships/Volume", volume.VTreeID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get volume snapshots: %q: %w", volumeID, err)
}
var filteredVolumes []powerFlexVolume
for _, volume := range actualResponse {
if volume.AncestorVolumeID == volumeID {
filteredVolumes = append(filteredVolumes, volume)
}
}
return filteredVolumes, nil
}
// deleteVolume deletes the volume behind volumeID.
// The deleteMode can be one of ONLY_ME, INCLUDING_DESCENDANTS, DESCENDANTS_ONLY or WHOLE_VTREE.
// It describes the impact when deleting a volume from the underlying VTree. ONLY_ME deletes the
// provided volume only whereas WHOLE_VTREE also deletes the volumes parent(s) and child(s).
func (p *powerFlexClient) deleteVolume(volumeID string, deleteMode string) error {
body, err := p.createBodyReader(map[string]any{
"removeMode": deleteMode,
})
if err != nil {
return err
}
err = p.requestAuthenticated(http.MethodPost, fmt.Sprintf("/api/instances/Volume::%s/action/removeVolume", volumeID), body, nil)
if err != nil {
return fmt.Errorf("Failed to delete volume: %q: %w", volumeID, err)
}
return nil
}
// getHosts returns all hosts.
func (p *powerFlexClient) getHosts() ([]powerFlexSDC, error) {
var actualResponse []powerFlexSDC
err := p.requestAuthenticated(http.MethodGet, "/api/types/Sdc/instances", nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get hosts: %w", err)
}
return actualResponse, nil
}
// getNVMeHosts returns all NVMe hosts.
func (p *powerFlexClient) getNVMeHosts() ([]powerFlexSDC, error) {
allHosts, err := p.getHosts()
if err != nil {
return nil, err
}
var nvmeHosts []powerFlexSDC
for _, host := range allHosts {
if host.HostType == "NVMeHost" {
nvmeHosts = append(nvmeHosts, host)
}
}
return nvmeHosts, nil
}
// getNVMeHostByNQN returns the NVMe host matching the nqn.
func (p *powerFlexClient) getNVMeHostByNQN(nqn string) (*powerFlexSDC, error) {
allNVMeHosts, err := p.getNVMeHosts()
if err != nil {
return nil, err
}
for _, host := range allNVMeHosts {
if host.NQN == nqn {
return &host, nil
}
}
return nil, api.StatusErrorf(http.StatusNotFound, "Host not found using nqn: %q", nqn)
}
// createHost creates a new host.
func (p *powerFlexClient) createHost(hostName string, nqn string) (string, error) {
body, err := p.createBodyReader(map[string]any{
"name": hostName,
"nqn": nqn,
})
if err != nil {
return "", err
}
var actualResponse struct {
ID string `json:"id"`
}
err = p.requestAuthenticated(http.MethodPost, "/api/types/Host/instances", body, &actualResponse)
if err != nil {
return "", fmt.Errorf("Failed to create host: %w", err)
}
return actualResponse.ID, nil
}
// deleteHost deletes the host behind hostID.
func (p *powerFlexClient) deleteHost(hostID string) error {
err := p.requestAuthenticated(http.MethodPost, fmt.Sprintf("/api/instances/Sdc::%s/action/removeSdc", hostID), nil, nil)
if err != nil {
return fmt.Errorf("Failed to delete host: %w", err)
}
return nil
}
// createHostVolumeMapping creates the mapping between a host and volume.
func (p *powerFlexClient) createHostVolumeMapping(hostID string, volumeID string) error {
body, err := p.createBodyReader(map[string]any{
"hostId": hostID,
// This is required in live migration scenarios.
"allowMultipleMappings": "true",
})
if err != nil {
return err
}
err = p.requestAuthenticated(http.MethodPost, fmt.Sprintf("/api/instances/Volume::%s/action/addMappedHost", volumeID), body, nil)
if err != nil {
return fmt.Errorf("Failed to create host volume mapping between %q and %q: %w", hostID, volumeID, err)
}
return nil
}
// deleteHostVolumeMapping deletes the mapping between a host and volume.
func (p *powerFlexClient) deleteHostVolumeMapping(hostID string, volumeID string) error {
body, err := p.createBodyReader(map[string]any{
"hostId": hostID,
})
if err != nil {
return err
}
err = p.requestAuthenticated(http.MethodPost, fmt.Sprintf("/api/instances/Volume::%s/action/removeMappedHost", volumeID), body, nil)
if err != nil {
return fmt.Errorf("Failed to delete host volume mapping between %q and %q: %w", hostID, volumeID, err)
}
return nil
}
// getHostVolumeMappings returns the volume mappings for the host behind hostID.
func (p *powerFlexClient) getHostVolumeMappings(hostID string) ([]powerFlexVolume, error) {
var actualResponse []powerFlexVolume
err := p.requestAuthenticated(http.MethodGet, fmt.Sprintf("/api/instances/Sdc::%s/relationships/Volume", hostID), nil, &actualResponse)
if err != nil {
return nil, fmt.Errorf("Failed to get host volume mappings: %w", err)
}
return actualResponse, nil
}
// loadNVMeModules loads the NVMe/TCP kernel modules.
// Returns true if the modules can be loaded.
func (d *powerflex) loadNVMeModules() bool {
err := util.LoadModule("nvme_fabrics")
if err != nil {
return false
}
err = util.LoadModule("nvme_tcp")
return err == nil
}
// client returns the drivers PowerFlex client.
// A new client gets created if it not yet exists.
func (d *powerflex) client() *powerFlexClient {
if d.httpClient == nil {
d.httpClient = newPowerFlexClient(d)
}
return d.httpClient
}
// getHostNQN returns the unique NVMe nqn for the current host.
// A custom one is generated from the servers UUID since getting the nqn from /etc/nvme/hostnqn
// requires the nvme-cli package to be installed on the host.
func (d *powerflex) getHostNQN() string {
return fmt.Sprintf("nqn.2014-08.org.nvmexpress:uuid:%s", d.state.ServerUUID)
}
// getServerName returns the hostname of this host.
// It prefers the value from the daemons state in case LXD is clustered.
func (d *powerflex) getServerName() (string, error) {
if d.state.ServerName != "none" {
return d.state.ServerName, nil
}
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("Failed to get hostname: %w", err)
}
return hostname, nil
}
// getVolumeType returns the selected provisioning type of the volume.
// As a default it returns type thin.
func (d *powerflex) getVolumeType(vol Volume) powerFlexVolumeType {
var volumeType string
if vol.config["block.type"] != "" {
volumeType = vol.config["block.type"]
}
if volumeType == "thick" {
return powerFlexVolumeThick
}
return powerFlexVolumeThin
}
// createNVMeHost creates this NVMe host in PowerFlex.
// The operation is idempotent and locked using lock name powerflex.host.
func (d *powerflex) createNVMeHost() (string, error) {
unlock, err := locking.Lock(d.state.ShutdownCtx, "powerflex.host")
if err != nil {
return "", err
}
defer unlock()
var hostID string
nqn := d.getHostNQN()
client := d.client()
host, err := client.getNVMeHostByNQN(nqn)
if err != nil {
if !api.StatusErrorCheck(err, http.StatusNotFound) {
return "", err
}
hostname, err := d.getServerName()
if err != nil {
return "", err
}
hostID, err = client.createHost(hostname, nqn)
if err != nil {
return "", err
}
}
if hostID == "" {
hostID = host.ID
}
return hostID, nil
}
// deleteNVMeHost deletes this NVMe host in PowerFlex.
// The operation is idempotent and locked using lock name powerflex.host.
func (d *powerflex) deleteNVMeHost() error {
unlock, err := locking.Lock(d.state.ShutdownCtx, "powerflex.host")
if err != nil {
return err
}
defer unlock()
client := d.client()
nqn := d.getHostNQN()
host, err := client.getNVMeHostByNQN(nqn)
if err != nil {
// Skip the deletion if the host doesn't exist anymore.
if api.StatusErrorCheck(err, http.StatusNotFound) {
return nil
}
return err
}
return client.deleteHost(host.ID)
}
// mapNVMeVolume maps the given volume onto this host.
func (d *powerflex) mapNVMeVolume(volumeName string) (revert.Hook, error) {
revert := revert.New()
defer revert.Fail()
hostID, err := d.createNVMeHost()
if err != nil {
return nil, err
}
client := d.client()
volumeID, err := client.getVolumeID(volumeName)
if err != nil {
return nil, err
}
volume, err := client.getVolume(volumeID)
if err != nil {
return nil, err
}
mapped := false
for _, mapping := range volume.MappedSDCInfo {
if mapping.SDCID == hostID {
mapped = true
}
}
if !mapped {
err = client.createHostVolumeMapping(hostID, volumeID)
if err != nil {
return nil, err
}
revert.Add(func() { _ = client.deleteHostVolumeMapping(hostID, volumeID) })
}
cleanup := revert.Clone().Fail
revert.Success()
return cleanup, nil
}
// getNVMeMappedDevPath returns the local device path for the given NVMe volume name.
// Set mapVolume to true if the volume isn't already mapped to this host.
func (d *powerflex) getNVMeMappedDevPath(volumeName string, mapVolume bool) (string, revert.Hook, error) {
revert := revert.New()
defer revert.Fail()
if mapVolume {
cleanup, err := d.mapNVMeVolume(volumeName)
if err != nil {
return "", nil, err
}
revert.Add(cleanup)
// Connect to the NVMe/TCP subsystem.
// We have to connect after the first mapping was established.
// PowerFlex does not offer any discovery log entries until a volume gets mapped to the host.
// This action is idempotent.
err = d.connectNVMeSubsys()
if err != nil {
return "", nil, err
}
}
powerFlexVolumes := make(map[string]string)
// discoverFunc has to be called in a loop with a set timeout to ensure
// all the necessary directories and devices can be discovered.
discoverFunc := func(volumeID string) error {
var diskPaths []string
// If there are no other disks on the system by id, the directory might not even be there.
// Returns ENOENT in case the by-id/ directory does not exist.
diskPaths, err := resources.GetDisksByID(fmt.Sprintf("nvme-eui.%s", volumeID))
if err != nil {
return err
}
for _, diskPath := range diskPaths {
// Skip the disk if it is only a partition of the actual PowerFlex volume.
if strings.Contains(diskPath, "-part") {
continue
}
// The actual /dev/nvmeX might not already be created.
// Returns ENOENT in case the nvmeX device does not exist.
devPath, err := filepath.EvalSymlinks(diskPath)
if err != nil {
return err
}
powerFlexVolumes[volumeID] = devPath
}
return nil
}
powerFlexVolumeID, err := d.client().getVolumeID(volumeName)
if err != nil {
return "", nil, err
}
timeout := time.Now().Add(5 * time.Second)
// It might take the NVMe/TCP subsystem a while to create the local disk.
// Retry until it can be found.
for {
if time.Now().After(timeout) {
return "", nil, fmt.Errorf("Timeout exceeded for NVMe volume discovery: %q", volumeName)
}
err := discoverFunc(powerFlexVolumeID)
if err != nil {
// Try again if on of the directories cannot be found.
if errors.Is(err, unix.ENOENT) {
continue
}
return "", nil, err
}
// Exit if the volume got discovered.
_, ok := powerFlexVolumes[powerFlexVolumeID]
if ok {
break
}
// Exit if the volume wasn't explicitly mapped.
// Doing a retry would run into the timeout when the device isn't mapped.
if !mapVolume {
break
}
time.Sleep(10 * time.Millisecond)
}
if len(powerFlexVolumes) == 0 {
return "", nil, fmt.Errorf("Failed to discover any NVMe volume")
}
powerFlexVolumePath, ok := powerFlexVolumes[powerFlexVolumeID]
if !ok {
return "", nil, fmt.Errorf("Volume not found: %q", volumeName)
}
cleanup := revert.Clone().Fail
revert.Success()
return powerFlexVolumePath, cleanup, nil
}
// getMappedDevPath returns the local device path for the given volume name.
func (d *powerflex) getMappedDevPath(vol Volume, mapVolume bool) (string, revert.Hook, error) {
if d.config["powerflex.mode"] == "nvme" {
volName, err := d.getVolumeName(vol)
if err != nil {
return "", nil, err
}
return d.getNVMeMappedDevPath(volName, mapVolume)
}
return "", nil, ErrNotSupported
}
// unmapNVMeVolume unmaps the given NVMe volume from this host.
func (d *powerflex) unmapNVMeVolume(volumeName string) error {
client := d.client()
volume, err := client.getVolumeID(volumeName)
if err != nil {
return err
}
nqn := d.getHostNQN()
host, err := client.getNVMeHostByNQN(nqn)
if err != nil {
return err
}