-
Notifications
You must be signed in to change notification settings - Fork 525
/
lazy.go
3114 lines (2589 loc) · 101 KB
/
lazy.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 2023 The Nuclio Authors.
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 functionres
import (
"bytes"
"context"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/nuclio/nuclio/pkg/common"
"github.com/nuclio/nuclio/pkg/errgroup"
"github.com/nuclio/nuclio/pkg/functionconfig"
"github.com/nuclio/nuclio/pkg/platform/abstract"
"github.com/nuclio/nuclio/pkg/platform/kube"
nuclioio "github.com/nuclio/nuclio/pkg/platform/kube/apis/nuclio.io/v1beta1"
"github.com/nuclio/nuclio/pkg/platform/kube/client"
nuclioioclient "github.com/nuclio/nuclio/pkg/platform/kube/client/clientset/versioned"
"github.com/nuclio/nuclio/pkg/platformconfig"
"github.com/nuclio/nuclio/pkg/processor"
"github.com/nuclio/nuclio/pkg/processor/config"
"github.com/nuclio/nuclio/pkg/processor/trigger/cron"
"github.com/nuclio/nuclio/pkg/processor/trigger/http"
"dario.cat/mergo"
"github.com/mitchellh/mapstructure"
"github.com/nuclio/errors"
"github.com/nuclio/logger"
"github.com/v3io/version-go"
"golang.org/x/text/cases"
"golang.org/x/text/language"
appsv1 "k8s.io/api/apps/v1"
autosv2 "k8s.io/api/autoscaling/v2"
batchv1 "k8s.io/api/batch/v1"
"k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apiresource "k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/yaml"
)
type deploymentResourceMethod string
const (
createDeploymentResourceMethod deploymentResourceMethod = "create"
updateDeploymentResourceMethod deploymentResourceMethod = "update"
)
//
// Client
//
type lazyClient struct {
logger logger.Logger
kubeClientSet kubernetes.Interface
nuclioClientSet nuclioioclient.Interface
classLabels labels.Set
platformConfigurationProvider PlatformConfigurationProvider
nodeScaleUpSleepTimeout time.Duration
}
func NewLazyClient(parentLogger logger.Logger,
kubeClientSet kubernetes.Interface,
nuclioClientSet nuclioioclient.Interface) (Client, error) {
newClient := lazyClient{
logger: parentLogger.GetChild("functionres"),
kubeClientSet: kubeClientSet,
nuclioClientSet: nuclioClientSet,
classLabels: make(labels.Set),
// TODO: make this value configurable
// from k8s docs (https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#how-does-scale-up-work):
// autoscale cycle is at least 10s.
// We saw that this value was not enough in GKE and AKS, so to mitigate the wait was increased to 60 sec
nodeScaleUpSleepTimeout: 60 * time.Second,
}
newClient.initClassLabels()
return &newClient, nil
}
func (lc *lazyClient) List(ctx context.Context, namespace string) ([]Resources, error) {
listOptions := metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=function", common.NuclioLabelKeyClass),
}
result, err := lc.kubeClientSet.AppsV1().Deployments(namespace).List(ctx, listOptions)
if err != nil {
return nil, errors.Wrap(err, "Failed to list deployments")
}
lc.logger.DebugWithCtx(ctx, "Got deployments", "num", len(result.Items))
var resources []Resources
// iterate over items, create a lazy resources
for _, item := range result.Items {
// create a lazy resource and append to resources - populating deployment
resources = append(resources, &lazyResources{
deployment: &item,
})
}
return resources, nil
}
func (lc *lazyClient) Get(ctx context.Context, namespace string, name string) (Resources, error) {
var result *appsv1.Deployment
deploymentName := kube.DeploymentNameFromFunctionName(name)
result, err := lc.kubeClientSet.AppsV1().
Deployments(namespace).
Get(ctx, deploymentName, metav1.GetOptions{})
lc.logger.DebugWithCtx(ctx,
"Got deployment",
"namespace", namespace,
"deploymentName", deploymentName,
"result", result,
"err", err)
// if we didn't find it
if err != nil {
if apierrors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
// create a lazy resources instance, populating deployment
return &lazyResources{
deployment: result,
}, err
}
func (lc *lazyClient) CreateOrUpdate(ctx context.Context,
function *nuclioio.NuclioFunction,
imagePullSecrets string) (Resources, error) {
var err error
// get labels from the function and add class labels
functionLabels := lc.getFunctionLabels(function)
// set a few constants
functionLabels[common.NuclioResourceLabelKeyFunctionName] = function.Name
// TODO: remove when versioning is back in
function.Spec.Version = -1
function.Spec.Alias = common.FunctionTagLatest
functionLabels[common.NuclioLabelKeyFunctionVersion] = common.FunctionTagLatest
resources := lazyResources{}
platformConfig := lc.platformConfigurationProvider.GetPlatformConfiguration()
for _, augmentedConfig := range platformConfig.FunctionAugmentedConfigs {
selector, err := metav1.LabelSelectorAsSelector(&augmentedConfig.LabelSelector)
if err != nil {
return nil, errors.Wrap(err, "Failed to get selector from label selector")
}
// if the label matches any of the function labels, augment the function with provided function config
if selector.Matches(functionLabels) {
encodedFunctionConfig, err := yaml.Marshal(augmentedConfig.FunctionConfig)
if err != nil {
return nil, errors.Wrap(err, "Failed to marshal augmented function config")
}
if err := yaml.Unmarshal(encodedFunctionConfig, function); err != nil {
return nil, errors.Wrap(err, "Failed to join augmented function config into target function")
}
}
}
// create or update the applicable configMap
if resources.configMap, err = lc.createOrUpdateConfigMap(ctx, functionLabels, function); err != nil {
return nil, errors.Wrap(err, "Failed to create/update configMap")
}
// create or update the applicable service
if resources.service, err = lc.createOrUpdateService(ctx, functionLabels, function); err != nil {
return nil, errors.Wrap(err, "Failed to create/update service")
}
// create or update the applicable deployment
if resources.deployment, err = lc.createOrUpdateDeployment(ctx,
functionLabels,
imagePullSecrets,
function); err != nil {
return nil, errors.Wrap(err, "Failed to create/update deployment")
}
// create or update the HPA
if resources.horizontalPodAutoscaler, err = lc.createOrUpdateHorizontalPodAutoscaler(ctx,
functionLabels,
function); err != nil {
return nil, errors.Wrap(err, "Failed to create/update HPA")
}
// create or update ingress
if resources.ingress, err = lc.createOrUpdateIngress(ctx, functionLabels, function); err != nil {
return nil, errors.Wrap(err, "Failed to create/update ingress")
}
// whether to use kubernetes cron job to invoke nuclio function cron trigger
if lc.platformConfigurationProvider.GetPlatformConfiguration().CronTriggerCreationMode == platformconfig.KubeCronTriggerCreationMode {
if resources.cronJobs, err = lc.createOrUpdateCronJobs(ctx, functionLabels, function, &resources); err != nil {
return nil, errors.Wrap(err, "Failed to create cron jobs from cron triggers")
}
}
lc.logger.DebugWithCtx(ctx,
"Successfully created/updated resources",
"functionName", function.Name,
"functionNamespace", function.Namespace)
return &resources, nil
}
func (lc *lazyClient) UpdatedServiceSelectorWhenScaledFromZero(ctx context.Context,
function *nuclioio.NuclioFunction) error {
// get labels from the function and add class labels
functionLabels := lc.getFunctionLabels(function)
functionLabels[common.NuclioResourceLabelKeyFunctionName] = function.Name
functionLabels[common.NuclioLabelKeyFunctionVersion] = common.FunctionTagLatest
// marshal labels to json
patchBytes, err := json.Marshal(map[string]interface{}{
"spec": map[string]interface{}{
"selector": functionLabels,
},
})
if err != nil {
return errors.Wrap(err, "Failed to marshal selector when patching service")
}
if err := lc.patchService(ctx, function, patchBytes); err != nil {
return errors.Wrap(err, "Failed to patch service selector")
}
return nil
}
func (lc *lazyClient) WaitAvailable(ctx context.Context,
function *nuclioio.NuclioFunction,
functionResourcesCreateOrUpdateTimestamp time.Time) (error, functionconfig.FunctionState) {
lc.logger.DebugWithCtx(ctx,
"Waiting for function resources to be available",
"namespace", function.Namespace,
"functionName", function.Name)
var deploymentReady bool
var ingressReady bool
var timeDeploymentReady time.Time
var reasonInitContainersNotDone string
// readiness flag for init containers
var initContainersDone bool
if len(function.Spec.InitContainers) == 0 {
// if there are no any init containers defined, then set to true (so we don't wait for any)
initContainersDone = true
}
counter := 0
waitMs := 250
readinessVerifierTicker := time.NewTicker(time.Duration(waitMs) * time.Millisecond)
availableTicker := time.NewTicker(50 * time.Millisecond)
// cleanup resources once done
defer readinessVerifierTicker.Stop()
defer availableTicker.Stop()
for {
select {
// check if context is still OK
case <-ctx.Done():
// for an edge-case where context exceeded deadline/cancelled right when resources got ready
if initContainersDone && deploymentReady && ingressReady {
lc.logger.DebugWithCtx(ctx,
"Function reached availability right when context is cancelled",
"err", ctx.Err(),
"namespace", function.Namespace,
"functionName", function.Name)
return nil, functionconfig.FunctionStateReady
}
if !initContainersDone {
lc.logger.WarnWithCtx(ctx,
"Function available wait is cancelled due to context timeout",
"reason", reasonInitContainersNotDone,
"err", ctx.Err(),
"namespace", function.Namespace,
"functionName", function.Name)
return errors.New(fmt.Sprintf("Init containers are not done yet. Reason: %s. Increasing readiness timeout may help", reasonInitContainersNotDone)),
functionconfig.FunctionStateUnhealthy
} else {
lc.logger.WarnWithCtx(ctx,
"Function available wait is cancelled due to context timeout",
"err", ctx.Err(),
"namespace", function.Namespace,
"functionName", function.Name)
}
return ctx.Err(), functionconfig.FunctionStateUnhealthy
// verify availability
case <-availableTicker.C:
if deploymentReady && ingressReady {
return nil, functionconfig.FunctionStateReady
}
// verify function resources readiness
case <-readinessVerifierTicker.C:
counter++
// exponentially wait more next time, up to 2 seconds
waitMs *= 2
if waitMs > 2000 {
waitMs = 2000
}
readinessVerifierTicker.Reset(time.Duration(waitMs) * time.Millisecond)
// waiting for init containers to be ready
if !initContainersDone {
var err error
initContainersDone, reasonInitContainersNotDone, err = lc.checkFunctionInitContainersDone(ctx, function)
if err != nil {
return errors.Wrap(err, "Function init containers check failed"), functionconfig.FunctionStateUnhealthy
}
if !initContainersDone {
lc.logger.DebugWithCtx(ctx,
"Function init containers are not done yet, continuing",
"namespace", function.Namespace,
"name", function.Name,
"reason", reasonInitContainersNotDone)
continue
} else {
lc.logger.DebugWithCtx(ctx,
"Function init containers finished successfully",
"namespace", function.Namespace,
"name", function.Name)
}
}
// deployment is ready
// ingress is not yet (being too slow I guess, marking as unhealthy)
// give ingress 2.5 minutes to be ready - since nginx ingress controller's
// sync cycle is 1 minute this ensures we'll wait at least 2 cycles.
// apply fail-fast when user did not ask to wait the full timeout
if deploymentReady &&
!ingressReady &&
time.Since(timeDeploymentReady) >= 150*time.Second &&
!function.Spec.WaitReadinessTimeoutBeforeFailure {
lc.logger.WarnWithCtx(ctx,
"Function deployment is ready while ingress is not yet, stop waiting",
"namespace", function.Namespace,
"name", function.Name)
return errors.New("Function deployment is ready while ingress is not"), functionconfig.FunctionStateUnhealthy
}
// check deployment readiness
if !deploymentReady {
err, functionState := lc.waitFunctionDeploymentReadiness(ctx,
function,
functionResourcesCreateOrUpdateTimestamp)
// HACK - we return with empty function state to indicate a possibly transient error
if functionState == "" {
if counter == 1 || counter%5 == 0 {
if err != nil {
lc.logger.WarnWithCtx(ctx,
"Failed to wait for function deployment readiness (probably a transient error)",
"err", err.Error(),
"namespace", function.Namespace,
"name", function.Name)
}
}
continue
}
if err != nil {
return errors.Wrap(err, "Failed to wait for function deployment readiness"), functionState
}
deploymentReady = true
timeDeploymentReady = time.Now()
lc.logger.DebugWithCtx(ctx,
"Function deployment is ready",
"namespace", function.Namespace,
"name", function.Name)
}
// check ingress readiness
if !ingressReady {
// if function have no ingress, assume ready and bail ingress readiness
if len(functionconfig.GetFunctionIngresses(client.NuclioioToFunctionConfig(function))) == 0 {
ingressReady = true
continue
}
if err := lc.waitFunctionIngressReadiness(ctx, function); err != nil {
lc.logger.WarnWithCtx(ctx,
"Function ingress is not ready yet, continuing",
"err", err.Error(),
"namespace", function.Namespace,
"name", function.Name)
continue
}
lc.logger.DebugWithCtx(ctx,
"Function ingress is ready",
"namespace", function.Namespace,
"name", function.Name)
ingressReady = true
}
}
}
}
func (lc *lazyClient) Delete(ctx context.Context, namespace string, name string) error {
propagationPolicy := metav1.DeletePropagationForeground
deleteOptions := metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
}
// Delete ingress
ingressName := kube.IngressNameFromFunctionName(name)
err := lc.kubeClientSet.NetworkingV1().Ingresses(namespace).Delete(ctx, ingressName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete ingress")
}
} else {
lc.logger.DebugWithCtx(ctx, "Deleted ingress", "namespace", namespace, "ingressName", ingressName)
}
// Delete HPA if exists
hpaName := kube.HPANameFromFunctionName(name)
err = lc.kubeClientSet.AutoscalingV2().HorizontalPodAutoscalers(namespace).Delete(ctx, hpaName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete HPA")
}
} else {
lc.logger.DebugWithCtx(ctx, "Deleted HPA", "namespace", namespace, "hpaName", hpaName)
}
// Delete Service if exists
serviceName := kube.ServiceNameFromFunctionName(name)
err = lc.kubeClientSet.CoreV1().Services(namespace).Delete(ctx, serviceName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete service")
}
} else {
lc.logger.DebugWithCtx(ctx, "Deleted service", "namespace", namespace, "serviceName", serviceName)
}
// Delete Secrets if exist
if err := lc.deleteFunctionSecrets(ctx, name, namespace); err != nil {
return errors.Wrap(err, "Failed to delete function secrets")
}
// Delete Deployment if exists
deploymentName := kube.DeploymentNameFromFunctionName(name)
err = lc.kubeClientSet.AppsV1().Deployments(namespace).Delete(ctx, deploymentName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete deployment")
}
} else {
lc.logger.DebugWithCtx(ctx,
"Deleted deployment",
"namespace", namespace,
"deploymentName", deploymentName)
}
// Delete configMap if exists
configMapName := kube.ConfigMapNameFromFunctionName(name)
err = lc.kubeClientSet.CoreV1().ConfigMaps(namespace).Delete(ctx, configMapName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete configMap")
}
} else {
lc.logger.DebugWithCtx(ctx,
"Deleted configMap",
"namespace", namespace,
"configMapName", configMapName)
}
// Delete function events
if err = lc.deleteFunctionEvents(ctx, name, namespace); err != nil {
return errors.Wrap(err, "Failed to delete function events")
}
// Delete function k8s cronJobs
if lc.platformConfigurationProvider.GetPlatformConfiguration().
CronTriggerCreationMode == platformconfig.KubeCronTriggerCreationMode {
if err := lc.deleteCronJobs(ctx, name, namespace); err != nil {
return errors.Wrap(err, "Failed to delete function cron jobs")
}
}
lc.logger.DebugWithCtx(ctx, "Deleted deployed function", "namespace", namespace, "name", name)
return nil
}
// SetPlatformConfigurationProvider sets the provider of the platform configuration for any future access
func (lc *lazyClient) SetPlatformConfigurationProvider(platformConfigurationProvider PlatformConfigurationProvider) {
lc.platformConfigurationProvider = platformConfigurationProvider
}
func (lc *lazyClient) waitFunctionIngressReadiness(ctx context.Context,
function *nuclioio.NuclioFunction) error {
functionIngresses, err := lc.kubeClientSet.NetworkingV1().
Ingresses(function.Namespace).
Get(ctx, kube.IngressNameFromFunctionName(function.Name), metav1.GetOptions{})
if err != nil {
return errors.Wrap(err, "Failed to get function ingresses")
}
for _, ingress := range functionIngresses.Status.LoadBalancer.Ingress {
if ingress.IP != "" || ingress.Hostname != "" {
lc.logger.DebugWithCtx(ctx,
"Found at least one populated ingress, ingress is ready",
"functionName", function.Name,
"functionNamespace", function.Namespace,
"ingress", ingress)
return nil
}
}
return errors.New("Function ingress is not ready yet")
}
func (lc *lazyClient) waitFunctionDeploymentReadiness(ctx context.Context,
function *nuclioio.NuclioFunction,
functionResourcesCreateOrUpdateTimestamp time.Time) (error, functionconfig.FunctionState) {
// get the deployment. if it doesn't exist yet, retry a bit later
functionDeployment, err := lc.getFunctionDeployment(ctx, function)
if err != nil {
return errors.Wrap(err, "Failed to get function deployment"), ""
}
// find the condition whose type is Available - that's the one we want to examine
for _, deploymentCondition := range functionDeployment.Status.Conditions {
// when we find the right condition, check its Status to see if it's true.
// a DeploymentCondition whose Type == Available and Status == True means the deployment is available
if deploymentCondition.Type == appsv1.DeploymentAvailable {
available := deploymentCondition.Status == v1.ConditionTrue
if available && functionDeployment.Status.UnavailableReplicas == 0 {
lc.logger.DebugWithCtx(ctx,
"Deployment is available",
"reason", deploymentCondition.Reason,
"functionName", function.Name)
return nil, functionconfig.FunctionStateReady
}
lc.logger.DebugWithCtx(ctx,
"Deployment not available yet",
"reason", deploymentCondition.Reason,
"unavailableReplicas", functionDeployment.Status.UnavailableReplicas,
"functionName", function.Name)
// we found the condition, wasn't available
break
}
}
// avoid fail-fast when user explicitly asks to wait for function readiness timeout
if !function.Spec.WaitReadinessTimeoutBeforeFailure {
// get the deployment pods. if it doesn't exist yet, retry a bit later
podsList, err := lc.kubeClientSet.CoreV1().
Pods(function.Namespace).
List(ctx,
metav1.ListOptions{
LabelSelector: common.CompileListFunctionPodsLabelSelector(function.Name),
})
if err != nil {
return errors.Wrap(err, "Failed to list function pods"), ""
}
// fail-fast mechanism
if failedStatus, err := lc.resolveFailFast(ctx,
podsList,
functionResourcesCreateOrUpdateTimestamp); err != nil {
return errors.Wrapf(err, "NuclioFunction deployment failed"), failedStatus
}
}
return errors.New("Function deployment is not ready yet"), ""
}
// getFunctionDeployment returns function's deployment
func (lc *lazyClient) getFunctionDeployment(ctx context.Context, function *nuclioio.NuclioFunction) (*appsv1.Deployment, error) {
return lc.kubeClientSet.AppsV1().
Deployments(function.Namespace).
Get(ctx, kube.DeploymentNameFromFunctionName(function.Name), metav1.GetOptions{})
}
// checkFunctionInitContainersDone checks that all function init containers are in terminated status
// returns (IsDone, reasonNotDone, error)
// Possible combinations and their meaning:
// (true, "", nil) - all init containers are terminated with 0 exit code, we can proceed to other checks
// (false, notDoneReason, nil) - some init containers are still waiting/running OR required number of pods hasn't been created yet, so need to wait
// (false, "", err) - we can stop waiting here since something is broken, so function won't be successfully started
// (true, err) - impossible
func (lc *lazyClient) checkFunctionInitContainersDone(ctx context.Context, function *nuclioio.NuclioFunction) (bool, string, error) {
functionDeployment, err := lc.getFunctionDeployment(ctx, function)
if err != nil {
return false, "", err
}
notDoneReason := ""
// deployment doesn't exist yet
if functionDeployment == nil {
notDoneReason = "deployment doesn't exist yet"
return false, notDoneReason, nil
}
// if initContainers aren't defined or replicas number is equal to 0, skip
if len(function.Spec.InitContainers) == 0 || functionDeployment.Spec.Replicas == nil {
return true, "", nil
}
functionPods, err := lc.getFunctionPods(ctx, function)
if err != nil {
return false, "", err
}
// since we are here, it means that we have already checked that the expected number of pods isn't zero
// so at least one is expected
if functionPods == nil {
return false, "", errors.New(fmt.Sprintf("Couldn't find any pods for function %s", function.Name))
}
// checking that the number of pods is equal to expected replicas, otherwise checking init container
// statuses doesn't make sense; need to wait more time
if *functionDeployment.Spec.Replicas != int32(len(functionPods.Items)) {
notDoneReason = fmt.Sprintf("Not all pod replicas are deployed yet. Expected replicas: %d. Actual replicas: %d",
*functionDeployment.Spec.Replicas,
len(functionPods.Items))
return false, notDoneReason, nil
}
// going through each pod's init containers and check that they all were terminated with exit code 0
for _, pod := range functionPods.Items {
for _, initContainerStatus := range pod.Status.InitContainerStatuses {
switch {
case initContainerStatus.State.Terminated != nil:
if initContainerStatus.State.Terminated.ExitCode == 0 {
continue
} else {
errorMessage := fmt.Sprintf("Init container has been terminated"+
"with non zero error code. ExitCode: %d. Reason %s",
initContainerStatus.State.Terminated.ExitCode,
initContainerStatus.State.Terminated.Reason,
)
// if init container is terminated, but exit with non-zero exit code, then we check
// pod's restart policy and if it's `Never`, we exit with error; otherwise we wait
if pod.Spec.RestartPolicy == v1.RestartPolicyNever {
return false, "", errors.New(errorMessage)
} else {
notDoneReason = fmt.Sprintf("Init container %s has failed with non-zero code, "+
"but it will be restarted", initContainerStatus.Name)
return false, notDoneReason, nil
}
}
case initContainerStatus.State.Running != nil:
notDoneReason = fmt.Sprintf("Init container %s is still running", initContainerStatus.Name)
return false, notDoneReason, nil
case initContainerStatus.State.Waiting != nil:
notDoneReason = fmt.Sprintf("Init container %s hasn't started yet", initContainerStatus.Name)
return false, notDoneReason, nil
}
}
}
return true, "", nil
}
func (lc *lazyClient) getFunctionPods(ctx context.Context,
function *nuclioio.NuclioFunction) (*v1.PodList, error) {
labelSelector := common.CompileListFunctionPodsLabelSelector(function.Name)
if functionPods, err := lc.kubeClientSet.CoreV1().Pods(function.Namespace).List(ctx,
metav1.ListOptions{
LabelSelector: labelSelector,
},
); err == nil {
return functionPods, nil
} else {
return nil, errors.Wrap(err, "Failed to get function deployment's pods")
}
}
func (lc *lazyClient) createOrUpdateCronJobs(ctx context.Context,
functionLabels labels.Set,
function *nuclioio.NuclioFunction,
resources Resources) ([]*batchv1.CronJob, error) {
var cronJobs []*batchv1.CronJob
var suspendCronJobs bool
// if function was paused - suspend all cron jobs
if function.Spec.Disable {
suspendCronJobs = true
}
cronTriggerCronJobs, err := lc.createOrUpdateCronTriggerCronJobs(ctx, functionLabels, function, resources, suspendCronJobs)
if err != nil {
return nil, errors.Wrap(err, "Failed to create cron trigger cron jobs")
}
cronJobs = append(cronJobs, cronTriggerCronJobs...)
return cronJobs, nil
}
// create cron triggers as k8s cron jobs instead of creating them inside the processor
// these k8s cron jobs will invoke the function's default http trigger on their schedule/interval
// this will enable using the scale to zero functionality of http triggers for cron triggers
func (lc *lazyClient) createOrUpdateCronTriggerCronJobs(ctx context.Context,
functionLabels labels.Set,
function *nuclioio.NuclioFunction,
resources Resources,
suspendCronJobs bool) ([]*batchv1.CronJob, error) {
var cronJobs []*batchv1.CronJob
cronTriggers := functionconfig.GetTriggersByKind(function.Spec.Triggers, "cron")
// first, remove all cron-trigger-cron-jobs that are irrelevant - exists but doesn't appear on function spec (removed on update)
if err := lc.deleteRemovedCronTriggersCronJob(ctx, functionLabels, function, cronTriggers); err != nil {
return nil, errors.Wrap(err, "Failed to delete removed cron triggers cron job")
}
for triggerName, cronTrigger := range cronTriggers {
cronJobSpec, err := lc.generateCronTriggerCronJobSpec(ctx, functionLabels, function, resources, cronTrigger)
if err != nil {
return nil, errors.Wrapf(err, "Failed to generate cron job spec from cron trigger. Trigger name: %s", triggerName)
}
extraMetaLabels := labels.Set{
common.NuclioLabelKeyComponent: "cron-trigger",
common.NuclioLabelKeyFunctionCronTriggerName: triggerName,
}
cronJob, err := lc.createOrUpdateCronJob(ctx,
functionLabels,
extraMetaLabels,
function,
triggerName,
cronJobSpec,
suspendCronJobs)
if err != nil {
go func() {
if deleteCronJobsErr := lc.deleteCronJobs(ctx, function.Name, function.Namespace); deleteCronJobsErr != nil {
lc.logger.WarnWithCtx(ctx, "Failed to delete cron jobs on cron job creation failure",
"deleteCronJobsErr", deleteCronJobsErr)
}
}()
return nil, errors.Wrapf(err, "Failed to create/update cron job for trigger: %s", triggerName)
}
cronJobs = append(cronJobs, cronJob)
}
return cronJobs, nil
}
// delete every cron-trigger-cron-job of the function that has been removed from the function's triggers
func (lc *lazyClient) deleteRemovedCronTriggersCronJob(ctx context.Context,
functionLabels labels.Set,
function *nuclioio.NuclioFunction,
newCronTriggers map[string]functionconfig.Trigger) error {
// make a list of all the new cron trigger cron job names
var newCronTriggerNames []string
for newCronTriggerName := range newCronTriggers {
newCronTriggerNames = append(newCronTriggerNames, newCronTriggerName)
}
cronTriggerInNewCronTriggers, err := lc.compileCronTriggerNotInSliceLabels(newCronTriggerNames)
if err != nil {
return errors.Wrap(err, "Failed to compile cron trigger not in slice labels")
}
// retrieve all the cron jobs that aren't inside the new cron triggers, so they can be deleted
cronJobsToDelete, err := lc.kubeClientSet.
BatchV1().
CronJobs(function.Namespace).
List(ctx, metav1.ListOptions{
LabelSelector: lc.compileCronTriggerLabelSelector(function.Name, cronTriggerInNewCronTriggers),
})
if err != nil {
return errors.Wrap(err, "Failed to list cron jobs")
}
// if there's none to delete return
if len(cronJobsToDelete.Items) == 0 {
return nil
}
lc.logger.DebugWithCtx(ctx,
"Deleting removed cron trigger cron job",
"cronJobsToDelete", cronJobsToDelete)
errGroup, _ := errgroup.WithContext(ctx, lc.logger)
for _, cronJobToDelete := range cronJobsToDelete.Items {
cronJobToDelete := cronJobToDelete
errGroup.Go("DeleteCronTrigger", func() error {
// delete this removed cron trigger cron job
err := lc.kubeClientSet.BatchV1().
CronJobs(function.Namespace).
Delete(ctx, cronJobToDelete.Name, metav1.DeleteOptions{})
if err != nil {
return errors.Wrapf(err, "Failed to delete removed cron trigger cron job: %s", cronJobToDelete.Name)
}
return nil
})
}
return errGroup.Wait()
}
// as a closure so resourceExists can update
func (lc *lazyClient) createOrUpdateResource(ctx context.Context,
resourceName string,
getResource func() (interface{}, error),
resourceIsDeleting func(interface{}) bool,
createResource func() (interface{}, error),
updateResource func(interface{}) (interface{}, error)) (interface{}, error) {
var resource interface{}
var err error
updateDeadline := time.Now().Add(2 * time.Minute)
for {
waitingForDeletionDeadline := time.Now().Add(1 * time.Minute)
// get the resource until it's not deleting
for {
// get resource will return the resource
resource, err = getResource()
// if the resource is deleting, wait for it to complete deleting
if err == nil && resourceIsDeleting(resource) {
lc.logger.DebugWithCtx(ctx, "Resource is deleting, waiting", "name", resourceName)
// we need to wait a bit and try again
time.Sleep(1 * time.Second)
// if we passed the deadline
if time.Now().After(waitingForDeletionDeadline) {
return nil, errors.New("Timed out waiting for service to delete")
}
} else {
// there was either an error or the resource exists and is not being deleted
break
}
}
// if there's an error
if err != nil {
// bail if error is not "not found"
if !apierrors.IsNotFound(err) {
return nil, errors.Wrapf(err, "Failed to get resource")
}
// create the resource
resource, err = createResource()
if err != nil {
if !apierrors.IsAlreadyExists(err) {
return nil, errors.Wrap(err, "Failed to create resource")
}
// this case could happen if several controllers are running in parallel. (may happen on rolling upgrade of the controller)
lc.logger.WarnWithCtx(ctx, "Got \"resource already exists\" error on creation. Retrying (Perhaps more than 1 controller is running?)",
"name", resourceName,
"err", err.Error())
continue
}
lc.logger.DebugWithCtx(ctx, "Resource created", "name", resourceName)
return resource, nil
}
resource, err = updateResource(resource)
if err != nil {
// if there was an error and it wasn't conflict - there was an error. Bail
if !apierrors.IsConflict(err) {
return nil, errors.Wrapf(err, "Failed to update resource")
}
// if we passed the deadline
if time.Now().After(updateDeadline) {
return nil, errors.Errorf("Timed out updating resource: %s", resourceName)
}
lc.logger.DebugWithCtx(ctx, "Got conflict while trying to update resource. Retrying", "name", resourceName)
continue
}
lc.logger.DebugWithCtx(ctx, "Resource updated", "name", resourceName)
return resource, nil
}
}
func (lc *lazyClient) createOrUpdateConfigMap(ctx context.Context,
functionLabels labels.Set,
function *nuclioio.NuclioFunction) (*v1.ConfigMap, error) {
getConfigMap := func() (interface{}, error) {
return lc.kubeClientSet.CoreV1().
ConfigMaps(function.Namespace).
Get(ctx, kube.ConfigMapNameFromFunctionName(function.Name), metav1.GetOptions{})
}
configMapIsDeleting := func(resource interface{}) bool {
return (resource).(*v1.ConfigMap).ObjectMeta.DeletionTimestamp != nil
}
createConfigMap := func() (interface{}, error) {
configMap := v1.ConfigMap{}
if err := lc.populateConfigMap(functionLabels, function, &configMap); err != nil {
return nil, errors.Wrap(err, "Failed to populate configMap")
}
return lc.kubeClientSet.CoreV1().ConfigMaps(function.Namespace).Create(ctx, &configMap, metav1.CreateOptions{})
}
updateConfigMap := func(resource interface{}) (interface{}, error) {
configMap := resource.(*v1.ConfigMap)
// update existing
if err := lc.populateConfigMap(functionLabels, function, configMap); err != nil {
return nil, errors.Wrap(err, "Failed to populate configMap")
}
return lc.kubeClientSet.CoreV1().ConfigMaps(function.Namespace).Update(ctx, configMap, metav1.UpdateOptions{})
}
resource, err := lc.createOrUpdateResource(ctx,
"configMap",
getConfigMap,
configMapIsDeleting,
createConfigMap,
updateConfigMap)
if err != nil {
return nil, err
}
return resource.(*v1.ConfigMap), err
}