-
Notifications
You must be signed in to change notification settings - Fork 117
/
provider.go
2586 lines (2281 loc) · 89.1 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-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 provider
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
jsonpatch "github.com/evanphx/json-patch"
pbempty "github.com/golang/protobuf/ptypes/empty"
structpb "github.com/golang/protobuf/ptypes/struct"
pkgerrors "github.com/pkg/errors"
"github.com/pulumi/pulumi-kubernetes/pkg/await"
"github.com/pulumi/pulumi-kubernetes/pkg/clients"
"github.com/pulumi/pulumi-kubernetes/pkg/cluster"
"github.com/pulumi/pulumi-kubernetes/pkg/gen"
"github.com/pulumi/pulumi-kubernetes/pkg/kinds"
"github.com/pulumi/pulumi-kubernetes/pkg/logging"
"github.com/pulumi/pulumi-kubernetes/pkg/metadata"
"github.com/pulumi/pulumi-kubernetes/pkg/openapi"
"github.com/pulumi/pulumi/pkg/resource/provider"
"github.com/pulumi/pulumi/sdk/go/common/diag"
"github.com/pulumi/pulumi/sdk/go/common/resource"
"github.com/pulumi/pulumi/sdk/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/go/common/util/contract"
logger "github.com/pulumi/pulumi/sdk/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/go/common/util/rpcutil/rpcerror"
pulumirpc "github.com/pulumi/pulumi/sdk/proto/go"
"google.golang.org/grpc/codes"
"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/apimachinery/pkg/util/sets"
"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"
"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"
lastAppliedConfigKey = "kubectl.kubernetes.io/last-applied-configuration"
initialAPIVersionKey = "__initialApiVersion"
)
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 {
host *provider.HostClient
canceler *cancellationContext
name string
version string
providerPackage string
opts kubeOpts
defaultNamespace string
enableDryRun bool
enableSecrets bool
suppressDeprecationWarnings bool
yamlRenderMode bool
yamlDirectory string
clusterUnreachable bool // Kubernetes cluster is unreachable.
clusterUnreachableReason string // Detailed error message if cluster is unreachable.
config *rest.Config // Cluster config, e.g., through $KUBECONFIG file.
clientSet *clients.DynamicClientSet
logClient *clients.LogClient
k8sVersion cluster.ServerVersion
resources k8sopenapi.Resources
resourcesMutex sync.RWMutex
}
var _ pulumirpc.ResourceProviderServer = (*kubeProvider)(nil)
func makeKubeProvider(
host *provider.HostClient, name, version string,
) (pulumirpc.ResourceProviderServer, error) {
return &kubeProvider{
host: host,
canceler: makeCancellationContext(),
name: name,
version: version,
providerPackage: name,
enableDryRun: false,
enableSecrets: false,
suppressDeprecationWarnings: false,
}, 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
}
func (k *kubeProvider) GetSchema(ctx context.Context, req *pulumirpc.GetSchemaRequest) (*pulumirpc.GetSchemaResponse, error) {
return nil, rpcerror.New(codes.Unimplemented, "GetSchema is unimplemented")
}
// 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,
RejectAssets: true,
})
if err != nil {
return nil, pkgerrors.Wrapf(err, "CheckConfig failed because of malformed resource inputs")
}
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
}
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 truthyValue("enableDryRun", news) {
failures = append(failures, &pulumirpc.CheckFailure{
Property: "enableDryRun",
Reason: fmt.Sprintf(errTemplate, "enableDryRun"),
})
}
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,
RejectAssets: true,
})
if err != nil {
return nil, pkgerrors.Wrapf(err, "DiffConfig failed because of malformed resource inputs")
}
// We can't tell for sure if a computed value has changed, so we make the conservative choice
// and force a replacement.
if news["kubeconfig"].IsComputed() {
return &pulumirpc.DiffResponse{
Changes: pulumirpc.DiffResponse_DIFF_SOME,
Diffs: []string{"kubeconfig"},
Replaces: []string{"kubeconfig"},
}, 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.
if !reflect.DeepEqual(oldConfig, newConfig) {
diffs = append(diffs, "kubeconfig")
}
if olds["context"] != news["context"] {
diffs = append(diffs, "context")
}
if olds["cluster"] != news["cluster"] {
diffs = append(diffs, "cluster")
}
if olds["namespace"] != news["namespace"] {
diffs = append(diffs, "namespace")
}
if olds["enableDryRun"] != news["enableDryRun"] {
diffs = append(diffs, "enableDryRun")
}
if olds["renderYamlToDirectory"] != news["renderYamlToDirectory"] {
diffs = append(diffs, "renderYamlToDirectory")
// If the render directory changes, all of 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 := getActiveClusterFromConfig(oldConfig, olds)
activeCluster := getActiveClusterFromConfig(newConfig, news)
if !reflect.DeepEqual(oldActiveCluster, activeCluster) {
replaces = diffs
}
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"
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.
//
// Compute config overrides.
overrides := &clientcmd.ConfigOverrides{
Context: clientapi.Context{
Cluster: vars["kubernetes:config:cluster"],
},
CurrentContext: vars["kubernetes:config:context"],
}
enableDryRun := 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:enableDryRun"]; 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_DRY_RUN"); exists {
return enabled == trueStr
}
// Default to false.
return false
}
if enableDryRun() {
k.enableDryRun = 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
}
renderYamlToDirectory := func() string {
// Read the config from the Provider.
if directory, exists := vars["kubernetes:config:renderYamlToDirectory"]; exists {
return directory
}
return ""
}
k.yamlDirectory = renderYamlToDirectory()
k.yamlRenderMode = len(k.yamlDirectory) > 0
var kubeconfig clientcmd.ClientConfig
if configJSON, ok := vars["kubernetes:config:kubeconfig"]; ok {
config, err := clientcmd.Load([]byte(configJSON))
if err != nil {
// Rather than erroring out here, 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.
k.clusterUnreachable = true
k.clusterUnreachableReason = fmt.Sprintf("failed to parse kubeconfig data in "+
"`kubernetes:config:kubeconfig`; this must be a YAML literal string and not "+
"a filename or path - %v", err)
} else {
kubeconfig = clientcmd.NewDefaultClientConfig(*config, overrides)
configurationNamespace, _, err := kubeconfig.Namespace()
if err == nil {
k.defaultNamespace = configurationNamespace
}
}
} else {
// Use client-go to resolve the final configuration values for the client. Typically these
// values would 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)
}
if defaultNamespace := vars["kubernetes:config:namespace"]; defaultNamespace != "" {
k.defaultNamespace = defaultNamespace
}
// Attempt to load the configuration from the provided kubeconfig. If this fails, mark the cluster as unreachable.
if !k.clusterUnreachable {
config, err := kubeconfig.ClientConfig()
if err != nil {
k.clusterUnreachable = true
k.clusterUnreachableReason = fmt.Sprintf(
"unable to load Kubernetes client configuration from kubeconfig file: %v", err)
} else {
k.config = config
}
}
// These operations require a reachable cluster.
if !k.clusterUnreachable {
cs, err := clients.NewDynamicClientSet(k.config)
if err != nil {
return nil, err
}
k.clientSet = cs
lc, err := clients.NewLogClient(k.config)
if err != nil {
return nil, err
}
k.logClient = lc
k.k8sVersion = cluster.TryGetServerVersion(cs.DiscoveryClientCached)
if _, err = k.getResources(); err != nil {
k.clusterUnreachable = true
k.clusterUnreachableReason = fmt.Sprintf(
"unable to load schema information from the API server: %v", err)
}
}
return &pulumirpc.ConfigureResponse{
AcceptSecrets: 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, pkgerrors.Wrapf(err, "failed to unmarshal %v args during an Invoke call", tok)
}
switch tok {
case invokeDecodeYaml:
var text, defaultNamespace string
if textArg := args["text"]; textArg.HasValue() && textArg.IsString() {
text = textArg.StringValue()
} else {
return nil, pkgerrors.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]interface{}{"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 pkgerrors.Wrapf(err, "failed to unmarshal %v args during an StreamInvoke call", tok)
}
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.
//
// Still, we implement this cancellation also for `list`, primarily for completeness. We'd
// like to avoid an unpleasant and non-actionable error that would appear on a `Send` on a
// client that is no longer accepting requests. This also helps to guard against the
// possibility that some dark corner of gRPC signals cancellation by accident, e.g., during
// shutdown.
//
if k.clusterUnreachable {
return fmt.Errorf("configured Kubernetes cluster is unreachable: %s", k.clusterUnreachableReason)
}
namespace := ""
if args["namespace"].HasValue() {
namespace = args["namespace"].StringValue()
}
if !args["group"].HasValue() || !args["version"].HasValue() || !args["kind"].HasValue() {
return fmt.Errorf(
"list requires a group, version, and kind that uniquely specify the resource type")
}
cl, err := k.clientSet.ResourceClient(schema.GroupVersionKind{
Group: args["group"].StringValue(),
Version: args["version"].StringValue(),
Kind: args["kind"].StringValue(),
}, namespace)
if err != nil {
return err
}
list, err := cl.List(metav1.ListOptions{})
if err != nil {
return err
}
//
// List resources. Send them one-by-one, asynchronously, to the client requesting them.
//
objects := make(chan map[string]interface{})
defer close(objects)
done := make(chan struct{})
defer close(done)
go func() {
for _, o := range list.Items {
objects <- o.Object
}
done <- struct{}{}
}()
for {
select {
case <-k.canceler.context.Done():
//
// `kubeProvider#Cancel` was called. Terminate the `StreamInvoke` RPC, free all
// resources, and exit without error.
//
return nil
case <-done:
//
// Success. Return.
//
return nil
case o := <-objects:
//
// Publish resource from the list back to user.
//
resp, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(o),
plugin.MarshalOptions{})
if err != nil {
return err
}
err = server.Send(&pulumirpc.InvokeResponse{Return: resp})
if err != nil {
return err
}
case <-server.Context().Done():
//
// gRPC stream was cancelled from the client that issued the `StreamInvoke` request
// to us. In this case, we terminate the `StreamInvoke` RPC, free all resources, and
// exit without error.
//
// This is required for `watch`, but is implemented in `list` for completeness.
// Users calling `watch` from one of the SDKs need to be able to cancel a `watch`
// and signal to the provider that it's ok to reclaim the resources associated with
// a `watch`. In `list` it's to prevent the user from getting weird errors if a
// client somehow cancels the streaming request and they subsequently send a message
// anyway.
//
return nil
}
}
case streamInvokeWatch:
//
// Set up resource watcher.
//
if k.clusterUnreachable {
return fmt.Errorf("configured Kubernetes cluster is unreachable: %s", k.clusterUnreachableReason)
}
namespace := ""
if args["namespace"].HasValue() {
namespace = args["namespace"].StringValue()
}
if !args["group"].HasValue() || !args["version"].HasValue() || !args["kind"].HasValue() {
return fmt.Errorf(
"watch requires a group, version, and kind that uniquely specify the resource type")
}
cl, err := k.clientSet.ResourceClient(schema.GroupVersionKind{
Group: args["group"].StringValue(),
Version: args["version"].StringValue(),
Kind: args["kind"].StringValue(),
}, namespace)
if err != nil {
return err
}
watch, err := cl.Watch(metav1.ListOptions{})
if err != nil {
return err
}
//
// Watch for resource updates, and stream them back to the caller.
//
for {
select {
case <-k.canceler.context.Done():
//
// `kubeProvider#Cancel` was called. Terminate the `StreamInvoke` RPC, free all
// resources, and exit without error.
//
watch.Stop()
return nil
case event := <-watch.ResultChan():
//
// Kubernetes resource was updated. Publish resource update back to user.
//
resp, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(
map[string]interface{}{
"type": event.Type,
"object": event.Object.(*unstructured.Unstructured).Object,
}),
plugin.MarshalOptions{})
if err != nil {
return err
}
err = server.Send(&pulumirpc.InvokeResponse{Return: resp})
if err != nil {
return err
}
case <-server.Context().Done():
//
// gRPC stream was cancelled from the client that issued the `StreamInvoke` request
// to us. In this case, we terminate the `StreamInvoke` RPC, free all resources, and
// exit without error.
//
// Usually, this happens in the language provider, e.g., in the call to `cancel`
// below.
//
// const deployments = await streamInvoke("kubernetes:kubernetes:watch", {
// group: "apps", version: "v1", kind: "Deployment",
// });
// deployments.cancel();
//
watch.Stop()
return nil
}
}
case streamInvokePodLogs:
//
// Set up log stream for Pod.
//
if k.clusterUnreachable {
return fmt.Errorf("configured Kubernetes cluster is unreachable: %s", k.clusterUnreachableReason)
}
namespace := "default"
if args["namespace"].HasValue() {
namespace = args["namespace"].StringValue()
}
if !args["name"].HasValue() {
return fmt.Errorf(
"could not retrieve pod logs because the pod name was not present")
}
name := args["name"].StringValue()
podLogs, err := k.logClient.Logs(namespace, name)
if err != nil {
return err
}
defer podLogs.Close()
//
// Enumerate logs by line. Send back to the user.
//
// TODO: We send the logs back one-by-one, but we should probably batch them instead.
//
logLines := make(chan string)
defer close(logLines)
done := make(chan error)
defer close(done)
go func() {
podLogLines := bufio.NewScanner(podLogs)
for podLogLines.Scan() {
logLines <- podLogLines.Text()
}
if err := podLogLines.Err(); err != nil {
done <- err
} else {
done <- nil
}
}()
for {
select {
case <-k.canceler.context.Done():
//
// `kubeProvider#Cancel` was called. Terminate the `StreamInvoke` RPC, free all
// resources, and exit without error.
//
return nil
case err := <-done:
//
// Complete. Return the error if applicable.
//
return err
case line := <-logLines:
//
// Publish log line back to user.
//
resp, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(
map[string]interface{}{"lines": []string{line}}),
plugin.MarshalOptions{})
if err != nil {
return err
}
err = server.Send(&pulumirpc.InvokeResponse{Return: resp})
if err != nil {
return err
}
case <-server.Context().Done():
//
// gRPC stream was cancelled from the client that issued the `StreamInvoke` request
// to us. In this case, we terminate the `StreamInvoke` RPC, free all resources, and
// exit without error.
//
// Usually, this happens in the language provider, e.g., in the call to `cancel`
// below.
//
// const podLogLines = await streamInvoke("kubernetes:kubernetes:podLogs", {
// namespace: "default", name: "nginx-f94d8bc55-xftvs",
// });
// podLogLines.cancel();
//
return nil
}
}
default:
return fmt.Errorf("unknown Invoke type '%s'", tok)
}
}
// Check validates that the given property bag is valid for a resource of the given type and returns
// the inputs that should be passed to successive calls to Diff, Create, or Update for this
// resource. As a rule, the provider inputs returned by a call to Check should preserve the original
// representation of the properties as present in the program inputs. Though this rule is not
// required for correctness, violations thereof can negatively impact the end-user experience, as
// the provider inputs are using for detecting and rendering diffs.
func (k *kubeProvider) Check(ctx context.Context, req *pulumirpc.CheckRequest) (*pulumirpc.CheckResponse, error) {
//
// Behavior as of v0.12.x: We take two inputs:
//
// 1. req.News, the new resource inputs, i.e., the property bag coming from a custom resource like
// k8s.core.v1.Service
// 2. req.Olds, the last version submitted from a custom resource.
//
// `req.Olds` are ignored (and are sometimes nil). `req.News` are validated, and `.metadata.name`
// is given to it if it's not already provided.
//
// Utilities for determining whether a resource's GVK exists.
gvkExists := func(gvk schema.GroupVersionKind) bool {
knownGVKs := sets.NewString()
if knownGVKs.Has(gvk.String()) {
return true
}
gv := gvk.GroupVersion()
rls, err := k.clientSet.DiscoveryClientCached.ServerResourcesForGroupVersion(gv.String())
if err != nil {
if !errors.IsNotFound(err) {
logger.V(3).Infof("ServerResourcesForGroupVersion(%q) returned unexpected error %v", gv, err)
}
return false
}
for _, rl := range rls.APIResources {
knownGVKs.Insert(gv.WithKind(rl.Kind).String())
}
return knownGVKs.Has(gvk.String())
}
urn := resource.URN(req.GetUrn())
label := fmt.Sprintf("%s.Check(%s)", k.label(), urn)
logger.V(9).Infof("%s executing", label)
// Obtain old resource inputs. This is the old version of the resource(s) supplied by the user as
// an update.
oldResInputs := req.GetOlds()
olds, err := plugin.UnmarshalProperties(oldResInputs, plugin.MarshalOptions{
Label: fmt.Sprintf("%s.olds", label), KeepUnknowns: true, SkipNulls: true, KeepSecrets: true,
})
if err != nil {
return nil, err
}
oldInputs := propMapToUnstructured(olds)
// Obtain new resource inputs. This is the new version of the resource(s) supplied by the user as
// an update.
newResInputs := req.GetNews()
news, err := plugin.UnmarshalProperties(newResInputs, plugin.MarshalOptions{
Label: fmt.Sprintf("%s.news", label),
KeepUnknowns: true,
SkipNulls: true,
RejectAssets: true,
KeepSecrets: true,
})
if err != nil {
return nil, pkgerrors.Wrapf(err, "check failed because malformed resource inputs")
}
newInputs := propMapToUnstructured(news)
var failures []*pulumirpc.CheckFailure
// If annotations with a reserved internal prefix exist, report that as error.
for k := range newInputs.GetAnnotations() {
if metadata.IsInternalAnnotation(k) {
failures = append(failures, &pulumirpc.CheckFailure{
Reason: fmt.Sprintf("invalid use of reserved internal annotation %q", k),
})
}
}
annotatedInputs, err := legacyInitialAPIVersion(oldInputs, newInputs)
if err != nil {
return nil, pkgerrors.Wrapf(
err, "Failed to create resource %s/%s because of an error generating the %s value in "+
"`.metadata.annotations`",
newInputs.GetNamespace(), newInputs.GetName(), metadata.AnnotationInitialAPIVersion)
}
newInputs = annotatedInputs
// Adopt name from old object if appropriate.
//
// If the user HAS NOT assigned a name in the new inputs, we autoname it and mark the object as
// autonamed in `.metadata.annotations`. This makes it easier for `Diff` to decide whether this
// needs to be `DeleteBeforeReplace`'d. If the resource is marked `DeleteBeforeReplace`, then
// `Create` will allocate it a new name later.
if len(oldInputs.Object) > 0 {
// NOTE: If old inputs exist, they have a name, either provided by the user or filled in with a
// previous run of `Check`.
contract.Assert(oldInputs.GetName() != "")
metadata.AdoptOldAutonameIfUnnamed(newInputs, oldInputs)
// If this resource does not have a "managed-by: pulumi" label in its inputs, it is likely we are importing
// a resource that was created out-of-band. In this case, we do not add the `managed-by` label here, as doing
// so would result in a persistent failure to import due to a diff that the user cannot correct.
if metadata.HasManagedByLabel(oldInputs) {
_, err = metadata.TrySetManagedByLabel(newInputs)
if err != nil {
return nil, pkgerrors.Wrapf(err,
"Failed to create object because of a problem setting managed-by labels")
}
}
} else {
metadata.AssignNameIfAutonamable(newInputs, urn.Name())
// Set a "managed-by: pulumi" label on all created k8s resources.
_, err = metadata.TrySetManagedByLabel(newInputs)
if err != nil {
return nil, pkgerrors.Wrapf(err,
"Failed to create object because of a problem setting managed-by labels")
}
}
gvk, err := k.gvkFromURN(urn)
if err != nil {
return nil, err
}
// Skip the API version check if the cluster is unreachable.
if !k.clusterUnreachable {
if removed, version := kinds.RemovedAPIVersion(gvk, k.k8sVersion); removed {
return nil, &kinds.RemovedAPIError{GVK: gvk, Version: version}
}
if !k.suppressDeprecationWarnings && kinds.DeprecatedAPIVersion(gvk) {
_ = k.host.Log(ctx, diag.Warning, urn, gen.APIVersionComment(gvk))
}
}
// If a default namespace is set on the provider for this resource, check if the resource has Namespaced
// or Global scope. For namespaced resources, set the namespace to the default value if unset.
if k.defaultNamespace != "" && len(newInputs.GetNamespace()) == 0 {
namespacedKind, err := clients.IsNamespacedKind(gvk, k.clientSet)
if err != nil {
if clients.IsNoNamespaceInfoErr(err) {
// This is probably a CustomResource without a registered CustomResourceDefinition.