-
Notifications
You must be signed in to change notification settings - Fork 113
/
provider.go
3376 lines (2976 loc) · 120 KB
/
provider.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-2023, 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 provider
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"time"
jsonpatch "github.com/evanphx/json-patch"
"github.com/golang/protobuf/ptypes/empty"
pbempty "github.com/golang/protobuf/ptypes/empty"
structpb "github.com/golang/protobuf/ptypes/struct"
checkjob "github.com/pulumi/cloud-ready-checks/pkg/kubernetes/job"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/await"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/clients"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/cluster"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/gen"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/host"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/kinds"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/logging"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/metadata"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/openapi"
providerresource "github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/provider/resource"
"github.com/pulumi/pulumi-kubernetes/provider/v4/pkg/ssa"
pulumischema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
"github.com/pulumi/pulumi/pkg/v3/resource/provider"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
logger "github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/rpcutil/rpcerror"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
helmcli "helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/helmpath"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientapi "k8s.io/client-go/tools/clientcmd/api"
k8sopenapi "k8s.io/kubectl/pkg/util/openapi"
"k8s.io/utils/ptr"
"sigs.k8s.io/yaml"
)
// --------------------------------------------------------------------------
// Kubernetes resource provider.
//
// Implements functionality for the Pulumi Kubernetes Resource Provider. This code is responsible
// for producing sensible responses for the gRPC server to send back to a client when it requests
// something to do with the Kubernetes resources it's meant to manage.
// --------------------------------------------------------------------------
const (
streamInvokeList = "kubernetes:kubernetes:list"
streamInvokeWatch = "kubernetes:kubernetes:watch"
streamInvokePodLogs = "kubernetes:kubernetes:podLogs"
invokeDecodeYaml = "kubernetes:yaml:decode"
invokeHelmTemplate = "kubernetes:helm:template"
invokeKustomize = "kubernetes:kustomize:directory"
lastAppliedConfigKey = "kubectl.kubernetes.io/last-applied-configuration"
initialAPIVersionKey = "__initialApiVersion"
fieldManagerKey = "__fieldManager"
secretKind = "Secret"
)
type cancellationContext struct {
context context.Context
cancel context.CancelFunc
}
func makeCancellationContext() *cancellationContext {
ctx, cancel := context.WithCancel(context.Background())
return &cancellationContext{
context: ctx,
cancel: cancel,
}
}
type kubeOpts struct {
rejectUnknownResources bool
}
type kubeProvider struct {
pulumirpc.UnimplementedResourceProviderServer
host host.HostClient
canceler *cancellationContext
name string
version string
pulumiSchema []byte
terraformMapping []byte
providerPackage string
opts kubeOpts
defaultNamespace string
deleteUnreachable bool
skipUpdateUnreachable bool
enableConfigMapMutable bool
enableSecrets bool
suppressDeprecationWarnings bool
suppressHelmHookWarnings bool
serverSideApplyMode bool
helmDriver string
helmPluginsPath string
helmRegistryConfigPath string
helmRepositoryConfigPath string
helmRepositoryCache string
helmSettings *helmcli.EnvSettings
helmReleaseProvider customResourceProvider
yamlRenderMode bool
yamlDirectory string
clusterUnreachable bool // Kubernetes cluster is unreachable.
clusterUnreachableReason string // Detailed error message if cluster is unreachable.
makeClient func(context.Context, *rest.Config) (*clients.DynamicClientSet, *clients.LogClient, error)
clientSet *clients.DynamicClientSet
logClient *clients.LogClient
k8sVersion cluster.ServerVersion
resources k8sopenapi.Resources
resourcesMutex sync.RWMutex
resourceProviders map[string]providerresource.ResourceProviderFactory
}
var _ pulumirpc.ResourceProviderServer = (*kubeProvider)(nil)
func makeKubeProvider(
host host.HostClient, name, version string, pulumiSchema, terraformMapping []byte,
) (*kubeProvider, error) {
return &kubeProvider{
host: host,
canceler: makeCancellationContext(),
name: name,
version: version,
pulumiSchema: pulumiSchema,
terraformMapping: terraformMapping,
providerPackage: name,
enableSecrets: false,
suppressDeprecationWarnings: false,
deleteUnreachable: false,
skipUpdateUnreachable: false,
makeClient: makeClient,
resourceProviders: resourceProviders,
}, nil
}
// makeClient makes a client to connect to a Kubernetes cluster using the given config.
// ctx is a cancellation context that may be used to cancel any subsequent requests made by the clients.
func makeClient(ctx context.Context, config *rest.Config) (*clients.DynamicClientSet, *clients.LogClient, error) {
cs, err := clients.NewDynamicClientSet(config)
if err != nil {
return nil, nil, err
}
lc, err := clients.MakeLogClient(ctx, config)
if err != nil {
return nil, nil, err
}
return cs, lc, nil
}
func (k *kubeProvider) getResources() (k8sopenapi.Resources, error) {
k.resourcesMutex.RLock()
rs := k.resources
k.resourcesMutex.RUnlock()
if rs != nil {
return rs, nil
}
k.resourcesMutex.Lock()
defer k.resourcesMutex.Unlock()
rs, err := openapi.GetResourceSchemasForClient(k.clientSet.DiscoveryClientCached)
if err != nil {
return nil, err
}
k.resources = rs
return k.resources, nil
}
func (k *kubeProvider) invalidateResources() {
k.resourcesMutex.Lock()
defer k.resourcesMutex.Unlock()
k.resources = nil
}
// Call dynamically executes a method in the provider associated with a component resource.
func (k *kubeProvider) Call(ctx context.Context, req *pulumirpc.CallRequest) (*pulumirpc.CallResponse, error) {
return nil, status.Error(codes.Unimplemented, "Call is not yet implemented")
}
// GetMapping fetches the mapping for this resource provider, if any. A provider should return an empty
// response (not an error) if it doesn't have a mapping for the given key.
func (k *kubeProvider) GetMapping(ctx context.Context, request *pulumirpc.GetMappingRequest) (*pulumirpc.GetMappingResponse, error) {
// We only return a mapping for terraform
if request.Key != "terraform" {
// an empty response means no mapping, by design we don't return an error here
return &pulumirpc.GetMappingResponse{}, nil
}
return &pulumirpc.GetMappingResponse{
Provider: "kubernetes",
Data: k.terraformMapping,
}, nil
}
// GetSchema returns the JSON-encoded schema for this provider's package.
func (k *kubeProvider) GetSchema(ctx context.Context, req *pulumirpc.GetSchemaRequest) (*pulumirpc.GetSchemaResponse, error) {
if v := req.GetVersion(); v != 0 {
return nil, fmt.Errorf("unsupported schema version %d", v)
}
return &pulumirpc.GetSchemaResponse{Schema: string(k.pulumiSchema)}, nil
}
// CheckConfig validates the configuration for this provider.
func (k *kubeProvider) CheckConfig(ctx context.Context, req *pulumirpc.CheckRequest) (*pulumirpc.CheckResponse, error) {
urn := resource.URN(req.GetUrn())
label := fmt.Sprintf("%s.CheckConfig(%s)", k.label(), urn)
logger.V(9).Infof("%s executing", label)
news, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.news", label),
KeepUnknowns: true,
SkipNulls: true,
})
if err != nil {
return nil, fmt.Errorf("CheckConfig failed because of malformed resource inputs: %w", err)
}
truthyValue := func(argName resource.PropertyKey, props resource.PropertyMap) bool {
if arg := props[argName]; arg.HasValue() {
switch {
case arg.IsString() && len(arg.StringValue()) > 0:
return true
case arg.IsBool() && arg.BoolValue():
return true
default:
return false
}
}
return false
}
strictMode := false
if pConfig, ok := k.loadPulumiConfig(); ok {
if v, ok := pConfig["strictMode"]; ok {
if v, ok := v.(string); ok {
strictMode = v == "true"
}
}
}
if v := news["strictMode"]; v.HasValue() && v.IsString() {
strictMode = v.StringValue() == "true"
}
if strictMode && providers.IsProviderType(urn.Type()) {
var failures []*pulumirpc.CheckFailure
if providers.IsDefaultProvider(urn) {
failures = append(failures, &pulumirpc.CheckFailure{
Reason: fmt.Sprintf("strict mode prohibits default provider"),
})
}
if v := news["kubeconfig"]; !v.HasValue() || v.StringValue() == "" {
failures = append(failures, &pulumirpc.CheckFailure{
Property: "kubeconfig",
Reason: fmt.Sprintf(`strict mode requires Provider "kubeconfig" argument`),
})
}
if v := news["context"]; !v.HasValue() || v.StringValue() == "" {
failures = append(failures, &pulumirpc.CheckFailure{
Property: "context",
Reason: fmt.Sprintf(`strict mode requires Provider "context" argument`),
})
}
if len(failures) > 0 {
return &pulumirpc.CheckResponse{Inputs: req.GetNews(), Failures: failures}, nil
}
}
renderYamlEnabled := truthyValue("renderYamlToDirectory", news)
errTemplate := `%q arg is not compatible with "renderYamlToDirectory" arg`
if renderYamlEnabled {
var failures []*pulumirpc.CheckFailure
if truthyValue("cluster", news) {
failures = append(failures, &pulumirpc.CheckFailure{
Property: "cluster",
Reason: fmt.Sprintf(errTemplate, "cluster"),
})
}
if truthyValue("context", news) {
failures = append(failures, &pulumirpc.CheckFailure{
Property: "context",
Reason: fmt.Sprintf(errTemplate, "context"),
})
}
if truthyValue("kubeconfig", news) {
failures = append(failures, &pulumirpc.CheckFailure{
Property: "kubeconfig",
Reason: fmt.Sprintf(errTemplate, "kubeconfig"),
})
}
if len(failures) > 0 {
return &pulumirpc.CheckResponse{Inputs: req.GetNews(), Failures: failures}, nil
}
}
return &pulumirpc.CheckResponse{Inputs: req.GetNews()}, nil
}
// DiffConfig diffs the configuration for this provider.
func (k *kubeProvider) DiffConfig(ctx context.Context, req *pulumirpc.DiffRequest) (*pulumirpc.DiffResponse, error) {
urn := resource.URN(req.GetUrn())
label := fmt.Sprintf("%s.DiffConfig(%s)", k.label(), urn)
logger.V(9).Infof("%s executing", label)
olds, err := plugin.UnmarshalProperties(req.GetOlds(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.olds", label),
KeepUnknowns: true,
SkipNulls: true,
})
if err != nil {
return nil, err
}
news, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.news", label),
KeepUnknowns: true,
SkipNulls: true,
})
if err != nil {
return nil, fmt.Errorf("DiffConfig failed because of malformed resource inputs: %w", err)
}
// We can't tell for sure if a computed value has changed, so we make the conservative choice
// and force a replacement. Note that getActiveClusterFromConfig relies on all three of the below properties.
for _, key := range []resource.PropertyKey{"kubeconfig", "context", "cluster"} {
if news[key].IsComputed() {
return &pulumirpc.DiffResponse{
Changes: pulumirpc.DiffResponse_DIFF_SOME,
Diffs: []string{string(key)},
Replaces: []string{string(key)},
}, nil
}
}
var diffs, replaces []string
oldConfig, err := parseKubeconfigPropertyValue(olds["kubeconfig"])
if err != nil {
return nil, err
}
newConfig, err := parseKubeconfigPropertyValue(news["kubeconfig"])
if err != nil {
return nil, err
}
// Check for differences in provider overrides.
diff := olds.Diff(news)
for _, k := range diff.ChangedKeys() {
diffs = append(diffs, string(k))
// Handle any special cases.
switch k {
case "renderYamlToDirectory":
// If the render directory changes, all the manifests will be replaced.
replaces = append(replaces, "renderYamlToDirectory")
}
}
// In general, it's not possible to tell from a kubeconfig if the k8s cluster it points to has
// changed. k8s clusters do not have a well defined identity, so the best we can do is check
// if the settings for the active cluster have changed. This is not a foolproof method; a trivial
// counterexample is changing the load balancer or DNS entry pointing to the same cluster.
//
// Given this limitation, we try to strike a reasonable balance by planning a replacement iff
// the active cluster in the kubeconfig changes. This could still plan an erroneous replacement,
// but should work for the majority of cases.
//
// The alternative of ignoring changes to the kubeconfig is untenable; if the k8s cluster has
// changed, any dependent resources must be recreated, and ignoring changes prevents that from
// happening.
oldActiveCluster, oldFound := getActiveClusterFromConfig(oldConfig, olds)
activeCluster, found := getActiveClusterFromConfig(newConfig, news)
if !oldFound || !found {
// The config is either ambient or invalid, so we can't draw any conclusions.
} else if !reflect.DeepEqual(oldActiveCluster, activeCluster) {
// one of these properties must have changed for the active cluster to change.
for _, key := range []string{"kubeconfig", "context", "cluster"} {
if slices.Contains(diffs, key) {
replaces = append(replaces, key)
}
}
}
logger.V(7).Infof("%s: diffs %v / replaces %v", label, diffs, replaces)
if len(diffs) > 0 || len(replaces) > 0 {
return &pulumirpc.DiffResponse{
Changes: pulumirpc.DiffResponse_DIFF_SOME,
Diffs: diffs,
Replaces: replaces,
}, nil
}
return &pulumirpc.DiffResponse{
Changes: pulumirpc.DiffResponse_DIFF_NONE,
}, nil
}
// Configure configures the resource provider with "globals" that control its behavior.
func (k *kubeProvider) Configure(_ context.Context, req *pulumirpc.ConfigureRequest) (*pulumirpc.ConfigureResponse, error) {
const trueStr = "true"
// Configure Helm settings based on the ambient Helm environment,
// using the provider configuration as overrides.
helmSettings := helmcli.New()
helmFlags := helmSettings.RESTClientGetter().(*genericclioptions.ConfigFlags)
helmSettings.Debug = true // enable verbose logging (piped to glog at level 6)
vars := req.GetVariables()
//
// Set simple configuration settings.
//
k.opts = kubeOpts{
rejectUnknownResources: vars["kubernetes:config:rejectUnknownResources"] == trueStr,
}
k.enableSecrets = req.GetAcceptSecrets()
//
// Configure client-go using provided or ambient kubeconfig file.
//
if defaultNamespace := vars["kubernetes:config:namespace"]; defaultNamespace != "" {
k.defaultNamespace = defaultNamespace
helmSettings.SetNamespace(defaultNamespace)
logger.V(9).Infof("namespace set to %v", defaultNamespace)
}
// Compute config overrides.
overrides := &clientcmd.ConfigOverrides{
Context: clientapi.Context{
Cluster: vars["kubernetes:config:cluster"],
Namespace: k.defaultNamespace,
},
CurrentContext: vars["kubernetes:config:context"],
}
if overrides.Context.Cluster != "" {
helmFlags.ClusterName = &overrides.Context.Cluster
}
if overrides.CurrentContext != "" {
helmSettings.KubeContext = overrides.CurrentContext
}
deleteUnreachable := func() bool {
// If the provider flag is set, use that value to determine behavior. This will override the ENV var.
if enabled, exists := vars["kubernetes:config:deleteUnreachable"]; exists {
return enabled == trueStr
}
// If the provider flag is not set, fall back to the ENV var.
if enabled, exists := os.LookupEnv("PULUMI_K8S_DELETE_UNREACHABLE"); exists {
return enabled == trueStr
}
// Default to false.
return false
}
if deleteUnreachable() {
k.deleteUnreachable = true
}
skipUpdateUnreachable := func() bool {
// If the provider flag is set, use that value to determine behavior. This will override the ENV var.
if enabled, exists := vars["kubernetes:config:skipUpdateUnreachable"]; exists {
return enabled == trueStr
}
// If the provider flag is not set, fall back to the ENV var.
if enabled, exists := os.LookupEnv("PULUMI_K8S_SKIP_UPDATE_UNREACHABLE"); exists {
return enabled == trueStr
}
// Default to false.
return false
}
if skipUpdateUnreachable() {
k.skipUpdateUnreachable = true
}
enableServerSideApply := func() bool {
// If the provider flag is set, use that value to determine behavior. This will override the ENV var.
if enabled, exists := vars["kubernetes:config:enableServerSideApply"]; exists {
return enabled == trueStr
}
// If the provider flag is not set, fall back to the ENV var.
if enabled, exists := os.LookupEnv("PULUMI_K8S_ENABLE_SERVER_SIDE_APPLY"); exists {
return enabled == trueStr
}
// Default to true.
return true
}
if enableServerSideApply() {
k.serverSideApplyMode = true
}
enableConfigMapMutable := func() bool {
// If the provider flag is set, use that value to determine behavior. This will override the ENV var.
if enabled, exists := vars["kubernetes:config:enableConfigMapMutable"]; exists {
return enabled == trueStr
}
// If the provider flag is not set, fall back to the ENV var.
if enabled, exists := os.LookupEnv("PULUMI_K8S_ENABLE_CONFIGMAP_MUTABLE"); exists {
return enabled == trueStr
}
// Default to false.
return false
}
if enableConfigMapMutable() {
k.enableConfigMapMutable = true
}
suppressDeprecationWarnings := func() bool {
// If the provider flag is set, use that value to determine behavior. This will override the ENV var.
if enabled, exists := vars["kubernetes:config:suppressDeprecationWarnings"]; exists {
return enabled == trueStr
}
// If the provider flag is not set, fall back to the ENV var.
if enabled, exists := os.LookupEnv("PULUMI_K8S_SUPPRESS_DEPRECATION_WARNINGS"); exists {
return enabled == trueStr
}
// Default to false.
return false
}
if suppressDeprecationWarnings() {
k.suppressDeprecationWarnings = true
}
suppressHelmHookWarnings := func() bool {
// If the provider flag is set, use that value to determine behavior. This will override the ENV var.
if enabled, exists := vars["kubernetes:config:suppressHelmHookWarnings"]; exists {
return enabled == trueStr
}
// If the provider flag is not set, fall back to the ENV var.
if enabled, exists := os.LookupEnv("PULUMI_K8S_SUPPRESS_HELM_HOOK_WARNINGS"); exists {
return enabled == trueStr
}
// Default to false.
return false
}
if suppressHelmHookWarnings() {
k.suppressHelmHookWarnings = true
}
renderYamlToDirectory := func() string {
// Read the config from the Provider.
if directory, exists := vars["kubernetes:config:renderYamlToDirectory"]; exists && directory != "" {
return directory
}
return ""
}
k.yamlDirectory = renderYamlToDirectory()
k.yamlRenderMode = len(k.yamlDirectory) > 0
var helmReleaseSettings HelmReleaseSettings
if obj, ok := vars["kubernetes:config:helmReleaseSettings"]; ok {
err := json.Unmarshal([]byte(obj), &helmReleaseSettings)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal helmReleaseSettings option: %w", err)
}
}
// TODO: Once https://github.com/pulumi/pulumi/issues/8132 is fixed, we can drop the env var handling logic.
helmDriver := func() string {
if helmReleaseSettings.Driver != nil {
return *helmReleaseSettings.Driver
}
// If the provider flag is not set, fall back to the ENV var.
if driver, exists := os.LookupEnv("PULUMI_K8S_HELM_DRIVER"); exists {
return driver
}
return "secret"
}
k.helmDriver = helmDriver() // TODO: Make sure this is in provider state
helmPluginsPath := func() string {
if helmReleaseSettings.PluginsPath != nil {
return *helmReleaseSettings.PluginsPath
}
// If the provider flag is not set, fall back to the ENV var.
if pluginsPath, exists := os.LookupEnv("PULUMI_K8S_HELM_PLUGINS_PATH"); exists {
return pluginsPath
}
return helmpath.DataPath("plugins")
}
k.helmPluginsPath = helmPluginsPath()
if helmReleaseSettings.PluginsPath != nil {
helmSettings.PluginsDirectory = *helmReleaseSettings.PluginsPath
}
helmRegistryConfigPath := func() string {
if helmReleaseSettings.RegistryConfigPath != nil {
return *helmReleaseSettings.RegistryConfigPath
}
// If the provider flag is not set, fall back to the ENV var.
if registryPath, exists := os.LookupEnv("PULUMI_K8S_HELM_REGISTRY_CONFIG_PATH"); exists {
return registryPath
}
return helmpath.ConfigPath("registry.json")
}
k.helmRegistryConfigPath = helmRegistryConfigPath()
if helmReleaseSettings.RegistryConfigPath != nil {
helmSettings.RegistryConfig = k.helmRegistryConfigPath
}
helmRepositoryConfigPath := func() string {
if helmReleaseSettings.RepositoryConfigPath != nil {
return *helmReleaseSettings.RepositoryConfigPath
}
if repositoryConfigPath, exists := os.LookupEnv("PULUMI_K8S_HELM_REPOSITORY_CONFIG_PATH"); exists {
return repositoryConfigPath
}
return helmpath.ConfigPath("repositories.yaml")
}
k.helmRepositoryConfigPath = helmRepositoryConfigPath()
if helmReleaseSettings.RepositoryConfigPath != nil {
helmSettings.RepositoryConfig = k.helmRepositoryConfigPath
}
helmRepositoryCache := func() string {
if helmReleaseSettings.RepositoryCache != nil {
return *helmReleaseSettings.RepositoryCache
}
if repositoryCache, exists := os.LookupEnv("PULUMI_K8S_HELM_REPOSITORY_CACHE"); exists {
return repositoryCache
}
return helmpath.CachePath("repository")
}
k.helmRepositoryCache = helmRepositoryCache()
if helmReleaseSettings.RepositoryCache != nil {
helmSettings.RepositoryCache = k.helmRepositoryCache
}
// Rather than erroring out on an invalid k8s config, mark the cluster as unreachable and conditionally bail out on
// operations that require a valid cluster. This will allow us to perform invoke operations using the default
// provider.
unreachableCluster := func(err error) {
k.clusterUnreachable = true
k.clusterUnreachableReason = fmt.Sprintf(
"failed to parse kubeconfig data in `kubernetes:config:kubeconfig`- %v", err)
}
var kubeconfig clientcmd.ClientConfig
var apiConfig *clientapi.Config
// Note: the Python SDK was setting the kubeconfig value to "" by default, so explicitly check for empty string.
if pathOrContents, ok := vars["kubernetes:config:kubeconfig"]; ok && pathOrContents != "" {
apiConfig, err := parseKubeconfigString(pathOrContents)
if err != nil {
unreachableCluster(err)
// note: kubeconfig is not set when the cluster is unreachable
} else {
kubeconfig = clientcmd.NewDefaultClientConfig(*apiConfig, overrides)
configurationNamespace, _, err := kubeconfig.Namespace()
if err == nil {
k.defaultNamespace = configurationNamespace
}
// initialize Helm settings to use the kubeconfig; use a generated file as necessary.
configFile, err := writeKubeconfigToFile(apiConfig)
if err != nil {
return nil, fmt.Errorf("failed to write kubeconfig file: %w", err)
}
helmSettings.KubeConfig = configFile
}
} else {
// Use client-go to resolve the final configuration values for the client. Typically, these
// values would reside in the $KUBECONFIG file, but can also be altered in several
// places, including in env variables, client-go default values, and (if we allowed it) CLI
// flags.
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig
kubeconfig = clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin)
configurationNamespace, _, err := kubeconfig.Namespace()
if err == nil {
k.defaultNamespace = configurationNamespace
}
}
var kubeClientSettings KubeClientSettings
if obj, ok := vars["kubernetes:config:kubeClientSettings"]; ok {
err := json.Unmarshal([]byte(obj), &kubeClientSettings)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal kubeClientSettings option: %w", err)
}
}
// TODO: Once https://github.com/pulumi/pulumi/issues/8132 is fixed, we can drop the env var handling logic.
if burst := os.Getenv("PULUMI_K8S_CLIENT_BURST"); burst != "" && kubeClientSettings.Burst == nil {
asInt, err := strconv.Atoi(burst)
if err != nil {
return nil, fmt.Errorf("invalid value specified for PULUMI_K8S_CLIENT_BURST: %w", err)
}
kubeClientSettings.Burst = &asInt
} else if kubeClientSettings.Burst == nil {
v := 120 // Increased from default value of 10
kubeClientSettings.Burst = &v
}
if qps := os.Getenv("PULUMI_K8S_CLIENT_QPS"); qps != "" && kubeClientSettings.QPS == nil {
asFloat, err := strconv.ParseFloat(qps, 64)
if err != nil {
return nil, fmt.Errorf("invalid value specified for PULUMI_K8S_CLIENT_QPS: %w", err)
}
kubeClientSettings.QPS = &asFloat
} else if kubeClientSettings.QPS == nil {
v := 50.0 // Increased from default value of 5.0
kubeClientSettings.QPS = &v
}
if timeout := os.Getenv("PULUMI_K8S_CLIENT_TIMEOUT"); timeout != "" && kubeClientSettings.Timeout == nil {
asInt, err := strconv.Atoi(timeout)
if err != nil {
return nil, fmt.Errorf("invalid value specified for PULUMI_K8S_CLIENT_TIMEOUT: %w", err)
}
kubeClientSettings.Timeout = &asInt
}
// Attempt to load the configuration from the provided kubeconfig. If this fails, mark the cluster as unreachable.
var config *rest.Config
if !k.clusterUnreachable {
contract.Assertf(kubeconfig != nil, "expected kubeconfig to be initialized")
var err error
config, err = kubeconfig.ClientConfig()
if err != nil {
k.clusterUnreachable = true
k.clusterUnreachableReason = fmt.Sprintf("unable to load Kubernetes client configuration from kubeconfig file. Make sure you have: \n\n"+
" \t • set up the provider as per https://www.pulumi.com/registry/packages/kubernetes/installation-configuration/ \n\n %v", err)
config = nil
} else {
if kubeClientSettings.Burst != nil {
config.Burst = *kubeClientSettings.Burst
helmSettings.BurstLimit = *kubeClientSettings.Burst
logger.V(9).Infof("kube client burst set to %v", config.Burst)
}
if kubeClientSettings.QPS != nil {
config.QPS = float32(*kubeClientSettings.QPS)
helmSettings.QPS = float32(*kubeClientSettings.QPS)
logger.V(9).Infof("kube client QPS set to %v", config.QPS)
}
if kubeClientSettings.Timeout != nil {
config.Timeout = time.Duration(*kubeClientSettings.Timeout) * time.Second
helmFlags.Timeout = ptr.To(strconv.Itoa(*kubeClientSettings.Timeout))
logger.V(9).Infof("kube client timeout set to %v", config.Timeout)
}
config.WarningHandler = rest.NoWarnings{}
}
}
var err error
k.clientSet, k.logClient, err = k.makeClient(k.canceler.context, config)
if err != nil {
return nil, err
}
// These operations require a reachable cluster.
if !k.clusterUnreachable {
k.k8sVersion = cluster.TryGetServerVersion(k.clientSet.DiscoveryClientCached)
if k.k8sVersion.Compare(cluster.ServerVersion{Major: 1, Minor: 13}) < 0 {
return nil, fmt.Errorf("minimum supported cluster version is v1.13. found v%s", k.k8sVersion)
}
if _, err = k.getResources(); err != nil {
k.clusterUnreachable = true
k.clusterUnreachableReason = fmt.Sprintf(
"unable to load schema information from the API server: %v", err)
}
}
if !k.clusterUnreachable {
k.helmSettings = helmSettings
}
k.helmReleaseProvider, err = newHelmReleaseProvider(
k.host,
k.canceler,
apiConfig,
overrides,
config,
k.clientSet,
k.helmDriver,
k.defaultNamespace,
k.enableSecrets,
k.helmPluginsPath,
k.helmRegistryConfigPath,
k.helmRepositoryConfigPath,
k.helmRepositoryCache,
k.clusterUnreachable,
k.clusterUnreachableReason)
if err != nil {
return nil, err
}
return &pulumirpc.ConfigureResponse{
AcceptSecrets: true,
SupportsPreview: true,
}, nil
}
// Invoke dynamically executes a built-in function in the provider.
func (k *kubeProvider) Invoke(ctx context.Context,
req *pulumirpc.InvokeRequest) (*pulumirpc.InvokeResponse, error) {
// Important: Some invoke logic is intended to run during preview, and the Kubernetes provider
// inputs may not have resolved yet. Any invoke logic that depends on an active cluster must check
// k.clusterUnreachable and handle that condition appropriately.
tok := req.GetTok()
label := fmt.Sprintf("%s.Invoke(%s)", k.label(), tok)
args, err := plugin.UnmarshalProperties(
req.GetArgs(), plugin.MarshalOptions{Label: label, KeepUnknowns: true})
if err != nil {
return nil, fmt.Errorf("failed to unmarshal %v args during an Invoke call: %w", tok, err)
}
switch tok {
case invokeDecodeYaml:
var text, defaultNamespace string
if textArg := args["text"]; textArg.HasValue() && textArg.IsString() {
text = textArg.StringValue()
} else {
return nil, errors.New("missing required field 'text' of type string")
}
if defaultNsArg := args["defaultNamespace"]; defaultNsArg.HasValue() && defaultNsArg.IsString() {
defaultNamespace = defaultNsArg.StringValue()
}
result, err := decodeYaml(text, defaultNamespace, k.clientSet)
if err != nil {
return nil, err
}
objProps, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(map[string]any{"result": result}),
plugin.MarshalOptions{
Label: label, KeepUnknowns: true, SkipNulls: true,
})
if err != nil {
return nil, err
}
return &pulumirpc.InvokeResponse{Return: objProps}, nil
case invokeHelmTemplate:
var jsonOpts string
if jsonOptsArgs := args["jsonOpts"]; jsonOptsArgs.HasValue() && jsonOptsArgs.IsString() {
jsonOpts = jsonOptsArgs.StringValue()
} else {
return nil, errors.New("missing required field 'jsonOpts' of type string")
}
var opts HelmChartOpts
err = json.Unmarshal([]byte(jsonOpts), &opts)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal 'jsonOpts': %w", err)
}
text, err := helmTemplate(k.host, opts, k.clientSet)
if err != nil {
return nil, fmt.Errorf("failed to generate YAML for specified Helm chart: %w", err)
}
// Decode the generated YAML here to avoid an extra invoke in the client.
result, err := decodeYaml(text, opts.Namespace, k.clientSet)
if err != nil {
return nil, fmt.Errorf("failed to decode YAML for specified Helm chart: %w", err)
}
objProps, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(map[string]any{"result": result}),
plugin.MarshalOptions{
Label: label, KeepUnknowns: true, SkipNulls: true,
})
if err != nil {
return nil, err
}
return &pulumirpc.InvokeResponse{Return: objProps}, nil
case invokeKustomize:
var directory string
if directoryArg := args["directory"]; directoryArg.HasValue() && directoryArg.IsString() {
directory = directoryArg.StringValue()
} else {
return nil, errors.New("missing required field 'directory' of type string")
}
result, err := kustomizeDirectory(directory, k.clientSet)
if err != nil {
return nil, err
}
objProps, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(map[string]any{"result": result}),
plugin.MarshalOptions{
Label: label, KeepUnknowns: true, SkipNulls: true,
})
if err != nil {
return nil, err
}
return &pulumirpc.InvokeResponse{Return: objProps}, nil
default:
return nil, fmt.Errorf("unknown Invoke type %q", tok)
}
}
// StreamInvoke dynamically executes a built-in function in the provider. The result is streamed
// back as a series of messages.
func (k *kubeProvider) StreamInvoke(
req *pulumirpc.InvokeRequest, server pulumirpc.ResourceProvider_StreamInvokeServer) error {
// Important: Some invoke logic is intended to run during preview, and the Kubernetes provider
// inputs may not have resolved yet. Any invoke logic that depends on an active cluster must check
// k.clusterUnreachable and handle that condition appropriately.
// Unmarshal arguments.
tok := req.GetTok()
label := fmt.Sprintf("%s.StreamInvoke(%s)", k.label(), tok)
args, err := plugin.UnmarshalProperties(
req.GetArgs(), plugin.MarshalOptions{Label: label, KeepUnknowns: true})
if err != nil {
return fmt.Errorf("failed to unmarshal %v args during an StreamInvoke call: %w", tok, err)
}
switch tok {
case streamInvokeList:
//
// Request a list of all resources of some type, in some number of namespaces.
//
// DESIGN NOTES: `list` must be a `StreamInvoke` instead of an `Invoke` to avoid the gRPC
// message size limit. Unlike `watch`, which will continue until the user cancels the
// request, `list` is guaranteed to terminate after all the resources are listed. The role
// of the SDK implementations of `list` is thus to wait for the stream to terminate,
// aggregate the resources into a list, and return to the user.
//
// We send the resources asynchronously. This requires an "event loop" (below), which
// continuously attempts to send the resource, checking for cancellation on each send. This
// allows for the theoretical possibility that the gRPC client cancels the `list` operation
// prior to completion. The SDKs implementing `list` will very probably never expose a
// `cancel` handler in the way that `watch` does; `watch` requires it because a watcher is
// expected to never terminate, and users of the various SDKs need a way to tell the
// provider to stop streaming and reclaim the resources associated with the stream.