/
plugins.go
1927 lines (1682 loc) 路 61.6 KB
/
plugins.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-2021, 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 workspace
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"hash"
"io"
"io/fs"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"time"
"github.com/blang/semver"
"github.com/cheggaaa/pb"
"github.com/djherbis/times"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag/colors"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/archive"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/fsutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/httputil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/version"
"github.com/pulumi/pulumi/sdk/v3/nodejs/npm"
"github.com/pulumi/pulumi/sdk/v3/python"
)
const (
windowsGOOS = "windows"
)
var (
enableLegacyPluginBehavior = os.Getenv("PULUMI_ENABLE_LEGACY_PLUGIN_SEARCH") != ""
)
// pluginDownloadURLOverrides is a variable instead of a constant so it can be set using the `-X` `ldflag` at build
// time, if necessary. When non-empty, it's parsed into `pluginDownloadURLOverridesParsed` in `init()`. The expected
// format is `regexp=URL`, and multiple pairs can be specified separated by commas, e.g. `regexp1=URL1,regexp2=URL2`.
//
// For example, when set to "^foo.*=https://foo,^bar.*=https://bar", plugin names that start with "foo" will use
// https://foo as the download URL and names that start with "bar" will use https://bar.
var pluginDownloadURLOverrides string
// pluginDownloadURLOverridesParsed is the parsed array from `pluginDownloadURLOverrides`.
var pluginDownloadURLOverridesParsed pluginDownloadOverrideArray
// pluginDownloadURLOverride represents a plugin download URL override, parsed from `pluginDownloadURLOverrides`.
type pluginDownloadURLOverride struct {
reg *regexp.Regexp // The regex used to match against the plugin's name.
url string // The URL to use for the matched plugin.
}
// pluginDownloadOverrideArray represents an array of overrides.
type pluginDownloadOverrideArray []pluginDownloadURLOverride
// get returns the URL and true if name matches an override's regular expression,
// otherwise an empty string and false.
func (overrides pluginDownloadOverrideArray) get(name string) (string, bool) {
for _, override := range overrides {
if override.reg.MatchString(name) {
return override.url, true
}
}
return "", false
}
func init() {
var err error
if pluginDownloadURLOverridesParsed, err = parsePluginDownloadURLOverrides(pluginDownloadURLOverrides); err != nil {
panic(fmt.Errorf("error parsing `pluginDownloadURLOverrides`: %w", err))
}
}
// parsePluginDownloadURLOverrides parses an overrides string with the expected format `regexp1=URL1,regexp2=URL2`.
func parsePluginDownloadURLOverrides(overrides string) (pluginDownloadOverrideArray, error) {
var result pluginDownloadOverrideArray
if overrides == "" {
return result, nil
}
for _, pair := range strings.Split(overrides, ",") {
split := strings.Split(pair, "=")
if len(split) != 2 || split[0] == "" || split[1] == "" {
return nil, fmt.Errorf("expected format to be \"regexp1=URL1,regexp2=URL2\"; got %q", overrides)
}
reg, err := regexp.Compile(split[0])
if err != nil {
return nil, err
}
result = append(result, pluginDownloadURLOverride{
reg: reg,
url: split[1],
})
}
return result, nil
}
// InstallPluginError is returned by functions that are unable to download and install a plugin
type InstallPluginError struct {
// The name of the plugin
Name string
// The kind of the plugin
Kind PluginKind
// The requested version of the plugin, if any.
Version *semver.Version
// the underlying error that occurred during the download or install
UnderlyingError error
}
func (err *InstallPluginError) Error() string {
if err.Version != nil {
return fmt.Sprintf("Could not automatically download and install %[1]s plugin 'pulumi-%[1]s-%[2]s'"+
"at version v%[3]s, "+
"install the plugin using `pulumi plugin install %[1]s %[2]s v%[3]s`.\n"+
"Underlying error: %[4]s",
err.Kind, err.Name, err.Version.String(), err.UnderlyingError.Error())
}
return fmt.Sprintf("Could not automatically download and install %[1]s plugin 'pulumi-%[1]s-%[2]s', "+
"install the plugin using `pulumi plugin install %[1]s %[2]s`.\n"+
"Underlying error: %[3]s",
err.Kind, err.Name, err.UnderlyingError.Error())
}
// PluginSource deals with downloading a specific version of a plugin, or looking up the latest version of it.
type PluginSource interface {
// Download fetches an io.ReadCloser for this plugin and also returns the size of the response (if known).
Download(
version semver.Version, opSy string, arch string,
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (io.ReadCloser, int64, error)
// GetLatestVersion tries to find the latest version for this plugin. This is currently only supported for
// plugins we can get from github releases.
GetLatestVersion(getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (*semver.Version, error)
}
// getPulumiSource can download a plugin from get.pulumi.com
type getPulumiSource struct {
name string
kind PluginKind
}
func newGetPulumiSource(name string, kind PluginKind) *getPulumiSource {
return &getPulumiSource{name: name, kind: kind}
}
func (source *getPulumiSource) GetLatestVersion(
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (*semver.Version, error) {
return nil, errors.New("GetLatestVersion is not supported for plugins from get.pulumi.com")
}
func (source *getPulumiSource) Download(
version semver.Version, opSy string, arch string,
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (io.ReadCloser, int64, error) {
serverURL := "https://get.pulumi.com/releases/plugins"
logging.V(1).Infof("%s downloading from %s", source.name, serverURL)
serverURL = interpolateURL(serverURL, version, opSy, arch)
serverURL = strings.TrimSuffix(serverURL, "/")
logging.V(1).Infof("%s downloading from %s", source.name, serverURL)
endpoint := fmt.Sprintf("%s/%s",
serverURL,
url.QueryEscape(fmt.Sprintf("pulumi-%s-%s-v%s-%s-%s.tar.gz", source.kind, source.name, version.String(), opSy, arch)))
req, err := buildHTTPRequest(endpoint, "")
if err != nil {
return nil, -1, err
}
return getHTTPResponse(req)
}
// githubSource can download a plugin from github releases
type githubSource struct {
host string
organization string
repository string
name string
kind PluginKind
token string
}
// Creates a new github source adding authentication data in the environment, if it exists
func newGithubSource(url *url.URL, name string, kind PluginKind) (*githubSource, error) {
contract.Assert(url.Scheme == "github")
// 14-03-2022 we stopped looking at GITHUB_PERSONAL_ACCESS_TOKEN and sending basic auth for github and
// instead just look at GITHUB_TOKEN and send in a header. Given GITHUB_PERSONAL_ACCESS_TOKEN was an
// envvar we made up we check to see if it's set here and log a warning. This can be removed after a few
// releases.
if os.Getenv("GITHUB_PERSONAL_ACCESS_TOKEN") != "" {
logging.Warningf("GITHUB_PERSONAL_ACCESS_TOKEN is no longer used for Github authentication, set GITHUB_TOKEN instead")
}
host := url.Host
parts := strings.Split(strings.Trim(url.Path, "/"), "/")
if host == "" {
return nil, fmt.Errorf("github:// url must have a host part, was: %s", url.String())
}
if len(parts) != 1 && len(parts) != 2 {
return nil, fmt.Errorf(
"github:// url must have the format <host>/<organization>[/<repository>], was: %s",
url.String())
}
organization := parts[0]
repository := "pulumi-" + name
if len(parts) == 2 {
repository = parts[1]
}
return &githubSource{
host: host,
organization: organization,
repository: repository,
name: name,
kind: kind,
token: os.Getenv("GITHUB_TOKEN"),
}, nil
}
func (source *githubSource) HasAuthentication() bool {
return source.token != ""
}
func (source *githubSource) GetLatestVersion(
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (*semver.Version, error) {
releaseURL := fmt.Sprintf(
"https://%s/repos/%s/%s/releases/latest",
source.host, source.organization, source.repository)
logging.V(9).Infof("plugin GitHub releases url: %s", releaseURL)
req, err := buildHTTPRequest(releaseURL, source.token)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
resp, length, err := getHTTPResponse(req)
if err != nil {
return nil, err
}
jsonBody, err := ioutil.ReadAll(resp)
if err != nil {
return nil, fmt.Errorf("cannot unmarshal github response len(%d): %s", length, err.Error())
}
release := struct {
TagName string `json:"tag_name"`
}{}
err = json.Unmarshal(jsonBody, &release)
if err != nil {
return nil, err
}
parsedVersion, err := semver.ParseTolerant(release.TagName)
if err != nil {
return nil, fmt.Errorf("invalid plugin semver: %w", err)
}
return &parsedVersion, nil
}
func (source *githubSource) Download(
version semver.Version, opSy string, arch string,
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (io.ReadCloser, int64, error) {
assetName := fmt.Sprintf("pulumi-%s-%s-v%s-%s-%s.tar.gz", source.kind, source.name, version.String(), opSy, arch)
releaseURL := fmt.Sprintf(
"https://%s/repos/%s/%s/releases/tags/v%s",
source.host, source.organization, source.repository, version.String())
logging.V(9).Infof("plugin GitHub releases url: %s", releaseURL)
req, err := buildHTTPRequest(releaseURL, source.token)
if err != nil {
return nil, -1, err
}
req.Header.Set("Accept", "application/json")
resp, length, err := getHTTPResponse(req)
if err != nil {
return nil, -1, err
}
jsonBody, err := ioutil.ReadAll(resp)
if err != nil {
logging.V(9).Infof("cannot unmarshal github response len(%d): %s", length, err.Error())
return nil, -1, err
}
release := struct {
Assets []struct {
Name string `json:"name"`
URL string `json:"url"`
} `json:"assets"`
}{}
err = json.Unmarshal(jsonBody, &release)
if err != nil {
logging.V(9).Infof("github json response: %s", jsonBody)
logging.V(9).Infof("cannot unmarshal github response: %s", err.Error())
return nil, -1, err
}
assetURL := ""
for _, asset := range release.Assets {
if asset.Name == assetName {
assetURL = asset.URL
}
}
if assetURL == "" {
logging.V(9).Infof("github json response: %s", jsonBody)
logging.V(9).Infof("plugin asset '%s' not found", assetName)
return nil, -1, errors.Errorf("plugin asset '%s' not found", assetName)
}
logging.V(1).Infof("%s downloading from %s", source.name, assetURL)
req, err = buildHTTPRequest(assetURL, source.token)
if err != nil {
return nil, -1, err
}
req.Header.Set("Accept", "application/octet-stream")
return getHTTPResponse(req)
}
// pluginURLSource can download a plugin from a given PluginDownloadURL, it doesn't support GetLatestVersion
type pluginURLSource struct {
name string
kind PluginKind
pluginDownloadURL string
}
func newPluginURLSource(name string, kind PluginKind, pluginDownloadURL string) *pluginURLSource {
return &pluginURLSource{
name: name,
kind: kind,
pluginDownloadURL: pluginDownloadURL,
}
}
func (source *pluginURLSource) GetLatestVersion(
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (*semver.Version, error) {
return nil, errors.New("GetLatestVersion is not supported for plugins using PluginDownloadURL")
}
func (source *pluginURLSource) Download(
version semver.Version, opSy string, arch string,
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (io.ReadCloser, int64, error) {
serverURL := source.pluginDownloadURL
logging.V(1).Infof("%s downloading from %s", source.name, serverURL)
serverURL = interpolateURL(serverURL, version, opSy, arch)
serverURL = strings.TrimSuffix(serverURL, "/")
logging.V(1).Infof("%s downloading from %s", source.name, serverURL)
endpoint := fmt.Sprintf("%s/%s",
serverURL,
url.QueryEscape(fmt.Sprintf("pulumi-%s-%s-v%s-%s-%s.tar.gz", source.kind, source.name, version.String(), opSy, arch)))
req, err := buildHTTPRequest(endpoint, "")
if err != nil {
return nil, -1, err
}
return getHTTPResponse(req)
}
// fallbackSource handles our current complicated default logic of trying the pulumi public github, then maybe
// the users private github, then get.pulumi.com
type fallbackSource struct {
name string
kind PluginKind
}
func newFallbackSource(name string, kind PluginKind) *fallbackSource {
return &fallbackSource{
name: name,
kind: kind,
}
}
func urlMustParse(rawURL string) *url.URL {
url, err := url.Parse(rawURL)
contract.AssertNoError(err)
return url
}
func (source *fallbackSource) GetLatestVersion(
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (*semver.Version, error) {
// Try and get this package from our public pulumi github
public, err := newGithubSource(urlMustParse("github://api.github.com/pulumi"), source.name, source.kind)
if err != nil {
return nil, err
}
version, err := public.GetLatestVersion(getHTTPResponse)
if err != nil {
return nil, err
}
return version, nil
}
func (source *fallbackSource) Download(
version semver.Version, opSy string, arch string,
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (io.ReadCloser, int64, error) {
// Try and get this package from public pulumi github
public, err := newGithubSource(urlMustParse("github://api.github.com/pulumi"), source.name, source.kind)
if err != nil {
return nil, -1, err
}
resp, length, err := public.Download(version, opSy, arch, getHTTPResponse)
if err == nil {
return resp, length, nil
}
// Fallback to get.pulumi.com
pulumi := newGetPulumiSource(source.name, source.kind)
return pulumi.Download(version, opSy, arch, getHTTPResponse)
}
type checksumError struct {
expected []byte
actual []byte
}
func (err *checksumError) Error() string {
return fmt.Sprintf("invalid checksum, expected %x, actual %x", err.expected, err.actual)
}
// checksumSource will validate that the archive downloaded from the inner source matches a checksum
type checksumSource struct {
source PluginSource
checksum map[string][]byte
}
func newChecksumSource(source PluginSource, checksum map[string][]byte) *checksumSource {
return &checksumSource{
source: source,
checksum: checksum,
}
}
func (source *checksumSource) GetLatestVersion(
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (*semver.Version, error) {
return source.source.GetLatestVersion(getHTTPResponse)
}
type checksumReader struct {
checksum []byte
io io.ReadCloser
hasher hash.Hash
}
func (reader *checksumReader) Read(p []byte) (int, error) {
n, err := reader.io.Read(p)
if err != nil {
if err == io.EOF {
// Check the checksum matches
actualChecksum := reader.hasher.Sum(nil)
if !bytes.Equal(reader.checksum, actualChecksum) {
return n, &checksumError{expected: reader.checksum, actual: actualChecksum}
}
}
return n, err
}
m, err := reader.hasher.Write(p[0:n])
contract.AssertNoError(err)
contract.Assert(m == n)
return n, nil
}
func (reader *checksumReader) Close() error {
return reader.io.Close()
}
func (source *checksumSource) Download(
version semver.Version, opSy string, arch string,
getHTTPResponse func(*http.Request) (io.ReadCloser, int64, error)) (io.ReadCloser, int64, error) {
checksum := source.checksum[fmt.Sprintf("%s-%s", opSy, arch)]
response, length, err := source.source.Download(version, opSy, arch, getHTTPResponse)
if err != nil {
return nil, -1, err
}
return &checksumReader{
checksum: checksum,
hasher: sha256.New(),
io: response,
}, length, nil
}
// ProjectPlugin Information about a locally installed plugin specified by the project.
type ProjectPlugin struct {
Name string // the simple name of the plugin.
Kind PluginKind // the kind of the plugin (language, resource, etc).
Version *semver.Version // the plugin's semantic version, if present.
Path string // the path that a plugin is to be loaded from (this will always be a directory)
}
// Spec Return a PluginSpec object for this project plugin.
func (pp ProjectPlugin) Spec() PluginSpec {
return PluginSpec{
Name: pp.Name,
Kind: pp.Kind,
Version: pp.Version,
}
}
// PluginSpec provides basic specification for a plugin.
type PluginSpec struct {
Name string // the simple name of the plugin.
Kind PluginKind // the kind of the plugin (language, resource, etc).
Version *semver.Version // the plugin's semantic version, if present.
PluginDownloadURL string // an optional server to use when downloading this plugin.
PluginDir string // if set, will be used as the root plugin dir instead of ~/.pulumi/plugins.
// if set will be used to validate the plugin downloaded matches. This is keyed by "$os-$arch", e.g. "linux-x64".
Checksums map[string][]byte
}
// Dir gets the expected plugin directory for this plugin.
func (spec PluginSpec) Dir() string {
dir := fmt.Sprintf("%s-%s", spec.Kind, spec.Name)
if spec.Version != nil {
dir = fmt.Sprintf("%s-v%s", dir, spec.Version.String())
}
return dir
}
// File gets the expected filename for this plugin, excluding any platform specific suffixes (e.g. ".exe" on
// windows).
func (spec PluginSpec) File() string {
return fmt.Sprintf("pulumi-%s-%s", spec.Kind, spec.Name)
}
// DirPath returns the directory where this plugin should be installed.
func (spec PluginSpec) DirPath() (string, error) {
var err error
dir := spec.PluginDir
if dir == "" {
dir, err = GetPluginDir()
if err != nil {
return "", err
}
}
return filepath.Join(dir, spec.Dir()), nil
}
// LockFilePath returns the full path to the plugin's lock file used during installation
// to prevent concurrent installs.
func (spec PluginSpec) LockFilePath() (string, error) {
dir, err := spec.DirPath()
if err != nil {
return "", err
}
return fmt.Sprintf("%s.lock", dir), nil
}
// PartialFilePath returns the full path to the plugin's partial file used during installation
// to indicate installation of the plugin hasn't completed yet.
func (spec PluginSpec) PartialFilePath() (string, error) {
dir, err := spec.DirPath()
if err != nil {
return "", err
}
return fmt.Sprintf("%s.partial", dir), nil
}
func (spec PluginSpec) String() string {
var version string
if v := spec.Version; v != nil {
version = fmt.Sprintf("-%s", v)
}
return spec.Name + version
}
// PluginInfo provides basic information about a plugin. Each plugin gets installed into a system-wide
// location, by default `~/.pulumi/plugins/<kind>-<name>-<version>/`. A plugin may contain multiple files,
// however the primary loadable executable must be named `pulumi-<kind>-<name>`.
type PluginInfo struct {
Name string // the simple name of the plugin.
Path string // the path that a plugin was loaded from (this will always be a directory)
Kind PluginKind // the kind of the plugin (language, resource, etc).
Version *semver.Version // the plugin's semantic version, if present.
Size int64 // the size of the plugin, in bytes.
InstallTime time.Time // the time the plugin was installed.
LastUsedTime time.Time // the last time the plugin was used.
SchemaPath string // if set, used as the path for loading and caching the schema
SchemaTime time.Time // if set and newer than the file at SchemaPath, used to invalidate a cached schema
}
// Spec returns the PluginSpec for this PluginInfo
func (info *PluginInfo) Spec() PluginSpec {
return PluginSpec{Name: info.Name, Kind: info.Kind, Version: info.Version}
}
func (info PluginInfo) String() string {
var version string
if v := info.Version; v != nil {
version = fmt.Sprintf("-%s", v)
}
return info.Name + version
}
// Delete removes the plugin from the cache. It also deletes any supporting files in the cache, which includes
// any files that contain the same prefix as the plugin itself.
func (info *PluginInfo) Delete() error {
dir := info.Path
if err := os.RemoveAll(dir); err != nil {
return err
}
// Attempt to delete any leftover .partial or .lock files.
// Don't fail the operation if we can't delete these.
contract.IgnoreError(os.Remove(fmt.Sprintf("%s.partial", dir)))
contract.IgnoreError(os.Remove(fmt.Sprintf("%s.lock", dir)))
return nil
}
// SetFileMetadata adds extra metadata from the given file, representing this plugin's directory.
func (info *PluginInfo) SetFileMetadata(path string) error {
// Get the file info.
file, err := os.Stat(path)
if err != nil {
return err
}
// Next, get the size from the directory (or, if there is none, just the file).
size, err := getPluginSize(path)
if err == nil {
info.Size = size
} else {
logging.V(6).Infof("unable to get plugin dir size for %s: %v", path, err)
}
// Next get the access times from the plugin binary itself.
tinfo := times.Get(file)
if tinfo.HasChangeTime() {
info.InstallTime = tinfo.ChangeTime()
} else {
info.InstallTime = tinfo.ModTime()
}
info.LastUsedTime = tinfo.AccessTime()
if info.Kind == ResourcePlugin {
info.SchemaPath = filepath.Join(filepath.Dir(path), "schema-"+info.Name+".json")
info.SchemaTime = tinfo.ModTime()
}
return nil
}
func interpolateURL(serverURL string, version semver.Version, os, arch string) string {
replacer := strings.NewReplacer(
"${VERSION}", url.QueryEscape(version.String()),
"${OS}", url.QueryEscape(os),
"${ARCH}", url.QueryEscape(arch))
return replacer.Replace(serverURL)
}
func (spec PluginSpec) GetSource() (PluginSource, error) {
baseSource, err := func() (PluginSource, error) {
// The plugin has a set URL use that.
if spec.PluginDownloadURL != "" {
// Support schematised URLS if the URL has a "schema" part we recognize
url, err := url.Parse(spec.PluginDownloadURL)
if err != nil {
return nil, err
}
if url.Scheme == "github" {
return newGithubSource(url, spec.Name, spec.Kind)
}
return newPluginURLSource(spec.Name, spec.Kind, spec.PluginDownloadURL), nil
}
// If the plugin name matches an override, download the plugin from the override URL.
if url, ok := pluginDownloadURLOverridesParsed.get(spec.Name); ok {
return newPluginURLSource(spec.Name, spec.Kind, url), nil
}
// Use our default fallback behaviour of github then get.pulumi.com
return newFallbackSource(spec.Name, spec.Kind), nil
}()
if err != nil {
return nil, err
}
if len(spec.Checksums) != 0 {
return newChecksumSource(baseSource, spec.Checksums), nil
}
return baseSource, nil
}
// GetLatestVersion tries to find the latest version for this plugin. This is currently only supported for
// plugins we can get from github releases.
func (spec PluginSpec) GetLatestVersion() (*semver.Version, error) {
source, err := spec.GetSource()
if err != nil {
return nil, err
}
return source.GetLatestVersion(getHTTPResponse)
}
// Download fetches an io.ReadCloser for this plugin and also returns the size of the response (if known).
func (spec PluginSpec) Download() (io.ReadCloser, int64, error) {
// Figure out the OS/ARCH pair for the download URL.
var opSy string
switch runtime.GOOS {
case "darwin", "linux", "windows":
opSy = runtime.GOOS
default:
return nil, -1, errors.Errorf("unsupported plugin OS: %s", runtime.GOOS)
}
var arch string
switch runtime.GOARCH {
case "amd64", "arm64":
arch = runtime.GOARCH
default:
return nil, -1, errors.Errorf("unsupported plugin architecture: %s", runtime.GOARCH)
}
// The plugin version is necessary for the endpoint. If it's not present, return an error.
if spec.Version == nil {
return nil, -1, errors.Errorf("unknown version for plugin %s", spec.Name)
}
source, err := spec.GetSource()
if err != nil {
return nil, -1, err
}
return source.Download(*spec.Version, opSy, arch, getHTTPResponse)
}
func buildHTTPRequest(pluginEndpoint string, token string) (*http.Request, error) {
req, err := http.NewRequest("GET", pluginEndpoint, nil)
if err != nil {
return nil, err
}
userAgent := fmt.Sprintf("pulumi-cli/1 (%s; %s)", version.Version, runtime.GOOS)
req.Header.Set("User-Agent", userAgent)
if token != "" {
req.Header.Set("Authorization", fmt.Sprintf("token %s", token))
}
return req, nil
}
func getHTTPResponse(req *http.Request) (io.ReadCloser, int64, error) {
logging.V(9).Infof("full plugin download url: %s", req.URL)
// This logs at level 11 because it could include authentication headers, we reserve log level 11 for
// detailed api logs that may include credentials.
logging.V(11).Infof("plugin install request headers: %v", req.Header)
resp, err := httputil.DoWithRetry(req, http.DefaultClient)
if err != nil {
return nil, -1, err
}
// As above this might include authentication information, but also to be consistent at what level headers
// print at.
logging.V(11).Infof("plugin install response headers: %v", resp.Header)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, -1, newDownloadError(resp.StatusCode, req.URL)
}
return resp.Body, resp.ContentLength, nil
}
// downloadError is an error that happened during the HTTP download of a plugin.
type downloadError struct {
msg string
code int
}
func (e *downloadError) Error() string {
return e.msg
}
func (e *downloadError) Code() int {
return e.code
}
// Create a new downloadError with a message that indicates GITHUB_TOKEN should be set.
func newGithubPrivateRepoError(statusCode int, url *url.URL) error {
return &downloadError{
code: statusCode,
msg: fmt.Sprintf("%d HTTP error fetching plugin from %s. "+
"If this is a private GitHub repository, try "+
"providing a token via the GITHUB_TOKEN environment variable. "+
"See: https://github.com/settings/tokens",
statusCode, url),
}
}
// Create a new downloadError.
func newDownloadError(statusCode int, url *url.URL) error {
if url.Host == "api.github.com" && statusCode == 404 {
return newGithubPrivateRepoError(statusCode, url)
}
return &downloadError{
code: statusCode,
msg: fmt.Sprintf("%d HTTP error fetching plugin from %s", statusCode, url),
}
}
// installLock acquires a file lock used to prevent concurrent installs.
func (spec PluginSpec) installLock() (unlock func(), err error) {
finalDir, err := spec.DirPath()
if err != nil {
return nil, err
}
lockFilePath := fmt.Sprintf("%s.lock", finalDir)
if err := os.MkdirAll(filepath.Dir(lockFilePath), 0700); err != nil {
return nil, errors.Wrap(err, "creating plugin root")
}
mutex := fsutil.NewFileMutex(lockFilePath)
if err := mutex.Lock(); err != nil {
return nil, err
}
return func() {
contract.IgnoreError(mutex.Unlock())
}, nil
}
// Install installs a plugin's tarball into the cache. See InstallWithContext for details.
func (spec PluginSpec) Install(tgz io.ReadCloser, reinstall bool) error {
return spec.InstallWithContext(context.Background(), tarPlugin{tgz}, reinstall)
}
// DownloadToFile downloads the given PluginInfo to a temporary file and returns that temporary file.
// This has some retry logic to re-attempt the download if it errors for any reason.
func DownloadToFile(
pkgPlugin PluginSpec,
wrapper func(stream io.ReadCloser, size int64) io.ReadCloser,
retry func(err error, attempt int, limit int, delay time.Duration)) (*os.File, error) {
// This is an internal helper that's pretty much just a copy of io.Copy except it returns read and
// write errors separately. We only want to retry if the read (i.e. download) fails, if the write
// fails thats probably due to file permissions or space limitations and there's no point retrying.
copyBuffer := func(dst io.Writer, src io.Reader) (written int64, readErr error, writeErr error) {
size := 32 * 1024
if l, ok := src.(*io.LimitedReader); ok && int64(size) > l.N {
if l.N < 1 {
size = 1
} else {
size = int(l.N)
}
}
buf := make([]byte, size)
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw < 0 || nr < nw {
nw = 0
if ew == nil {
ew = errors.New("invalid write result")
}
}
written += int64(nw)
if ew != nil {
return written, nil, ew
}
if nr != nw {
return written, nil, io.ErrShortWrite
}
}
if er != nil {
if er == io.EOF {
er = nil
}
return written, er, nil
}
}
}
tryDownload := func(dst io.WriteCloser) (error, error) {
defer dst.Close()
tarball, expectedByteCount, err := pkgPlugin.Download()
if err != nil {
return err, nil
}
if wrapper != nil {
tarball = wrapper(tarball, expectedByteCount)
}
defer tarball.Close()
copiedByteCount, readErr, writerErr := copyBuffer(dst, tarball)
if readErr != nil || writerErr != nil {
return readErr, writerErr
}
if copiedByteCount != expectedByteCount {
return nil, fmt.Errorf("expected %d bytes but copied %d when downloading plugin %s",
expectedByteCount, copiedByteCount, pkgPlugin)
}
return nil, nil
}
tryDownloadToFile := func() (string, error, error) {
file, err := ioutil.TempFile("" /* default temp dir */, "pulumi-plugin-tar")
if err != nil {
return "", nil, err
}
readErr, writeErr := tryDownload(file)
if readErr != nil || writeErr != nil {
err2 := os.Remove(file.Name())
if err2 != nil {
// only one of readErr or writeErr will be set
err := readErr
if err == nil {
err = writeErr
}
return "", nil, fmt.Errorf("error while removing tempfile: %v. Context: %w", err2, err)
}
return "", readErr, writeErr
}
return file.Name(), nil, nil
}
downloadToFileWithRetry := func() (string, error) {
delay := 80 * time.Millisecond
for attempt := 0; ; attempt++ {
tempFile, readErr, writeErr := tryDownloadToFile()
if readErr == nil && writeErr == nil {
return tempFile, nil
}
if writeErr != nil {
return "", writeErr
}
// If the readErr is a checksum error don't retry
if _, ok := readErr.(*checksumError); ok {
return "", readErr
}
// Don't retry, since the request was processed and rejected.
if err, ok := readErr.(*downloadError); ok && (err.Code() == 404 || err.Code() == 403) {
return "", readErr
}
// Don't attempt more than 5 times
attempts := 5
if readErr != nil && attempt >= attempts {
return "", readErr
}
if retry != nil {
retry(readErr, attempt+1, attempts, delay)
}
time.Sleep(delay)
delay = delay * 2
}
}
tarball, err := downloadToFileWithRetry()
if err != nil {
return nil, fmt.Errorf("failed to download plugin: %s: %w", pkgPlugin, err)
}
reader, err := os.Open(tarball)
if err != nil {
return nil, fmt.Errorf("failed to open downloaded plugin: %s: %w", pkgPlugin, err)
}
return reader, nil