/
lazy.go
2143 lines (1744 loc) · 67.5 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 2017 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"
"path/filepath"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/nuclio/nuclio/pkg/common"
"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/aws/aws-sdk-go/private/util"
"github.com/ghodss/yaml"
"github.com/imdario/mergo"
"github.com/mitchellh/mapstructure"
"github.com/nuclio/errors"
"github.com/nuclio/logger"
"github.com/v3io/version-go"
"golang.org/x/sync/errgroup"
appsv1 "k8s.io/api/apps/v1"
autosv2 "k8s.io/api/autoscaling/v2beta1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
"k8s.io/api/core/v1"
extv1beta1 "k8s.io/api/extensions/v1beta1"
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/util/intstr"
"k8s.io/client-go/kubernetes"
)
const (
ContainerHTTPPortName = "http"
containerMetricPort = 8090
containerMetricPortName = "metrics"
nginxIngressUpdateGracePeriod = 5 * time.Second
)
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
}
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),
}
newClient.initClassLabels()
return &newClient, nil
}
func (lc *lazyClient) List(ctx context.Context, namespace string) ([]Resources, error) {
listOptions := metav1.ListOptions{
LabelSelector: "nuclio.io/class=function",
}
result, err := lc.kubeClientSet.AppsV1().Deployments(namespace).List(listOptions)
if err != nil {
return nil, errors.Wrap(err, "Failed to list deployments")
}
lc.logger.DebugWith("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(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["nuclio.io/function-name"] = function.Name
// TODO: remove when versioning is back in
function.Spec.Version = -1
function.Spec.Alias = "latest"
functionLabels["nuclio.io/function-version"] = "latest"
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")
}
err = yaml.Unmarshal(encodedFunctionConfig, function)
if 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(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(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(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(functionLabels,
function); err != nil {
return nil, errors.Wrap(err, "Failed to create/update HPA")
}
// create or update ingress
if resources.ingress, err = lc.createOrUpdateIngress(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(functionLabels, function, &resources); err != nil {
return nil, errors.Wrap(err, "Failed to create cron jobs from cron triggers")
}
}
lc.logger.DebugWith("Successfully created/updated resources",
"functionName", function.Name,
"functionNamespace", function.Namespace)
return &resources, nil
}
func (lc *lazyClient) WaitAvailable(ctx context.Context, namespace string, name string) error {
deploymentName := kube.DeploymentNameFromFunctionName(name)
lc.logger.DebugWith("Waiting for deployment to be available",
"namespace", namespace,
"functionName", name,
"deploymentName", deploymentName)
waitMs := 250
for {
// wait a bit
time.Sleep(time.Duration(waitMs) * time.Millisecond)
// exponentially wait more next time, up to 2 seconds
waitMs *= 2
if waitMs > 2000 {
waitMs = 2000
}
// check if context is still OK
if err := ctx.Err(); err != nil {
return err
}
// get the deployment. if it doesn't exist yet, retry a bit later
result, err := lc.kubeClientSet.AppsV1().
Deployments(namespace).
Get(deploymentName, metav1.GetOptions{})
if err != nil {
continue
}
// find the condition whose type is Available - that's the one we want to examine
for _, deploymentCondition := range result.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 && result.Status.UnavailableReplicas == 0 {
lc.logger.DebugWith("Deployment is available",
"reason", deploymentCondition.Reason,
"deploymentName", deploymentName)
return nil
}
lc.logger.DebugWith("Deployment not available yet",
"reason", deploymentCondition.Reason,
"unavailableReplicas", result.Status.UnavailableReplicas,
"deploymentName", deploymentName)
// we found the condition, wasn't available
break
}
}
}
}
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.ExtensionsV1beta1().Ingresses(namespace).Delete(ingressName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete ingress")
}
} else {
lc.logger.DebugWith("Deleted ingress", "namespace", namespace, "ingressName", ingressName)
}
// Delete HPA if exists
hpaName := kube.HPANameFromFunctionName(name)
err = lc.kubeClientSet.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).Delete(hpaName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete HPA")
}
} else {
lc.logger.DebugWith("Deleted HPA", "namespace", namespace, "hpaName", hpaName)
}
// Delete Service if exists
serviceName := kube.ServiceNameFromFunctionName(name)
err = lc.kubeClientSet.CoreV1().Services(namespace).Delete(serviceName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete service")
}
} else {
lc.logger.DebugWith("Deleted service", "namespace", namespace, "serviceName", serviceName)
}
// Delete Deployment if exists
deploymentName := kube.DeploymentNameFromFunctionName(name)
err = lc.kubeClientSet.AppsV1().Deployments(namespace).Delete(deploymentName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete deployment")
}
} else {
lc.logger.DebugWith("Deleted deployment",
"namespace", namespace,
"deploymentName", deploymentName)
}
// Delete configMap if exists
configMapName := kube.ConfigMapNameFromFunctionName(name)
err = lc.kubeClientSet.CoreV1().ConfigMaps(namespace).Delete(configMapName, deleteOptions)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrap(err, "Failed to delete configMap")
}
} else {
lc.logger.DebugWith("Deleted configMap", "namespace", namespace, "configMapName", configMapName)
}
if err = lc.deleteFunctionEvents(ctx, name, namespace); err != nil {
return errors.Wrap(err, "Failed to delete function events")
}
if lc.platformConfigurationProvider.GetPlatformConfiguration().CronTriggerCreationMode == platformconfig.KubeCronTriggerCreationMode {
if err = lc.deleteCronJobs(name, namespace); err != nil {
return errors.Wrap(err, "Failed to delete function cron jobs")
}
}
lc.logger.DebugWith("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) createOrUpdateCronJobs(functionLabels labels.Set,
function *nuclioio.NuclioFunction,
resources Resources) ([]*batchv1beta1.CronJob, error) {
var cronJobs []*batchv1beta1.CronJob
var suspendCronJobs bool
// if function was paused - suspend all cron jobs
if function.Spec.Disable {
suspendCronJobs = true
}
cronTriggerCronJobs, err := lc.createOrUpdateCronTriggerCronJobs(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(functionLabels labels.Set,
function *nuclioio.NuclioFunction,
resources Resources,
suspendCronJobs bool) ([]*batchv1beta1.CronJob, error) {
var cronJobs []*batchv1beta1.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(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(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{
"nuclio.io/component": "cron-trigger",
"nuclio.io/function-cron-trigger-name": triggerName,
}
cronJob, err := lc.createOrUpdateCronJob(functionLabels,
extraMetaLabels,
function,
triggerName,
cronJobSpec,
suspendCronJobs)
if err != nil {
go func() {
if deleteCronJobsErr := lc.deleteCronJobs(function.Name, function.Namespace); deleteCronJobsErr != nil {
lc.logger.WarnWith("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(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.BatchV1beta1().CronJobs(function.Namespace).List(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.DebugWith("Deleting removed cron trigger cron job",
"cronJobsToDelete", cronJobsToDelete)
errGroup := errgroup.Group{}
for _, cronJobToDelete := range cronJobsToDelete.Items {
cronJobToDelete := cronJobToDelete
errGroup.Go(func() error {
// delete this removed cron trigger cron job
err := lc.kubeClientSet.BatchV1beta1().
CronJobs(function.Namespace).
Delete(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(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.DebugWith("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 {
// if there was an error and it wasn't not found - there was an error. bail
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.WarnWith("Got \"resource already exists\" error on creation. Retrying (Perhaps more than 1 controller is running?)",
"name", resourceName,
"err", err.Error())
continue
}
lc.logger.DebugWith("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.DebugWith("Got conflict while trying to update resource. Retrying", "name", resourceName)
continue
}
lc.logger.DebugWith("Resource updated", "name", resourceName)
return resource, nil
}
}
func (lc *lazyClient) createOrUpdateConfigMap(function *nuclioio.NuclioFunction) (*v1.ConfigMap, error) {
getConfigMap := func() (interface{}, error) {
return lc.kubeClientSet.CoreV1().
ConfigMaps(function.Namespace).
Get(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(nil, function, &configMap); err != nil {
return nil, errors.Wrap(err, "Failed to populate configMap")
}
return lc.kubeClientSet.CoreV1().ConfigMaps(function.Namespace).Create(&configMap)
}
updateConfigMap := func(resource interface{}) (interface{}, error) {
configMap := resource.(*v1.ConfigMap)
// update existing
if err := lc.populateConfigMap(nil, function, configMap); err != nil {
return nil, errors.Wrap(err, "Failed to populate configMap")
}
return lc.kubeClientSet.CoreV1().ConfigMaps(function.Namespace).Update(configMap)
}
resource, err := lc.createOrUpdateResource("configMap",
getConfigMap,
configMapIsDeleting,
createConfigMap,
updateConfigMap)
if err != nil {
return nil, err
}
return resource.(*v1.ConfigMap), err
}
func (lc *lazyClient) createOrUpdateService(functionLabels labels.Set,
function *nuclioio.NuclioFunction) (*v1.Service, error) {
getService := func() (interface{}, error) {
return lc.kubeClientSet.CoreV1().
Services(function.Namespace).
Get(kube.ServiceNameFromFunctionName(function.Name), metav1.GetOptions{})
}
serviceIsDeleting := func(resource interface{}) bool {
return (resource).(*v1.Service).ObjectMeta.DeletionTimestamp != nil
}
createService := func() (interface{}, error) {
spec := v1.ServiceSpec{}
lc.populateServiceSpec(functionLabels, function, &spec)
return lc.kubeClientSet.CoreV1().Services(function.Namespace).Create(&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: kube.ServiceNameFromFunctionName(function.Name),
Namespace: function.Namespace,
Labels: functionLabels,
},
Spec: spec,
})
}
updateService := func(resource interface{}) (interface{}, error) {
service := resource.(*v1.Service)
// update existing
service.Labels = functionLabels
lc.populateServiceSpec(functionLabels, function, &service.Spec)
return lc.kubeClientSet.CoreV1().Services(function.Namespace).Update(service)
}
resource, err := lc.createOrUpdateResource("service",
getService,
serviceIsDeleting,
createService,
updateService)
if err != nil {
return nil, err
}
return resource.(*v1.Service), err
}
func (lc *lazyClient) createOrUpdateDeployment(functionLabels labels.Set,
imagePullSecrets string,
function *nuclioio.NuclioFunction) (*appsv1.Deployment, error) {
// to make sure the pod re-pulls the image, we need to specify a unique string here
podAnnotations, err := lc.getPodAnnotations(function)
if err != nil {
return nil, errors.Wrap(err, "Failed to get pod annotations")
}
replicas := function.GetComputedReplicas()
if replicas != nil {
lc.logger.DebugWith("Got replicas", "replicas", *replicas, "functionName", function.Name)
}
deploymentAnnotations, err := lc.getDeploymentAnnotations(function)
if err != nil {
return nil, errors.Wrap(err, "Failed to get function annotations")
}
// get volumes and volumeMounts from configuration
volumes, volumeMounts := lc.getFunctionVolumeAndMounts(function)
getDeployment := func() (interface{}, error) {
return lc.kubeClientSet.AppsV1().
Deployments(function.Namespace).
Get(kube.DeploymentNameFromFunctionName(function.Name), metav1.GetOptions{})
}
deploymentIsDeleting := func(resource interface{}) bool {
return (resource).(*appsv1.Deployment).ObjectMeta.DeletionTimestamp != nil
}
if function.Spec.ImagePullSecrets != "" {
imagePullSecrets = function.Spec.ImagePullSecrets
}
createDeployment := func() (interface{}, error) {
method := createDeploymentResourceMethod
container := v1.Container{Name: "nuclio"}
lc.populateDeploymentContainer(functionLabels, function, &container)
container.VolumeMounts = volumeMounts
deploymentSpec := appsv1.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: functionLabels,
},
Replicas: replicas,
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: kube.PodNameFromFunctionName(function.Name),
Namespace: function.Namespace,
Labels: functionLabels,
Annotations: podAnnotations,
},
Spec: v1.PodSpec{
ImagePullSecrets: []v1.LocalObjectReference{
{Name: imagePullSecrets},
},
Containers: []v1.Container{
container,
},
Volumes: volumes,
ServiceAccountName: function.Spec.ServiceAccount,
SecurityContext: function.Spec.SecurityContext,
},
},
}
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: kube.DeploymentNameFromFunctionName(function.Name),
Namespace: function.Namespace,
Labels: functionLabels,
Annotations: deploymentAnnotations,
},
Spec: deploymentSpec,
}
// enrich deployment spec with default fields that were passed inside the platform configuration
if err := lc.enrichDeploymentFromPlatformConfiguration(function, deployment, method); err != nil {
return nil, err
}
return lc.kubeClientSet.AppsV1().Deployments(function.Namespace).Create(deployment)
}
updateDeployment := func(resource interface{}) (interface{}, error) {
deployment := resource.(*appsv1.Deployment)
method := updateDeploymentResourceMethod
// If we got nil replicas it means leave as is (in order to prevent unwanted scale down)
// but need to make sure the current replicas is not less than the min replicas
if replicas == nil {
minReplicas := function.GetComputedMinReplicas()
maxReplicas := function.GetComputedMaxReplicas()
deploymentReplicas := deployment.Status.Replicas
lc.logger.DebugWith("Verifying current replicas not lower than minReplicas or higher than max",
"functionName", function.Name,
"maxReplicas", maxReplicas,
"minReplicas", minReplicas,
"deploymentReplicas", deploymentReplicas)
switch {
case deploymentReplicas > maxReplicas:
replicas = &maxReplicas
case deploymentReplicas < minReplicas:
replicas = &minReplicas
default:
// if we're within the valid range - and want to leave as is (since replicas == nil) - use current value
// NOTE: since we're using the existing deployment (given by our get function) ResourceVersion is set
// meaning the update will fail with conflict if something has changed in the meanwhile (e.g. HPA
// changed the replicas count) - retry is handled by the createOrUpdateResource wrapper
replicas = &deploymentReplicas
}
}
deployment.Annotations = deploymentAnnotations
deployment.Spec.Replicas = replicas
deployment.Spec.Template.Annotations = podAnnotations
lc.populateDeploymentContainer(functionLabels, function, &deployment.Spec.Template.Spec.Containers[0])
deployment.Spec.Template.Spec.Volumes = volumes
deployment.Spec.Template.Spec.Containers[0].VolumeMounts = volumeMounts
deployment.Spec.Template.Spec.SecurityContext = function.Spec.SecurityContext
if function.Spec.ServiceAccount != "" {
deployment.Spec.Template.Spec.ServiceAccountName = function.Spec.ServiceAccount
}
// enrich deployment spec with default fields that were passed inside the platform configuration
// performed on update too, in case the platform config has been modified after the creation of this deployment
if err := lc.enrichDeploymentFromPlatformConfiguration(function, deployment, method); err != nil {
return nil, err
}
return lc.kubeClientSet.AppsV1().Deployments(function.Namespace).Update(deployment)
}
resource, err := lc.createOrUpdateResource("deployment",
getDeployment,
deploymentIsDeleting,
createDeployment,
updateDeployment)
if err != nil {
return nil, err
}
return resource.(*appsv1.Deployment), err
}
func (lc *lazyClient) resolveDeploymentStrategy(function *nuclioio.NuclioFunction) appsv1.DeploymentStrategyType {
// Since k8s (ATM) does not support rolling update for GPU
// redeploying a Nuclio function will get stuck if no GPU is available
// to overcome it, we simply change the update strategy to recreate
// so k8s will kill the existing pod\function and create the new one
if function.Spec.PositiveGPUResourceLimit() {
// requested a gpu resource, change to recreate
return appsv1.RecreateDeploymentStrategyType
}
// no gpu resources requested, set to rollingUpdate (default)
return appsv1.RollingUpdateDeploymentStrategyType
}
func (lc *lazyClient) enrichDeploymentFromPlatformConfiguration(function *nuclioio.NuclioFunction,
deployment *appsv1.Deployment, method deploymentResourceMethod) error {
var allowSetDeploymentStrategy = true
// get deployment augmented configurations
deploymentAugmentedConfigs, err := lc.getDeploymentAugmentedConfigs(function)
if err != nil {
return errors.Wrap(err, "Failed to get deployment augmented configs")
}
// merge
for _, augmentedConfig := range deploymentAugmentedConfigs {
if augmentedConfig.Kubernetes.Deployment != nil {
if augmentedConfig.Kubernetes.Deployment.Spec.Strategy.Type != "" ||
augmentedConfig.Kubernetes.Deployment.Spec.Strategy.RollingUpdate != nil {
allowSetDeploymentStrategy = false
}
if err := mergo.Merge(&deployment.Spec, &augmentedConfig.Kubernetes.Deployment.Spec); err != nil {
return errors.Wrap(err, "Failed to merge deployment spec")
}
}
}
switch method {
// on create, change inplace the deployment strategy
case createDeploymentResourceMethod:
if allowSetDeploymentStrategy {
deployment.Spec.Strategy.Type = lc.resolveDeploymentStrategy(function)
}
case updateDeploymentResourceMethod:
if allowSetDeploymentStrategy {
newDeploymentStrategyType := lc.resolveDeploymentStrategy(function)
if newDeploymentStrategyType != deployment.Spec.Strategy.Type {
// if current strategy is rolling update, in order to change it to `Recreate`
// we must remove `rollingUpdate` field
if deployment.Spec.Strategy.Type == appsv1.RollingUpdateDeploymentStrategyType &&
newDeploymentStrategyType == appsv1.RecreateDeploymentStrategyType {
deployment.Spec.Strategy.RollingUpdate = nil
}
deployment.Spec.Strategy.Type = newDeploymentStrategyType
}
}
}
return nil
}
func (lc *lazyClient) getDeploymentAugmentedConfigs(function *nuclioio.NuclioFunction) ([]platformconfig.LabelSelectorAndConfig, error) {
var configs []platformconfig.LabelSelectorAndConfig
// get the function labels
functionLabels := lc.getFunctionLabels(function)
// get platform config
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 deployment with provided function config
// NOTE: supports spec only for now. in the future we can remove .Spec and try to merge both meta and spec
if selector.Matches(functionLabels) {
configs = append(configs, augmentedConfig)
}
}
return configs, nil
}
func (lc *lazyClient) createOrUpdateHorizontalPodAutoscaler(functionLabels labels.Set,
function *nuclioio.NuclioFunction) (*autosv2.HorizontalPodAutoscaler, error) {
minReplicas := function.GetComputedMinReplicas()
maxReplicas := function.GetComputedMaxReplicas()
lc.logger.DebugWith("Create/Update hpa",
"functionName", function.Name,
"minReplicas", minReplicas,
"maxReplicas", maxReplicas)
// hpa min replicas must be equal or greater than 1
if minReplicas < 1 {
minReplicas = int32(1)
}
// hpa max replicas must be equal or greater than 1
if maxReplicas < 1 {
maxReplicas = int32(1)
}
targetCPU := int32(function.Spec.TargetCPU)
if targetCPU == 0 {
targetCPU = abstract.DefaultTargetCPU
}
getHorizontalPodAutoscaler := func() (interface{}, error) {
return lc.kubeClientSet.AutoscalingV2beta1().
HorizontalPodAutoscalers(function.Namespace).
Get(kube.HPANameFromFunctionName(function.Name), metav1.GetOptions{})
}
horizontalPodAutoscalerIsDeleting := func(resource interface{}) bool {
return (resource).(*autosv2.HorizontalPodAutoscaler).ObjectMeta.DeletionTimestamp != nil
}
createHorizontalPodAutoscaler := func() (interface{}, error) {
if minReplicas == maxReplicas {
return nil, nil
}
metricSpecs, err := lc.GetFunctionMetricSpecs(function.Name, targetCPU)
if err != nil {
return nil, errors.Wrap(err, "Failed to get function metric specs")
}
hpa := autosv2.HorizontalPodAutoscaler{
ObjectMeta: metav1.ObjectMeta{
Name: kube.HPANameFromFunctionName(function.Name),
Namespace: function.Namespace,
Labels: functionLabels,
},
Spec: autosv2.HorizontalPodAutoscalerSpec{
MinReplicas: &minReplicas,
MaxReplicas: maxReplicas,
Metrics: metricSpecs,
ScaleTargetRef: autosv2.CrossVersionObjectReference{
APIVersion: "apps/apps_v1",
Kind: "Deployment",
Name: kube.DeploymentNameFromFunctionName(function.Name),
},
},
}
return lc.kubeClientSet.AutoscalingV2beta1().HorizontalPodAutoscalers(function.Namespace).Create(&hpa)
}
updateHorizontalPodAutoscaler := func(resourceToUpdate interface{}) (interface{}, error) {
hpa := resourceToUpdate.(*autosv2.HorizontalPodAutoscaler)
metricSpecs, err := lc.GetFunctionMetricSpecs(function.Name, targetCPU)