forked from pulumi/pulumi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asset.go
1212 lines (1073 loc) · 34.8 KB
/
asset.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 2016-2018, Pulumi Corporation.
//
// 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 resource
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"time"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/util/contract"
"github.com/pulumi/pulumi/pkg/util/httputil"
"github.com/pulumi/pulumi/pkg/workspace"
)
// Asset is a serialized asset reference. It is a union: thus, only one of its fields will be non-nil. Several helper
// routines exist as members in order to easily interact with the assets referenced by an instance of this type.
// nolint: lll
type Asset struct {
Sig string `json:"4dabf18193072939515e22adb298388d" yaml:"4dabf18193072939515e22adb298388d"` // the unique asset signature (see properties.go).
Hash string `json:"hash,omitempty" yaml:"hash,omitempty"` // the SHA256 hash of the asset contents.
Text string `json:"text,omitempty" yaml:"text,omitempty"` // a textual asset.
Path string `json:"path,omitempty" yaml:"path,omitempty"` // a file on the current filesystem.
URI string `json:"uri,omitempty" yaml:"uri,omitempty"` // a URI (file://, http://, https://, or custom).
}
const (
AssetSig = "c44067f5952c0a294b673a41bacd8c17" // a randomly assigned type hash for assets.
AssetHashProperty = "hash" // the dynamic property for an asset's hash.
AssetTextProperty = "text" // the dynamic property for an asset's text.
AssetPathProperty = "path" // the dynamic property for an asset's path.
AssetURIProperty = "uri" // the dynamic property for an asset's URI.
)
// NewTextAsset produces a new asset and its corresponding SHA256 hash from the given text.
func NewTextAsset(text string) (*Asset, error) {
a := &Asset{Sig: AssetSig, Text: text}
err := a.EnsureHash()
return a, err
}
// NewPathAsset produces a new asset and its corresponding SHA256 hash from the given filesystem path.
func NewPathAsset(path string) (*Asset, error) {
a := &Asset{Sig: AssetSig, Path: path}
err := a.EnsureHash()
return a, err
}
// NewURIAsset produces a new asset and its corresponding SHA256 hash from the given network URI.
func NewURIAsset(uri string) (*Asset, error) {
a := &Asset{Sig: AssetSig, URI: uri}
err := a.EnsureHash()
return a, err
}
func (a *Asset) IsText() bool { return a.Text != "" }
func (a *Asset) IsPath() bool { return a.Path != "" }
func (a *Asset) IsURI() bool { return a.URI != "" }
func (a *Asset) GetText() (string, bool) {
if a.IsText() {
return a.Text, true
}
return "", false
}
func (a *Asset) GetPath() (string, bool) {
if a.IsPath() {
return a.Path, true
}
return "", false
}
func (a *Asset) GetURI() (string, bool) {
if a.IsURI() {
return a.URI, true
}
return "", false
}
var (
functionRegexp = regexp.MustCompile(`function __.*`)
withRegexp = regexp.MustCompile(` with\({ .* }\) {`)
environmentRegexp = regexp.MustCompile(` }\).apply\(.*\).apply\(this, arguments\);`)
preambleRegexp = regexp.MustCompile(
`function __.*\(\) {\n return \(function\(\) {\n with \(__closure\) {\n\nreturn `)
postambleRegexp = regexp.MustCompile(
`;\n\n }\n }\).apply\(__environment\).apply\(this, arguments\);\n}`)
)
// IsUserProgramCode checks to see if this is the special asset containing the users's code
func (a *Asset) IsUserProgramCode() bool {
if !a.IsText() {
return false
}
text := a.Text
return functionRegexp.MatchString(text) &&
withRegexp.MatchString(text) &&
environmentRegexp.MatchString(text)
}
// MassageIfUserProgramCodeAsset takes the text for a function and cleans it up a bit to make the
// user visible diffs less noisy. Specifically:
// 1. it tries to condense things by changling multiple blank lines into a single blank line.
// 2. it normalizs the sha hashes we emit so that changes to them don't appear in the diff.
// 3. it elides the with-capture headers, as changes there are not generally meaningful.
//
// TODO(https://github.com/pulumi/pulumi/issues/592) this is baking in a lot of knowledge about
// pulumi serialized functions. We should try to move to an alternative mode that isn't so brittle.
// Options include:
// 1. Have a documented delimeter format that plan.go will look for. Have the function serializer
// emit those delimeters around code that should be ignored.
// 2. Have our resource generation code supply not just the resource, but the "user presentable"
// resource that cuts out a lot of cruft. We could then just diff that content here.
func MassageIfUserProgramCodeAsset(asset *Asset, debug bool) *Asset {
if debug {
return asset
}
// Only do this for strings that match our serialized function pattern.
if !asset.IsUserProgramCode() {
return asset
}
text := asset.Text
replaceNewlines := func() {
for {
newText := strings.Replace(text, "\n\n\n", "\n\n", -1)
if len(newText) == len(text) {
break
}
text = newText
}
}
replaceNewlines()
firstFunc := functionRegexp.FindStringIndex(text)
text = text[firstFunc[0]:]
text = withRegexp.ReplaceAllString(text, " with (__closure) {")
text = environmentRegexp.ReplaceAllString(text, " }).apply(__environment).apply(this, arguments);")
text = preambleRegexp.ReplaceAllString(text, "")
text = postambleRegexp.ReplaceAllString(text, "")
replaceNewlines()
return &Asset{Text: text}
}
// GetURIURL returns the underlying URI as a parsed URL, provided it is one. If there was an error parsing the URI, it
// will be returned as a non-nil error object.
func (a *Asset) GetURIURL() (*url.URL, bool, error) {
if uri, isuri := a.GetURI(); isuri {
url, err := url.Parse(uri)
if err != nil {
return nil, true, err
}
return url, true, nil
}
return nil, false, nil
}
// Equals returns true if a is value-equal to other. In this case, value equality is determined only by the hash: even
// if the contents of two assets come from different sources, they are treated as equal if their hashes match.
// Similarly, if the contents of two assets come from the same source but the assets have different hashes, the assets
// are not equal.
func (a *Asset) Equals(other *Asset) bool {
if a == nil {
return other == nil
} else if other == nil {
return false
}
// If we can't get a hash for both assets, treat them as differing.
if err := a.EnsureHash(); err != nil {
return false
}
if err := other.EnsureHash(); err != nil {
return false
}
return a.Hash == other.Hash
}
// Serialize returns a weakly typed map that contains the right signature for serialization purposes.
func (a *Asset) Serialize() map[string]interface{} {
result := map[string]interface{}{
string(SigKey): AssetSig,
}
if a.Hash != "" {
result[AssetHashProperty] = a.Hash
}
if a.Text != "" {
result[AssetTextProperty] = a.Text
}
if a.Path != "" {
result[AssetPathProperty] = a.Path
}
if a.URI != "" {
result[AssetURIProperty] = a.URI
}
return result
}
// DeserializeAsset checks to see if the map contains an asset, using its signature, and if so deserializes it.
func DeserializeAsset(obj map[string]interface{}) (*Asset, bool, error) {
// If not an asset, return false immediately.
if obj[string(SigKey)] != AssetSig {
return &Asset{}, false, nil
}
// Else, deserialize the possible fields.
var hash string
if v, has := obj[AssetHashProperty]; has {
hash = v.(string)
}
var text string
if v, has := obj[AssetTextProperty]; has {
text = v.(string)
}
var path string
if v, has := obj[AssetPathProperty]; has {
path = v.(string)
}
var uri string
if v, has := obj[AssetURIProperty]; has {
uri = v.(string)
}
return &Asset{Hash: hash, Text: text, Path: path, URI: uri}, true, nil
}
// HasContents indicates whether or not an asset's contents can be read.
func (a *Asset) HasContents() bool {
return a.IsText() || a.IsPath() || a.IsURI()
}
// Bytes returns the contents of the asset as a byte slice.
func (a *Asset) Bytes() ([]byte, error) {
// If this is a text asset, just return its bytes directly.
if text, istext := a.GetText(); istext {
return []byte(text), nil
}
blob, err := a.Read()
if err != nil {
return nil, err
}
return ioutil.ReadAll(blob)
}
// Read begins reading an asset.
func (a *Asset) Read() (*Blob, error) {
contract.Assertf(a.HasContents(), "cannot read an asset that has no contents")
if a.IsText() {
return a.readText()
} else if a.IsPath() {
return a.readPath()
} else if a.IsURI() {
return a.readURI()
}
return nil, nil
}
func (a *Asset) readText() (*Blob, error) {
text, istext := a.GetText()
contract.Assertf(istext, "Expected a text-based asset")
return NewByteBlob([]byte(text)), nil
}
func (a *Asset) readPath() (*Blob, error) {
path, ispath := a.GetPath()
contract.Assertf(ispath, "Expected a path-based asset")
file, err := os.Open(path)
if err != nil {
return nil, errors.Wrapf(err, "failed to open asset file '%v'", path)
}
// Do a quick check to make sure it's a file, so we can fail gracefully if someone passes a directory.
info, err := file.Stat()
if err != nil {
contract.IgnoreClose(file)
return nil, errors.Wrapf(err, "failed to stat asset file '%v'", path)
}
if info.IsDir() {
contract.IgnoreClose(file)
return nil, errors.Errorf("asset path '%v' is a directory; try using an archive", path)
}
blob := &Blob{
rd: file,
sz: info.Size(),
}
return blob, nil
}
func (a *Asset) readURI() (*Blob, error) {
url, isurl, err := a.GetURIURL()
if err != nil {
return nil, err
}
contract.Assertf(isurl, "Expected a URI-based asset")
switch s := url.Scheme; s {
case "http", "https":
resp, err := httputil.GetWithRetry(url.String(), http.DefaultClient)
if err != nil {
return nil, err
}
return NewReadCloserBlob(resp.Body)
case "file":
contract.Assert(url.User == nil)
contract.Assert(url.RawQuery == "")
contract.Assert(url.Fragment == "")
if url.Host != "" && url.Host != "localhost" {
return nil, errors.Errorf("file:// host '%v' not supported (only localhost)", url.Host)
}
f, err := os.Open(url.Path)
if err != nil {
return nil, err
}
return NewFileBlob(f)
default:
return nil, errors.Errorf("Unrecognized or unsupported URI scheme: %v", s)
}
}
// EnsureHash computes the SHA256 hash of the asset's contents and stores it on the object.
func (a *Asset) EnsureHash() error {
if a.Hash == "" {
blob, err := a.Read()
if err != nil {
return err
}
defer contract.IgnoreClose(blob)
hash := sha256.New()
_, err = io.Copy(hash, blob)
if err != nil {
return err
}
a.Hash = hex.EncodeToString(hash.Sum(nil))
}
return nil
}
// Blob is a blob that implements ReadCloser and offers Len functionality.
type Blob struct {
rd io.ReadCloser // an underlying reader.
sz int64 // the size of the blob.
}
func (blob *Blob) Close() error { return blob.rd.Close() }
func (blob *Blob) Read(p []byte) (int, error) { return blob.rd.Read(p) }
func (blob *Blob) Size() int64 { return blob.sz }
// NewByteBlob creates a new byte blob.
func NewByteBlob(data []byte) *Blob {
return &Blob{
rd: ioutil.NopCloser(bytes.NewReader(data)),
sz: int64(len(data)),
}
}
// NewFileBlob creates a new asset blob whose size is known thanks to stat.
func NewFileBlob(f *os.File) (*Blob, error) {
stat, err := f.Stat()
if err != nil {
return nil, err
}
return &Blob{
rd: f,
sz: stat.Size(),
}, nil
}
// NewReadCloserBlob turn any old ReadCloser into an Blob, usually by making a copy.
func NewReadCloserBlob(r io.ReadCloser) (*Blob, error) {
if f, isf := r.(*os.File); isf {
// If it's a file, we can "fast path" the asset creation without making a copy.
return NewFileBlob(f)
}
// Otherwise, read it all in, and create a blob out of that.
defer contract.IgnoreClose(r)
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return NewByteBlob(data), nil
}
// Archive is a serialized archive reference. It is a union: thus, only one of its fields will be non-nil. Several
// helper routines exist as members in order to easily interact with archives of different kinds.
//nolint: lll
type Archive struct {
Sig string `json:"4dabf18193072939515e22adb298388d" yaml:"4dabf18193072939515e22adb298388d"` // the unique asset signature (see properties.go).
Hash string `json:"hash,omitempty" yaml:"hash,omitempty"` // the SHA256 hash of the archive contents.
Assets map[string]interface{} `json:"assets,omitempty" yaml:"assets,omitempty"` // a collection of other assets/archives.
Path string `json:"path,omitempty" yaml:"path,omitempty"` // a file on the current filesystem.
URI string `json:"uri,omitempty" yaml:"uri,omitempty"` // a remote URI (file://, http://, https://, etc).
}
const (
ArchiveSig = "0def7320c3a5731c473e5ecbe6d01bc7" // a randomly assigned archive type signature.
ArchiveHashProperty = "hash" // the dynamic property for an archive's hash.
ArchiveAssetsProperty = "assets" // the dynamic property for an archive's assets.
ArchivePathProperty = "path" // the dynamic property for an archive's path.
ArchiveURIProperty = "uri" // the dynamic property for an archive's URI.
)
func NewAssetArchive(assets map[string]interface{}) (*Archive, error) {
// Ensure all elements are either assets or archives.
for _, asset := range assets {
switch t := asset.(type) {
case *Asset, *Archive:
// ok
default:
return &Archive{}, errors.Errorf("type %v is not a valid archive element", t)
}
}
a := &Archive{Sig: ArchiveSig, Assets: assets}
err := a.EnsureHash()
return a, err
}
func NewPathArchive(path string) (*Archive, error) {
a := &Archive{Sig: ArchiveSig, Path: path}
err := a.EnsureHash()
return a, err
}
func NewURIArchive(uri string) (*Archive, error) {
a := &Archive{Sig: ArchiveSig, URI: uri}
err := a.EnsureHash()
return a, err
}
func (a *Archive) IsAssets() bool { return a.Assets != nil }
func (a *Archive) IsPath() bool { return a.Path != "" }
func (a *Archive) IsURI() bool { return a.URI != "" }
func (a *Archive) GetAssets() (map[string]interface{}, bool) {
if a.IsAssets() {
return a.Assets, true
}
return nil, false
}
func (a *Archive) GetPath() (string, bool) {
if a.IsPath() {
return a.Path, true
}
return "", false
}
func (a *Archive) GetURI() (string, bool) {
if a.IsURI() {
return a.URI, true
}
return "", false
}
// GetURIURL returns the underlying URI as a parsed URL, provided it is one. If there was an error parsing the URI, it
// will be returned as a non-nil error object.
func (a *Archive) GetURIURL() (*url.URL, bool, error) {
if uri, isuri := a.GetURI(); isuri {
url, err := url.Parse(uri)
if err != nil {
return nil, true, err
}
return url, true, nil
}
return nil, false, nil
}
// Equals returns true if a is value-equal to other. In this case, value equality is determined only by the hash: even
// if the contents of two archives come from different sources, they are treated as equal if their hashes match.
// Similarly, if the contents of two archives come from the same source but the archives have different hashes, the
// archives are not equal.
func (a *Archive) Equals(other *Archive) bool {
if a == nil {
return other == nil
} else if other == nil {
return false
}
// If we can't get a hash for both archives, treat them as differing.
if err := a.EnsureHash(); err != nil {
return false
}
if err := other.EnsureHash(); err != nil {
return false
}
return a.Hash == other.Hash
}
// Serialize returns a weakly typed map that contains the right signature for serialization purposes.
func (a *Archive) Serialize() map[string]interface{} {
result := map[string]interface{}{
string(SigKey): ArchiveSig,
}
if a.Hash != "" {
result[ArchiveHashProperty] = a.Hash
}
if a.Assets != nil {
assets := make(map[string]interface{})
for k, v := range a.Assets {
switch t := v.(type) {
case *Asset:
assets[k] = t.Serialize()
case *Archive:
assets[k] = t.Serialize()
default:
contract.Failf("Unrecognized asset map type %v", reflect.TypeOf(t))
}
}
result[ArchiveAssetsProperty] = assets
}
if a.Path != "" {
result[ArchivePathProperty] = a.Path
}
if a.URI != "" {
result[ArchiveURIProperty] = a.URI
}
return result
}
// DeserializeArchive checks to see if the map contains an archive, using its signature, and if so deserializes it.
func DeserializeArchive(obj map[string]interface{}) (*Archive, bool, error) {
// If not an archive, return false immediately.
if obj[string(SigKey)] != ArchiveSig {
return &Archive{}, false, nil
}
var hash string
if v, has := obj[ArchiveHashProperty]; has {
hash = v.(string)
}
var assets map[string]interface{}
if v, has := obj[ArchiveAssetsProperty]; has {
assets = make(map[string]interface{})
if v != nil {
for k, elem := range v.(map[string]interface{}) {
switch t := elem.(type) {
case *Asset:
assets[k] = t
case *Archive:
assets[k] = t
case map[string]interface{}:
a, isa, err := DeserializeAsset(t)
if err != nil {
return &Archive{}, false, err
} else if isa {
assets[k] = a
} else {
arch, isarch, err := DeserializeArchive(t)
if err != nil {
return &Archive{}, false, err
} else if !isarch {
return &Archive{}, false, errors.Errorf("archive member '%v' is not an asset or archive", k)
}
assets[k] = arch
}
default:
return &Archive{}, false, nil
}
}
}
}
var path string
if v, has := obj[ArchivePathProperty]; has {
path = v.(string)
}
var uri string
if v, has := obj[ArchiveURIProperty]; has {
uri = v.(string)
}
return &Archive{Hash: hash, Assets: assets, Path: path, URI: uri}, true, nil
}
// HasContents indicates whether or not an archive's contents can be read.
func (a *Archive) HasContents() bool {
return a.IsAssets() || a.IsPath() || a.IsURI()
}
// ArchiveReader presents the contents of an archive as a stream of named blobs.
type ArchiveReader interface {
// Next returns the name and contents of the next member of the archive. If there are no more members in the
// archive, this function returns ("", nil, io.EOF). The blob returned by a call to Next() must be read in full
// before the next call to Next().
Next() (string, *Blob, error)
// Close terminates the stream.
Close() error
}
// Open returns an ArchiveReader that can be used to iterate over the named blobs that comprise the archive.
func (a *Archive) Open() (ArchiveReader, error) {
contract.Assertf(a.HasContents(), "cannot read an archive that has no contents")
if a.IsAssets() {
return a.readAssets()
} else if a.IsPath() {
return a.readPath()
} else if a.IsURI() {
return a.readURI()
}
return nil, nil
}
// assetsArchiveReader is used to read an Assets archive.
type assetsArchiveReader struct {
assets map[string]interface{}
keys []string
archive ArchiveReader
archiveRoot string
}
func (r *assetsArchiveReader) Next() (string, *Blob, error) {
for {
// If we're currently flattening out a subarchive, first check to see if it has any more members. If it does,
// return the next member.
if r.archive != nil {
name, blob, err := r.archive.Next()
switch {
case err == io.EOF:
// The subarchive is complete. Nil it out and continue on.
r.archive = nil
case err != nil:
// The subarchive produced a legitimate error; return it.
return "", nil, err
default:
// The subarchive produced a valid blob. Return it.
return filepath.Join(r.archiveRoot, name), blob, nil
}
}
// If there are no more members in this archive, return io.EOF.
if len(r.keys) == 0 {
return "", nil, io.EOF
}
// Fetch the next key in the archive and slice it off of the list.
name := r.keys[0]
r.keys = r.keys[1:]
asset := r.assets[name]
switch t := asset.(type) {
case *Asset:
// An asset can be produced directly.
blob, err := t.Read()
if err != nil {
return "", nil, errors.Wrapf(err, "failed to expand archive asset '%v'", name)
}
return name, blob, nil
case *Archive:
// An archive must be flattened into its constituent blobs. Open the archive for reading and loop.
archive, err := t.Open()
if err != nil {
return "", nil, errors.Wrapf(err, "failed to expand sub-archive '%v'", name)
}
r.archive = archive
r.archiveRoot = name
}
}
}
func (r *assetsArchiveReader) Close() error {
if r.archive != nil {
return r.archive.Close()
}
return nil
}
func (a *Archive) readAssets() (ArchiveReader, error) {
// To read a map-based archive, just produce a map from each asset to its associated reader.
m, isassets := a.GetAssets()
contract.Assertf(isassets, "Expected an asset map-based archive")
// Calculate and sort the list of member names s.t. it is deterministically orderered.
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
r := &assetsArchiveReader{
assets: m,
keys: keys,
}
return r, nil
}
// directoryArchiveReader is used to read an archive that is represented by a directory in the host filesystem.
type directoryArchiveReader struct {
directoryPath string
assetPaths []string
}
func (r *directoryArchiveReader) Next() (string, *Blob, error) {
// If there are no more members in this archive, return io.EOF.
if len(r.assetPaths) == 0 {
return "", nil, io.EOF
}
// Fetch the next path in the archive and slice it off of the list.
assetPath := r.assetPaths[0]
r.assetPaths = r.assetPaths[1:]
// Crop the asset's path s.t. it is relative to the directory path.
name, err := filepath.Rel(r.directoryPath, assetPath)
if err != nil {
return "", nil, err
}
name = filepath.Clean(name)
// Open and return the blob.
blob, err := (&Asset{Path: assetPath}).Read()
if err != nil {
return "", nil, err
}
return name, blob, nil
}
func (r *directoryArchiveReader) Close() error {
return nil
}
func (a *Archive) readPath() (ArchiveReader, error) {
// To read a path-based archive, read that file and use its extension to ascertain what format to use.
path, ispath := a.GetPath()
contract.Assertf(ispath, "Expected a path-based asset")
format := detectArchiveFormat(path)
if format == NotArchive {
// If not an archive, it could be a directory; if so, simply expand it out uncompressed as an archive.
info, err := os.Stat(path)
if err != nil {
return nil, errors.Wrapf(err, "couldn't read archive path '%v'", path)
} else if !info.IsDir() {
return nil, errors.Wrapf(err, "'%v' is neither a recognized archive type nor a directory", path)
}
// Accumulate the list of asset paths. This list is ordered deterministically by filepath.Walk.
assetPaths := []string{}
if walkerr := filepath.Walk(path, func(filePath string, f os.FileInfo, fileerr error) error {
// If there was an error, exit.
if fileerr != nil {
return fileerr
}
// If this is a .pulumi directory, we will skip this by default.
// TODO[pulumi/pulumi#122]: when we support .pulumiignore, this will be customizable.
if f.Name() == workspace.BookkeepingDir {
if f.IsDir() {
return filepath.SkipDir
}
return nil
}
// If this was a directory or a symlink, skip it.
if f.IsDir() || f.Mode()&os.ModeSymlink != 0 {
return nil
}
// Otherwise, add this asset to the list of paths and keep going.
assetPaths = append(assetPaths, filePath)
return nil
}); walkerr != nil {
return nil, walkerr
}
r := &directoryArchiveReader{
directoryPath: path,
assetPaths: assetPaths,
}
return r, nil
}
// Otherwise, it's an archive file, and we will go ahead and open it up and read it.
file, err := os.Open(path)
if err != nil {
return nil, err
}
return readArchive(file, format)
}
func (a *Archive) readURI() (ArchiveReader, error) {
// To read a URI-based archive, fetch the contents remotely and use the extension to pick the format to use.
url, isurl, err := a.GetURIURL()
if err != nil {
return nil, err
}
contract.Assertf(isurl, "Expected a URI-based asset")
format := detectArchiveFormat(url.Path)
if format == NotArchive {
// IDEA: support (a) hints and (b) custom providers that default to certain formats.
return nil, errors.Errorf("file at URL '%v' is not a recognized archive format", url)
}
ar, err := a.openURLStream(url)
if err != nil {
return nil, err
}
return readArchive(ar, format)
}
func (a *Archive) openURLStream(url *url.URL) (io.ReadCloser, error) {
switch s := url.Scheme; s {
case "http", "https":
resp, err := httputil.GetWithRetry(url.String(), http.DefaultClient)
if err != nil {
return nil, err
}
return resp.Body, nil
case "file":
contract.Assert(url.Host == "")
contract.Assert(url.User == nil)
contract.Assert(url.RawQuery == "")
contract.Assert(url.Fragment == "")
return os.Open(url.Path)
default:
return nil, errors.Errorf("Unrecognized or unsupported URI scheme: %v", s)
}
}
// Bytes fetches the archive contents as a byte slices. This is almost certainly the least efficient way to deal with
// the underlying streaming capabilities offered by assets and archives, but can be used in a pinch to interact with
// APIs that demand []bytes.
func (a *Archive) Bytes(format ArchiveFormat) ([]byte, error) {
var data bytes.Buffer
if err := a.Archive(format, &data); err != nil {
return nil, err
}
return data.Bytes(), nil
}
// Archive produces a single archive stream in the desired format. It prefers to return the archive with as little
// copying as is feasible, however if the desired format is different from the source, it will need to translate.
func (a *Archive) Archive(format ArchiveFormat, w io.Writer) error {
// If the source format is the same, just return that.
if sf, ss, err := a.ReadSourceArchive(); sf != NotArchive && sf == format {
if err != nil {
return err
}
_, err := io.Copy(w, ss)
return err
}
switch format {
case TarArchive:
return a.archiveTar(w)
case TarGZIPArchive:
return a.archiveTarGZIP(w)
case ZIPArchive:
return a.archiveZIP(w)
default:
contract.Failf("Illegal archive type: %v", format)
return nil
}
}
// addNextFileToTar adds the next file in the given archive to the given tar file. Returns io.EOF if the archive
// contains no more files.
func addNextFileToTar(r ArchiveReader, tw *tar.Writer) error {
file, data, err := r.Next()
if err != nil {
return err
}
defer contract.IgnoreClose(data)
sz := data.Size()
if err = tw.WriteHeader(&tar.Header{
Name: file,
Mode: 0600,
Size: sz,
}); err != nil {
return err
}
n, err := io.Copy(tw, data)
if err == tar.ErrWriteTooLong {
return errors.Wrap(err, fmt.Sprintf("incorrect blob size for %v: expected %v, got %v", file, sz, n))
}
return err
}
func (a *Archive) archiveTar(w io.Writer) error {
// Open the archive.
reader, err := a.Open()
if err != nil {
return err
}
defer contract.IgnoreClose(reader)
// Now actually emit the contents, file by file.
tw := tar.NewWriter(w)
for err == nil {
err = addNextFileToTar(reader, tw)
}
if err != io.EOF {
return err
}
return tw.Close()
}
func (a *Archive) archiveTarGZIP(w io.Writer) error {
z := gzip.NewWriter(w)
return a.archiveTar(z)
}
// addNextFileToZIP adds the next file in the given archive to the given ZIP file. Returns io.EOF if the archive
// contains no more files.
func addNextFileToZIP(r ArchiveReader, zw *zip.Writer) error {
file, data, err := r.Next()
if err != nil {
return err
}
defer contract.IgnoreClose(data)
fh := &zip.FileHeader{
// These are the two fields set by zw.Create()
Name: file,
Method: zip.Deflate,
}
// Set a nonzero -- but constant -- modification time. Otherwise, some agents (e.g. Azure
// websites) can't extract the resulting archive. The date is comfortably after 1980 because
// the ZIP format includes a date representation that starts at 1980. Use `SetModTime` to
// remain compatible with Go 1.9.
// nolint: megacheck
fh.SetModTime(time.Date(1990, time.January, 1, 0, 0, 0, 0, time.UTC))
fw, err := zw.CreateHeader(fh)
if err != nil {
return err
}
_, err = io.Copy(fw, data)
return err
}
func (a *Archive) archiveZIP(w io.Writer) error {
// Open the archive.
reader, err := a.Open()
if err != nil {
return err
}
defer contract.IgnoreClose(reader)
// Now actually emit the contents, file by file.
zw := zip.NewWriter(w)
for err == nil {
err = addNextFileToZIP(reader, zw)
}
if err != io.EOF {
return err
}
return zw.Close()
}
// ReadSourceArchive returns a stream to the underlying archive, if there is one.
func (a *Archive) ReadSourceArchive() (ArchiveFormat, io.ReadCloser, error) {
if path, ispath := a.GetPath(); ispath {
if format := detectArchiveFormat(path); format != NotArchive {