forked from kahing/goofys
/
backend_adlv2.go
1786 lines (1604 loc) · 62.6 KB
/
backend_adlv2.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
// Copyright 2019 Databricks
// Copyright (c) Microsoft and contributors for generated code from azure-sdk-for-go
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package internal
import (
. "github.com/kahing/goofys/api/common"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"github.com/google/uuid"
"github.com/jacobsa/fuse"
"github.com/sirupsen/logrus"
adl2 "github.com/Azure/azure-sdk-for-go/services/storage/datalake/2018-11-09/storagedatalake"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
)
type ADLv2 struct {
cap Capabilities
flags *FlagStorage
config *ADLv2Config
client adl2PathClient
bucket string
}
const ADL2_CLIENT_REQUEST_ID = "X-Ms-Client-Request-Id"
const ADL2_REQUEST_ID = "X-Ms-Request-Id"
var adl2Log = GetLogger("adlv2")
type ADLv2MultipartBlobCommitInput struct {
Size uint64
ContentType string
RenewLeaseStop chan bool
}
func IsADLv2Endpoint(endpoint string) bool {
return strings.HasPrefix(endpoint, "abfs://")
}
func adl2LogResp(level logrus.Level, r *http.Response) {
if r == nil {
return
}
if adl2Log.IsLevelEnabled(level) {
requestId := r.Request.Header.Get(ADL2_CLIENT_REQUEST_ID)
respId := r.Header.Get(ADL2_REQUEST_ID)
// don't log anything if this is being called twice,
// which it is via ResponseInspector
if respId != "" {
adl2Log.Logf(level, "%v %v %v %v %v", r.Request.Method,
r.Request.URL.String(),
requestId, r.Status, respId)
r.Header.Del(ADL2_REQUEST_ID)
}
}
}
func NewADLv2(bucket string, flags *FlagStorage, config *ADLv2Config) (*ADLv2, error) {
u, err := url.Parse(config.Endpoint)
if err != nil {
return nil, err
}
parts := strings.SplitN(u.Hostname(), ".", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("Invalid endpoint: %v", config.Endpoint)
}
storageAccountName := parts[0]
dnsSuffix := parts[1]
LogRequest := func(p autorest.Preparer) autorest.Preparer {
return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) {
r.URL.Scheme = u.Scheme
date := time.Now().Format(time.RFC1123)
date = strings.Replace(date, "UTC", "GMT", 1)
r.Header.Set("X-Ms-Date", date)
r.Header.Set("X-Ms-Version", "2018-11-09")
r.Header.Set(ADL2_CLIENT_REQUEST_ID, uuid.New().String())
r.Header.Set("Accept-Charset", "utf-8")
r.Header.Set("Content-Type", "")
r.Header.Set("Accept", "application/json, application/octet-stream")
// set transfer encoding and non-nil Body to
// ensure Content-Length: 0 is sent, seems
// like an idiotic golang behavior:
// https://github.com/golang/go/issues/20257
// azure server side rejects the request if
// Content-Length is missing
r.TransferEncoding = []string{"identity"}
if r.Header.Get("Content-Length") == "0" {
r.Body = http.NoBody
} else if r.Body == nil {
r.Body = http.NoBody
}
if adl2Log.IsLevelEnabled(logrus.DebugLevel) {
requestId := r.Header.Get(ADL2_CLIENT_REQUEST_ID)
op := r.Method
switch op {
case http.MethodPost:
// this is a lease
leaseAction := r.Header.Get("X-Ms-Lease-Action")
leaseId := r.Header.Get("X-Ms-Lease-Id")
proposeLeaseId := r.Header.Get("X-Ms-Proposed-Lease-Id")
op += fmt.Sprintf(" %v (%v, %v)",
leaseAction, leaseId, proposeLeaseId)
case http.MethodPatch:
action := r.URL.Query().Get("action")
op += " " + action
if action == "append" {
op += fmt.Sprintf("(%v)", r.ContentLength)
}
}
adl2Log.Debugf("%v %v %v", op,
r.URL.String(), requestId)
}
r, err := p.Prepare(r)
if err != nil {
adl2Log.Error(err)
}
return r, err
})
}
LogResponse := func(p autorest.Responder) autorest.Responder {
return autorest.ResponderFunc(func(r *http.Response) error {
adl2LogResp(logrus.DebugLevel, r)
err := p.Respond(r)
if err != nil {
adl2Log.Error(err)
}
return err
})
}
client := adl2.NewWithoutDefaults("", storageAccountName, dnsSuffix)
client.Authorizer = config.Authorizer
client.RequestInspector = LogRequest
client.ResponseInspector = LogResponse
client.Sender.(*http.Client).Transport = GetHTTPTransport()
b := &ADLv2{
flags: flags,
config: config,
client: adl2PathClient{client},
bucket: bucket,
cap: Capabilities{
DirBlob: true,
Name: "adl2",
// tested on 2019-11-07, seems to have same
// limit as azblob
MaxMultipartSize: 100 * 1024 * 1024,
},
}
return b, nil
}
func (b *ADLv2) Bucket() string {
return b.bucket
}
func (b *ADLv2) Delegate() interface{} {
return b
}
func (b *ADLv2) Init(key string) (err error) {
_, err = b.HeadBlob(&HeadBlobInput{Key: key})
if err == fuse.ENOENT {
err = nil
}
return
}
func (b *ADLv2) Capabilities() *Capabilities {
return &b.cap
}
type ADL2Error struct {
adl2.DataLakeStorageError
}
func (e ADL2Error) Error() string {
return fmt.Sprintf("%v: %v", *e.DataLakeStorageError.Error.Code,
*e.DataLakeStorageError.Error.Message)
}
func decodeADLv2Error(body io.Reader) (adlErr adl2.DataLakeStorageError, err error) {
decoder := json.NewDecoder(body)
err = decoder.Decode(&adlErr)
return
}
func mapADLv2Error(resp *http.Response, err error, rawError bool) error {
if resp == nil {
if err != nil {
if detailedError, ok := err.(autorest.DetailedError); ok {
if urlErr, ok := detailedError.Original.(*url.Error); ok {
adl2Log.Errorf("url.Err: %T: %v %v %v %v %v", urlErr.Err, urlErr.Err, urlErr.Temporary(), urlErr.Timeout(), urlErr.Op, urlErr.URL)
} else {
adl2Log.Errorf("%T: %v", detailedError.Original, detailedError.Original)
}
} else {
adl2Log.Errorf("unknown error: %v", err)
}
return syscall.EAGAIN
} else {
return err
}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
defer resp.Body.Close()
if rawError {
adlErr, err := decodeADLv2Error(resp.Body)
if err == nil {
return ADL2Error{adlErr}
} else {
adl2Log.Errorf("cannot parse error: %v", err)
return syscall.EAGAIN
}
} else {
switch resp.StatusCode {
case http.StatusBadRequest:
if !adl2Log.IsLevelEnabled(logrus.DebugLevel) {
adl2LogResp(logrus.ErrorLevel, resp)
}
adlErr, err := decodeADLv2Error(resp.Body)
if err == nil {
switch *adlErr.Error.Code {
case "MissingRequiredHeader", "UnsupportedHeader":
var s strings.Builder
for k, _ := range resp.Request.Header {
s.WriteString(k)
s.WriteString(" ")
}
adl2Log.Errorf("%v, sent: %v",
*adlErr.Error.Code,
s.String())
case "InvalidSourceUri":
adl2Log.Errorf("SourceUri: %v",
resp.Request.Header.Get("X-Ms-Rename-Source"))
}
}
case http.StatusPreconditionFailed:
return syscall.EAGAIN
}
err = mapHttpError(resp.StatusCode)
if err != nil {
return err
} else {
if !adl2Log.IsLevelEnabled(logrus.DebugLevel) {
adl2LogResp(logrus.ErrorLevel, resp)
}
adl2Log.Errorf("resp: %#v %v", resp, err)
return syscall.EINVAL
}
}
} else {
return err
}
}
func getHeader(resp *http.Response, key string) *string {
if v, set := resp.Header[http.CanonicalHeaderKey(key)]; set {
return &v[0]
} else {
return nil
}
}
func parseADLv2Time(v string) *time.Time {
t, err := time.Parse(time.RFC1123, v)
if err == nil {
return &t
} else {
return nil
}
}
func adlv2ToBlobItem(resp *http.Response, key string) BlobItemOutput {
return BlobItemOutput{
Key: &key,
ETag: getHeader(resp, "ETag"),
Size: uint64(resp.ContentLength),
LastModified: parseADLv2Time(resp.Header.Get("Last-Modified")),
}
}
func (b *ADLv2) HeadBlob(param *HeadBlobInput) (*HeadBlobOutput, error) {
key := param.Key
if strings.HasSuffix(key, "/") {
key = key[:len(key)-1]
}
// GetProperties(GetStatus) does not return user defined
// properties, despite what the documentation says, use a 0
// bytes range get instead
res, err := b.GetBlob(&GetBlobInput{
Key: key,
Start: 0,
Count: 0,
})
if err != nil {
return nil, err
}
res.Body.Close()
return &res.HeadBlobOutput, nil
}
func (b *ADLv2) ListBlobs(param *ListBlobsInput) (*ListBlobsOutput, error) {
if param.Delimiter != nil && *param.Delimiter != "/" {
return nil, fuse.EINVAL
}
var maxResults *int32
if param.MaxKeys != nil {
maxResults = PInt32(int32(*param.MaxKeys))
}
res, err := b.client.List(context.TODO(), param.Delimiter == nil, b.bucket,
nilStr(param.Prefix), nilStr(param.ContinuationToken), maxResults,
nil, "", nil, "")
if err != nil {
err = mapADLv2Error(res.Response.Response, err, false)
if err == fuse.ENOENT {
return &ListBlobsOutput{
RequestId: res.Response.Response.Header.Get(ADL2_REQUEST_ID),
}, nil
} else {
return nil, err
}
}
var prefixes []BlobPrefixOutput
var items []BlobItemOutput
if param.Delimiter != nil && param.Prefix != nil {
// we didn't get 404 which means the path must
// exists. If the path is actually a file, adlv2
// returns the file itself as the result. That's
// already handled by the loop below
if len(*res.Paths) != 1 ||
*(*res.Paths)[0].Name != strings.TrimRight(*param.Prefix, "/") {
// the prefix we listed is a directory
if strings.HasSuffix(*param.Prefix, "/") {
// we listed for the dir object itself
items = append(items, BlobItemOutput{
Key: param.Prefix,
})
} else {
prefixes = append(prefixes, BlobPrefixOutput{
PString(*param.Prefix + "/"),
})
}
} else {
if strings.HasSuffix(*param.Prefix, "/") {
// we asked for a dir and got a file
return &ListBlobsOutput{
RequestId: res.Response.Response.Header.Get(ADL2_REQUEST_ID),
}, nil
}
}
}
for _, p := range *res.Paths {
if param.Delimiter != nil {
if p.isDirectory() {
prefixes = append(prefixes, BlobPrefixOutput{
PString(*p.Name + "/"),
})
continue
}
}
key := *p.Name
if p.isDirectory() {
key += "/"
}
items = append(items, BlobItemOutput{
Key: &key,
ETag: p.ETag,
LastModified: parseADLv2Time(nilStr(p.LastModified)),
Size: uint64(p.contentLength()),
})
}
continuationToken := getHeader(res.Response.Response, "x-ms-continuation")
return &ListBlobsOutput{
Prefixes: prefixes,
Items: items,
NextContinuationToken: continuationToken,
IsTruncated: continuationToken != nil,
RequestId: res.Response.Response.Header.Get(ADL2_REQUEST_ID),
}, nil
}
func (b *ADLv2) DeleteBlob(param *DeleteBlobInput) (*DeleteBlobOutput, error) {
if strings.HasSuffix(param.Key, "/") {
return b.DeleteBlob(&DeleteBlobInput{param.Key[:len(param.Key)-1]})
}
res, err := b.client.Delete(context.TODO(), b.bucket, param.Key, nil, "", "",
/*ifMatch=*/ "", "", "", "", "", nil, "")
err = mapADLv2Error(res.Response, err, false)
if err != nil {
return nil, err
}
return &DeleteBlobOutput{}, nil
}
func (b *ADLv2) DeleteBlobs(param *DeleteBlobsInput) (*DeleteBlobsOutput, error) {
return nil, syscall.ENOTSUP
}
func (b *ADLv2) RenameBlob(param *RenameBlobInput) (*RenameBlobOutput, error) {
var continuation string
renameDest := param.Destination
if strings.HasSuffix(renameDest, "/") {
renameDest = renameDest[:len(renameDest)-1]
}
renameSource := param.Source
if strings.HasSuffix(renameSource, "/") {
renameSource = renameSource[:len(renameSource)-1]
}
renameSource = "/" + b.bucket + "/" + url.PathEscape(renameSource)
var requestId string
for cont := true; cont; cont = continuation != "" {
res, err := b.client.Create(context.TODO(), b.bucket, renameDest,
"", continuation, "", "", "", "", "", "", "", "", "", "",
renameSource, "", "", "", "", "", "", "", "", "", "", "",
"", "", "", nil, "")
if err != nil {
return nil, mapADLv2Error(res.Response, err, false)
}
continuation = res.Header.Get("x-ms-continuation")
requestId = res.Header.Get(ADL2_REQUEST_ID)
}
return &RenameBlobOutput{requestId}, nil
}
func (b *ADLv2) CopyBlob(param *CopyBlobInput) (*CopyBlobOutput, error) {
if param.Source != param.Destination || param.Metadata == nil {
return nil, syscall.ENOTSUP
}
res, err := b.client.Update(context.TODO(), adl2.SetProperties, b.bucket, param.Source, nil,
nil, nil, nil, "", "", "", "", "", "", "", "", b.toADLProperties(param.Metadata),
"", "", "", "", "", "", "", "", nil, "", nil, "")
if err != nil {
return nil, mapADLv2Error(res.Response, err, false)
}
return &CopyBlobOutput{
RequestId: res.Response.Header.Get(ADL2_REQUEST_ID),
}, nil
}
func (b *ADLv2) GetBlob(param *GetBlobInput) (*GetBlobOutput, error) {
var bytes string
if param.Start != 0 || param.Count != 0 {
if param.Count != 0 {
bytes = fmt.Sprintf("bytes=%v-%v", param.Start, param.Start+param.Count-1)
} else {
bytes = fmt.Sprintf("bytes=%v-", param.Start)
}
}
res, err := b.client.Read(context.TODO(), b.bucket, param.Key, bytes,
"", nil, nilStr(param.IfMatch), "", "", "",
"", nil, "")
if err != nil {
return nil, mapADLv2Error(res.Response.Response, err, false)
}
metadata := make(map[string]*string)
for _, p := range res.Header["X-Ms-Properties"] {
csv := strings.Split(p, ",")
for _, kv := range csv {
kv = strings.TrimSpace(kv)
if len(kv) == 0 {
continue
}
s := strings.SplitN(kv, "=", 2)
if len(s) != 2 {
adl2Log.Warnf("Dropping property: %v: %v", param.Key, kv)
continue
}
key := strings.TrimSpace(s[0])
value := strings.TrimSpace(s[1])
buf, err := base64.StdEncoding.DecodeString(value)
if err != nil {
adl2Log.Warnf("Unable to decode property: %v: %v",
param.Key, key)
continue
}
metadata[key] = PString(string(buf))
}
}
return &GetBlobOutput{
HeadBlobOutput: HeadBlobOutput{
BlobItemOutput: adlv2ToBlobItem(res.Response.Response, param.Key),
ContentType: getHeader(res.Response.Response, "Content-Type"),
IsDirBlob: res.Header.Get("X-Ms-Resource-Type") == string(adl2.Directory),
Metadata: metadata,
},
Body: *res.Value,
}, nil
}
func (b *ADLv2) toADLProperties(metadata map[string]*string) string {
var buf strings.Builder
for k, v := range metadata {
buf.WriteString(k)
buf.WriteString("=")
buf.WriteString(base64.StdEncoding.EncodeToString([]byte(*v)))
buf.WriteString(",")
}
var s = buf.String()
if len(s) != 0 {
// remove trailing comma
s = s[:len(s)-1]
}
return s
}
func (b *ADLv2) create(key string, pathType adl2.PathResourceType, contentType *string,
metadata map[string]*string, leaseId string) (resp autorest.Response, err error) {
resp, err = b.client.Create(context.TODO(), b.bucket, key,
pathType, "", "", "", "", "", "", "", nilStr(contentType),
"", "", "", "", leaseId, "", b.toADLProperties(metadata), "", "", "", "", "", "",
"", "", "", "", "", nil, "")
if err != nil {
err = mapADLv2Error(resp.Response, err, false)
}
return
}
func (b *ADLv2) append(key string, offset int64, size int64, body io.ReadSeeker,
leaseId string) (resp autorest.Response, err error) {
resp, err = b.client.Update(context.TODO(), adl2.Append, b.bucket,
key, &offset, nil, nil, &size, "", leaseId, "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", &ReadSeekerCloser{body},
"", nil, "")
if err != nil {
err = mapADLv2Error(resp.Response, err, false)
}
return
}
func (b *ADLv2) flush(key string, offset int64, contentType string, leaseId string) (res autorest.Response, err error) {
res, err = b.client.Update(context.TODO(), adl2.Flush, b.bucket,
key, &offset, PBool(false), PBool(true), PInt64(0), "", leaseId, "",
contentType, "", "", "", "", "", "", "", "", "",
"", "", "", "", nil, "", nil, "")
if err != nil {
err = mapADLv2Error(res.Response, err, false)
}
return
}
func (b *ADLv2) PutBlob(param *PutBlobInput) (*PutBlobOutput, error) {
if param.DirBlob {
res, err := b.create(param.Key, adl2.Directory, param.ContentType,
param.Metadata, "")
if err != nil {
return nil, err
}
return &PutBlobOutput{
ETag: getHeader(res.Response, "ETag"),
}, nil
} else {
if param.Size == nil {
panic("size cannot be nil")
}
create, err := b.create(param.Key, adl2.File, param.ContentType,
param.Metadata, "")
if err != nil {
return nil, err
}
size := int64(*param.Size)
if size == 0 {
// nothing to write, we can return
// here. appending a 0-size buffer
// causes azure to fail with 400 bad
// request
return &PutBlobOutput{
ETag: getHeader(create.Response, "ETag"),
}, nil
}
// not doing a lease for these because append to 0
// would guarantee that we don't have concurrent
// appends, and flushing is safe to do
_, err = b.append(param.Key, 0, size, param.Body, "")
if err != nil {
return nil, err
}
flush, err := b.flush(param.Key, size, nilStr(param.ContentType), "")
if err != nil {
return nil, err
}
return &PutBlobOutput{
ETag: getHeader(flush.Response, "ETag"),
}, nil
}
}
// adlv2 doesn't have atomic multipart upload, instead we will hold a
// lease, replace the object, then release the lease
func (b *ADLv2) MultipartBlobBegin(param *MultipartBlobBeginInput) (*MultipartBlobCommitInput, error) {
leaseId := uuid.New().String()
err := b.lease(adl2.Acquire, param.Key, leaseId, 60, "")
if err == fuse.ENOENT {
// the file didn't exist, we will create the file
// first and then acquire the lease
create, err := b.create(param.Key, adl2.File, param.ContentType, param.Metadata, "")
if err != nil {
return nil, err
}
err = b.lease(adl2.Acquire, param.Key, leaseId, 60,
create.Response.Header.Get("ETag"))
if err != nil {
return nil, err
}
} else {
if err != nil {
return nil, err
}
defer func() {
if err != nil {
err2 := b.lease(adl2.Release, param.Key, leaseId, 0, "")
if err2 != nil {
adl2Log.Errorf("Unable to release lease for %v: %v",
param.Key, err2)
}
}
}()
_, err = b.create(param.Key, adl2.File, param.ContentType, param.Metadata, leaseId)
if err != nil {
return nil, err
}
}
commitData := &ADLv2MultipartBlobCommitInput{
ContentType: nilStr(param.ContentType),
RenewLeaseStop: make(chan bool, 1),
}
go func() {
for {
select {
case <-commitData.RenewLeaseStop:
break
case <-time.After(30 * time.Second):
b.lease(adl2.Renew, param.Key, leaseId, 60, "")
}
}
}()
return &MultipartBlobCommitInput{
Key: ¶m.Key,
Metadata: param.Metadata,
UploadId: &leaseId,
backendData: commitData,
}, nil
}
func (b *ADLv2) lease(action adl2.PathLeaseAction, key string, leaseId string, durationSec int32,
ifMatch string) error {
var proposeLeaseId string
var prevLeaseId string
if action == adl2.Acquire {
proposeLeaseId = leaseId
} else {
prevLeaseId = leaseId
}
var duration *int32
if durationSec != 0 {
duration = &durationSec
}
res, err := b.client.Lease(context.TODO(), action, b.bucket, key,
duration, nil, prevLeaseId, proposeLeaseId, ifMatch, "", "", "", "", nil, "")
if err != nil {
err = mapADLv2Error(res.Response, err, false)
}
return err
}
func (b *ADLv2) MultipartBlobAdd(param *MultipartBlobAddInput) (*MultipartBlobAddOutput, error) {
var commitData *ADLv2MultipartBlobCommitInput
var ok bool
if commitData, ok = param.Commit.backendData.(*ADLv2MultipartBlobCommitInput); !ok {
panic("Incorrect commit data type")
}
res, err := b.append(*param.Commit.Key, int64(param.Offset), int64(param.Size),
param.Body, *param.Commit.UploadId)
if err != nil {
return nil, err
}
atomic.AddUint64(&commitData.Size, param.Size)
return &MultipartBlobAddOutput{
res.Response.Header.Get(ADL2_REQUEST_ID),
}, nil
}
func (b *ADLv2) MultipartBlobAbort(param *MultipartBlobCommitInput) (*MultipartBlobAbortOutput, error) {
if param.UploadId != nil {
err := b.lease(adl2.Release, *param.Key, *param.UploadId, 0, "")
if err != nil {
return nil, err
}
}
return &MultipartBlobAbortOutput{}, nil
}
func (b *ADLv2) MultipartBlobCommit(param *MultipartBlobCommitInput) (*MultipartBlobCommitOutput, error) {
var commitData *ADLv2MultipartBlobCommitInput
var ok bool
if commitData, ok = param.backendData.(*ADLv2MultipartBlobCommitInput); !ok {
panic("Incorrect commit data type")
}
defer func() {
commitData.RenewLeaseStop <- true
leaseId := *param.UploadId
// if the commit failed, we don't need to release the
// lease during abort
param.UploadId = nil
err2 := b.lease(adl2.Release, *param.Key, leaseId, 0, "")
if err2 != nil {
adl2Log.Errorf("Unable to release lease for %v: %v",
*param.Key, err2)
}
}()
flush, err := b.flush(*param.Key, int64(commitData.Size), commitData.ContentType, *param.UploadId)
if err != nil {
return nil, err
}
return &MultipartBlobCommitOutput{
ETag: nil,
RequestId: flush.Response.Header.Get(ADL2_REQUEST_ID),
}, nil
}
func (b *ADLv2) MultipartExpire(param *MultipartExpireInput) (*MultipartExpireOutput, error) {
return nil, syscall.ENOTSUP
}
func (b *ADLv2) RemoveBucket(param *RemoveBucketInput) (*RemoveBucketOutput, error) {
fs := adl2.FilesystemClient{b.client.BaseClient}
res, err := fs.Delete(context.TODO(), b.bucket, "", "", uuid.New().String(), nil, "")
if err != nil {
return nil, mapADLv2Error(res.Response, err, false)
}
return &RemoveBucketOutput{}, nil
}
func (b *ADLv2) MakeBucket(param *MakeBucketInput) (*MakeBucketOutput, error) {
fs := adl2.FilesystemClient{b.client.BaseClient}
res, err := fs.Create(context.TODO(), b.bucket, "", uuid.New().String(), nil, "")
if err != nil {
return nil, mapADLv2Error(res.Response, err, false)
}
return &MakeBucketOutput{}, nil
}
// hacked from azure-sdk-for-go
// remove after these bugs are fixed:
// https://github.com/Azure/azure-sdk-for-go/issues/5502
// https://github.com/Azure/azure-sdk-for-go/issues/5550
// https://github.com/Azure/azure-sdk-for-go/issues/5549
type adl2PathClient struct {
adl2.BaseClient
}
func (client adl2PathClient) Create(ctx context.Context, filesystem string, pathParameter string, resource adl2.PathResourceType, continuation string, mode adl2.PathRenameMode, cacheControl string, contentEncoding string, contentLanguage string, contentDisposition string, xMsCacheControl string, xMsContentType string, xMsContentEncoding string, xMsContentLanguage string, xMsContentDisposition string, xMsRenameSource string, xMsLeaseID string, xMsSourceLeaseID string, xMsProperties string, xMsPermissions string, xMsUmask string, ifMatch string, ifNoneMatch string, ifModifiedSince string, ifUnmodifiedSince string, xMsSourceIfMatch string, xMsSourceIfNoneMatch string, xMsSourceIfModifiedSince string, xMsSourceIfUnmodifiedSince string, xMsClientRequestID string, timeout *int32, xMsDate string) (result autorest.Response, err error) {
req, err := client.CreatePreparer(ctx, filesystem, pathParameter, resource, continuation, mode, cacheControl, contentEncoding, contentLanguage, contentDisposition, xMsCacheControl, xMsContentType, xMsContentEncoding, xMsContentLanguage, xMsContentDisposition, xMsRenameSource, xMsLeaseID, xMsSourceLeaseID, xMsProperties, xMsPermissions, xMsUmask, ifMatch, ifNoneMatch, ifModifiedSince, ifUnmodifiedSince, xMsSourceIfMatch, xMsSourceIfNoneMatch, xMsSourceIfModifiedSince, xMsSourceIfUnmodifiedSince, xMsClientRequestID, timeout, xMsDate)
if err != nil {
err = autorest.NewErrorWithError(err, "storagedatalake.adl2PathClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "storagedatalake.adl2PathClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storagedatalake.adl2PathClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client adl2PathClient) CreatePreparer(ctx context.Context, filesystem string, pathParameter string, resource adl2.PathResourceType, continuation string, mode adl2.PathRenameMode, cacheControl string, contentEncoding string, contentLanguage string, contentDisposition string, xMsCacheControl string, xMsContentType string, xMsContentEncoding string, xMsContentLanguage string, xMsContentDisposition string, xMsRenameSource string, xMsLeaseID string, xMsSourceLeaseID string, xMsProperties string, xMsPermissions string, xMsUmask string, ifMatch string, ifNoneMatch string, ifModifiedSince string, ifUnmodifiedSince string, xMsSourceIfMatch string, xMsSourceIfNoneMatch string, xMsSourceIfModifiedSince string, xMsSourceIfUnmodifiedSince string, xMsClientRequestID string, timeout *int32, xMsDate string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"accountName": client.AccountName,
"dnsSuffix": client.DNSSuffix,
}
pathParameters := map[string]interface{}{
"filesystem": autorest.Encode("path", filesystem),
//"path": url.PathEscape(pathParameter),
"path": autorest.Encode("path", pathParameter),
}
queryParameters := map[string]interface{}{}
if len(string(resource)) > 0 {
queryParameters["resource"] = autorest.Encode("query", resource)
}
if len(continuation) > 0 {
queryParameters["continuation"] = autorest.Encode("query", continuation)
}
if len(string(mode)) > 0 {
queryParameters["mode"] = autorest.Encode("query", mode)
}
if timeout != nil {
queryParameters["timeout"] = autorest.Encode("query", *timeout)
}
preparer := autorest.CreatePreparer(
autorest.AsPut(),
autorest.WithCustomBaseURL("http://{accountName}.{dnsSuffix}", urlParameters),
autorest.WithPathParameters("/{filesystem}/{path}", pathParameters),
autorest.WithQueryParameters(queryParameters))
if len(cacheControl) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Cache-Control", autorest.String(cacheControl)))
}
if len(contentEncoding) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Content-Encoding", autorest.String(contentEncoding)))
}
if len(contentLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Content-Language", autorest.String(contentLanguage)))
}
if len(contentDisposition) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("Content-Disposition", autorest.String(contentDisposition)))
}
if len(xMsCacheControl) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-cache-control", autorest.String(xMsCacheControl)))
}
if len(xMsContentType) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-content-type", autorest.String(xMsContentType)))
}
if len(xMsContentEncoding) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-content-encoding", autorest.String(xMsContentEncoding)))
}
if len(xMsContentLanguage) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-content-language", autorest.String(xMsContentLanguage)))
}
if len(xMsContentDisposition) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-content-disposition", autorest.String(xMsContentDisposition)))
}
if len(xMsRenameSource) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-rename-source", autorest.String(xMsRenameSource)))
}
if len(xMsLeaseID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-lease-id", autorest.String(xMsLeaseID)))
}
if len(xMsSourceLeaseID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-source-lease-id", autorest.String(xMsSourceLeaseID)))
}
if len(xMsProperties) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-properties", autorest.String(xMsProperties)))
}
if len(xMsPermissions) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-permissions", autorest.String(xMsPermissions)))
}
if len(xMsUmask) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-umask", autorest.String(xMsUmask)))
}
if len(ifMatch) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("If-Match", autorest.String(ifMatch)))
}
if len(ifNoneMatch) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch)))
}
if len(ifModifiedSince) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("If-Modified-Since", autorest.String(ifModifiedSince)))
}
if len(ifUnmodifiedSince) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("If-Unmodified-Since", autorest.String(ifUnmodifiedSince)))
}
if len(xMsSourceIfMatch) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-source-if-match", autorest.String(xMsSourceIfMatch)))
}
if len(xMsSourceIfNoneMatch) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-source-if-none-match", autorest.String(xMsSourceIfNoneMatch)))
}
if len(xMsSourceIfModifiedSince) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-source-if-modified-since", autorest.String(xMsSourceIfModifiedSince)))
}
if len(xMsSourceIfUnmodifiedSince) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-source-if-unmodified-since", autorest.String(xMsSourceIfUnmodifiedSince)))
}
if len(xMsClientRequestID) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-client-request-id", autorest.String(xMsClientRequestID)))
}
if len(xMsDate) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-date", autorest.String(xMsDate)))
}
if len(client.XMsVersion) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("x-ms-version", autorest.String(client.XMsVersion)))
}
return preparer.Prepare((client.defaultRequest()).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client adl2PathClient) CreateSender(req *http.Request) (*http.Response, error) {
sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
return autorest.SendWithSender(client, req, sd...)
}