-
Notifications
You must be signed in to change notification settings - Fork 835
/
seldondeployment_controller.go
2039 lines (1821 loc) · 76.1 KB
/
seldondeployment_controller.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 2019 The Seldon 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 controllers
import (
"bytes"
"context"
"fmt"
"net/url"
"strconv"
"strings"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"knative.dev/pkg/apis"
types2 "github.com/gogo/protobuf/types"
"github.com/seldonio/seldon-core/operator/constants"
"github.com/seldonio/seldon-core/operator/utils"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/tools/record"
"knative.dev/pkg/kmp"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/go-logr/logr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"encoding/json"
kedav1alpha1 "github.com/kedacore/keda/v2/apis/keda/v1alpha1"
machinelearningv1 "github.com/seldonio/seldon-core/operator/apis/machinelearning.seldon.io/v1"
istio_networking "istio.io/api/networking/v1alpha3"
istio "istio.io/client-go/pkg/apis/networking/v1alpha3"
appsv1 "k8s.io/api/apps/v1"
autoscaling "k8s.io/api/autoscaling/v2beta1"
corev1 "k8s.io/api/core/v1"
policy "k8s.io/api/policy/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
ENV_DEFAULT_ENGINE_SERVER_PORT = "ENGINE_SERVER_PORT"
ENV_DEFAULT_ENGINE_SERVER_GRPC_PORT = "ENGINE_SERVER_GRPC_PORT"
ENV_CONTROLLER_ID = "CONTROLLER_ID"
ENV_PREDICTIVE_UNIT_DEFAULT_ENV_SECRET_REF_NAME = "PREDICTIVE_UNIT_DEFAULT_ENV_SECRET_REF_NAME"
// This env var in the operator allows you to change the default path
// to mount the cert in the containers
ENV_DEFAULT_CERT_MOUNT_PATH_NAME = "DEFAULT_CERT_MOUNT_PATH_NAME"
// The ENV VAR NAME for containers to be able to find the path
SELDON_MOUNT_PATH_ENV_NAME = "SELDON_CERT_MOUNT_PATH"
DEFAULT_ENGINE_CONTAINER_PORT = 8000
DEFAULT_ENGINE_GRPC_PORT = 5001
AMBASSADOR_ANNOTATION = "getambassador.io/config"
LABEL_CONTROLLER_ID = "seldon.io/controller-id"
ENV_KEDA_ENABLED = "KEDA_ENABLED"
)
var (
envDefaultCertMountPath = utils.GetEnv(ENV_DEFAULT_CERT_MOUNT_PATH_NAME, "/cert/")
PredictiveUnitDefaultEnvSecretRefName = utils.GetEnv(ENV_PREDICTIVE_UNIT_DEFAULT_ENV_SECRET_REF_NAME, "")
)
// SeldonDeploymentReconciler reconciles a SeldonDeployment object
type SeldonDeploymentReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
Namespace string
Recorder record.EventRecorder
ClientSet kubernetes.Interface
}
//---------------- Old part
type components struct {
serviceDetails map[string]*machinelearningv1.ServiceStatus
deployments []*appsv1.Deployment
services []*corev1.Service
hpas []*autoscaling.HorizontalPodAutoscaler
kedaScaledObjects []*kedav1alpha1.ScaledObject
pdbs []*policy.PodDisruptionBudget
virtualServices []*istio.VirtualService
destinationRules []*istio.DestinationRule
defaultDeploymentName string
addressable *machinelearningv1.SeldonAddressable
}
type httpGrpcPorts struct {
httpPort int
grpcPort int
}
func init() {
// Allow unknown fields in Istio API client. This is so that we are more resilience
// in cases user clusers have malformed resources.
istio_networking.VirtualServiceUnmarshaler.AllowUnknownFields = true
istio_networking.GatewayUnmarshaler.AllowUnknownFields = true
}
func createAddressableResource(mlDep *machinelearningv1.SeldonDeployment, namespace string, externalPorts []httpGrpcPorts) (*machinelearningv1.SeldonAddressable, error) {
// It was an explicit design decision to expose the service name instead of the ingress
// Currently there will only be a URL for the first predictor, and assumes always REST
firstPredictor := &mlDep.Spec.Predictors[0]
sdepSvcName := machinelearningv1.GetPredictorKey(mlDep, firstPredictor)
addressableHost := sdepSvcName + "." + namespace + ".svc.cluster.local" + ":" + strconv.Itoa(externalPorts[0].httpPort)
addressablePath := utils.GetPredictionPath(mlDep)
addressableUrl := url.URL{Scheme: "http", Host: addressableHost, Path: addressablePath}
return &machinelearningv1.SeldonAddressable{URL: addressableUrl.String()}, nil
}
func createKeda(podSpec *machinelearningv1.SeldonPodSpec, deploymentName string, seldonId string, namespace string) *kedav1alpha1.ScaledObject {
kedaScaledObj := &kedav1alpha1.ScaledObject{
ObjectMeta: metav1.ObjectMeta{
Name: deploymentName,
Namespace: namespace,
Labels: map[string]string{machinelearningv1.Label_seldon_id: seldonId},
},
Spec: kedav1alpha1.ScaledObjectSpec{
PollingInterval: podSpec.KedaSpec.PollingInterval,
CooldownPeriod: podSpec.KedaSpec.CooldownPeriod,
IdleReplicaCount: podSpec.KedaSpec.IdleReplicaCount,
MaxReplicaCount: podSpec.KedaSpec.MaxReplicaCount,
MinReplicaCount: podSpec.KedaSpec.MinReplicaCount,
Advanced: podSpec.KedaSpec.Advanced,
Triggers: podSpec.KedaSpec.Triggers,
ScaleTargetRef: &kedav1alpha1.ScaleTarget{
APIVersion: "apps/v1",
Kind: "Deployment",
Name: deploymentName,
},
Fallback: podSpec.KedaSpec.Fallback,
},
}
return kedaScaledObj
}
func createHpa(podSpec *machinelearningv1.SeldonPodSpec, deploymentName string, seldonId string, namespace string) *autoscaling.HorizontalPodAutoscaler {
hpa := autoscaling.HorizontalPodAutoscaler{
ObjectMeta: metav1.ObjectMeta{
Name: deploymentName,
Namespace: namespace,
Labels: map[string]string{machinelearningv1.Label_seldon_id: seldonId},
},
Spec: autoscaling.HorizontalPodAutoscalerSpec{
ScaleTargetRef: autoscaling.CrossVersionObjectReference{
Name: deploymentName,
APIVersion: "apps/v1",
Kind: "Deployment",
},
MaxReplicas: podSpec.HpaSpec.MaxReplicas,
Metrics: podSpec.HpaSpec.Metrics,
},
}
if podSpec.HpaSpec.MinReplicas != nil {
hpa.Spec.MinReplicas = podSpec.HpaSpec.MinReplicas
}
return &hpa
}
func createPdb(podSpec *machinelearningv1.SeldonPodSpec, deploymentName string, seldonId string, namespace string) *policy.PodDisruptionBudget {
pdb := policy.PodDisruptionBudget{
ObjectMeta: metav1.ObjectMeta{
Name: deploymentName,
Namespace: namespace,
Labels: map[string]string{machinelearningv1.Label_seldon_id: seldonId},
},
Spec: policy.PodDisruptionBudgetSpec{
MinAvailable: podSpec.PdbSpec.MinAvailable,
MaxUnavailable: podSpec.PdbSpec.MaxUnavailable,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{machinelearningv1.Label_seldon_id: seldonId},
},
},
}
return &pdb
}
// Create istio virtual service and destination rule.
// Creates routes for each predictor with traffic weight split
func createIstioResources(mlDep *machinelearningv1.SeldonDeployment,
seldonId string,
namespace string,
ports []httpGrpcPorts) ([]*istio.VirtualService, []*istio.DestinationRule, error) {
istio_gateway := utils.GetEnv(ENV_ISTIO_GATEWAY, "seldon-gateway")
istioTLSMode := utils.GetEnv(ENV_ISTIO_TLS_MODE, "")
istioRetriesAnnotation := getAnnotation(mlDep, ANNOTATION_ISTIO_RETRIES, "")
istioRetriesTimeoutAnnotation := getAnnotation(mlDep, ANNOTATION_ISTIO_RETRIES_TIMEOUT, "1")
istioRetries := 0
istioRetriesTimeout := 1
var err error
if istioRetriesAnnotation != "" {
istioRetries, err = strconv.Atoi(istioRetriesAnnotation)
if err != nil {
return nil, nil, err
}
istioRetriesTimeout, err = strconv.Atoi(istioRetriesTimeoutAnnotation)
if err != nil {
return nil, nil, err
}
}
vsvc := &istio.VirtualService{
ObjectMeta: metav1.ObjectMeta{
Name: seldonId,
Namespace: namespace,
},
Spec: istio_networking.VirtualService{
Hosts: []string{getAnnotation(mlDep, ANNOTATION_ISTIO_HOST, "*")},
Gateways: []string{getAnnotation(mlDep, ANNOTATION_ISTIO_GATEWAY, istio_gateway)},
Http: []*istio_networking.HTTPRoute{
{
Match: []*istio_networking.HTTPMatchRequest{
{
Uri: &istio_networking.StringMatch{MatchType: &istio_networking.StringMatch_Prefix{Prefix: "/seldon/" + namespace + "/" + mlDep.Name + "/"}},
},
},
Rewrite: &istio_networking.HTTPRewrite{Uri: "/"},
},
{
Match: []*istio_networking.HTTPMatchRequest{
{
Uri: &istio_networking.StringMatch{MatchType: &istio_networking.StringMatch_Regex{Regex: constants.GRPCRegExMatchIstio}},
Headers: map[string]*istio_networking.StringMatch{
"seldon": &istio_networking.StringMatch{MatchType: &istio_networking.StringMatch_Exact{Exact: mlDep.Name}},
"namespace": &istio_networking.StringMatch{MatchType: &istio_networking.StringMatch_Exact{Exact: namespace}},
},
},
},
},
},
},
}
// Add retries
if istioRetries > 0 {
vsvc.Spec.Http[0].Retries = &istio_networking.HTTPRetry{Attempts: int32(istioRetries), PerTryTimeout: &types2.Duration{Seconds: int64(istioRetriesTimeout)}, RetryOn: "gateway-error,connect-failure,refused-stream"}
vsvc.Spec.Http[1].Retries = &istio_networking.HTTPRetry{Attempts: int32(istioRetries), PerTryTimeout: &types2.Duration{Seconds: int64(istioRetriesTimeout)}, RetryOn: "gateway-error,connect-failure,refused-stream"}
}
// shadows don't get destinations in the vs as a shadow is a mirror instead
var shadows int = 0
for i := 0; i < len(mlDep.Spec.Predictors); i++ {
p := mlDep.Spec.Predictors[i]
if p.Shadow == true {
shadows += 1
}
}
routesHttp := make([]*istio_networking.HTTPRouteDestination, len(mlDep.Spec.Predictors)-shadows)
routesGrpc := make([]*istio_networking.HTTPRouteDestination, len(mlDep.Spec.Predictors)-shadows)
// the shdadow/mirror entry does need a DestinationRule though
drules := make([]*istio.DestinationRule, len(mlDep.Spec.Predictors))
routesIdx := 0
for i := 0; i < len(mlDep.Spec.Predictors); i++ {
p := mlDep.Spec.Predictors[i]
pSvcName := machinelearningv1.GetPredictorKey(mlDep, &p)
drule := &istio.DestinationRule{
ObjectMeta: metav1.ObjectMeta{
Name: pSvcName,
Namespace: namespace,
},
Spec: istio_networking.DestinationRule{
Host: pSvcName,
Subsets: []*istio_networking.Subset{
{
Name: p.Name,
Labels: map[string]string{
"version": p.Labels["version"],
},
},
},
TrafficPolicy: &istio_networking.TrafficPolicy{ConnectionPool: &istio_networking.ConnectionPoolSettings{Http: &istio_networking.ConnectionPoolSettings_HTTPSettings{IdleTimeout: &types2.Duration{Seconds: 60}}}},
},
}
if istioTLSMode != "" {
drule.Spec.TrafficPolicy = &istio_networking.TrafficPolicy{
Tls: &istio_networking.TLSSettings{
Mode: istio_networking.TLSSettings_TLSmode(istio_networking.TLSSettings_TLSmode_value[istioTLSMode]),
},
}
}
drules[i] = drule
if p.Shadow == true {
//if there's a shadow then add a mirror section to the VirtualService
vsvc.Spec.Http[0].Mirror = &istio_networking.Destination{
Host: pSvcName,
Subset: p.Name,
Port: &istio_networking.PortSelector{
Number: uint32(ports[i].httpPort),
},
}
vsvc.Spec.Http[1].Mirror = &istio_networking.Destination{
Host: pSvcName,
Subset: p.Name,
Port: &istio_networking.PortSelector{
Number: uint32(ports[i].grpcPort),
},
}
if p.Traffic > 0 {
//if shadow predictor's traffic is greater than 0, set the mirror percentage (like https://istio.io/latest/docs/tasks/traffic-management/mirroring/#mirroring-traffic-to-v2) in VirtualService
vsvc.Spec.Http[0].MirrorPercentage = &istio_networking.Percent{
Value: float64(p.Traffic),
}
vsvc.Spec.Http[1].MirrorPercentage = &istio_networking.Percent{
Value: float64(p.Traffic),
}
}
continue
}
//we split by adding different routes with their own Weights
//so not by tag - different destinations (like https://istio.io/docs/tasks/traffic-management/traffic-shifting/) distinguished by host
routesHttp[routesIdx] = &istio_networking.HTTPRouteDestination{
Destination: &istio_networking.Destination{
Host: pSvcName,
Subset: p.Name,
Port: &istio_networking.PortSelector{
Number: uint32(ports[i].httpPort),
},
},
Weight: p.Traffic,
}
routesGrpc[routesIdx] = &istio_networking.HTTPRouteDestination{
Destination: &istio_networking.Destination{
Host: pSvcName,
Subset: p.Name,
Port: &istio_networking.PortSelector{
Number: uint32(ports[i].grpcPort),
},
},
Weight: p.Traffic,
}
routesIdx += 1
}
vsvc.Spec.Http[0].Route = routesHttp
vsvc.Spec.Http[1].Route = routesGrpc
vscs := make([]*istio.VirtualService, 1)
vscs[0] = vsvc
return vscs, drules, nil
}
func getEngineHttpPort() (engine_http_port int, err error) {
// Get engine http port from environment or use default
engine_http_port = DEFAULT_ENGINE_CONTAINER_PORT
var env_engine_http_port = utils.GetEnv(ENV_DEFAULT_ENGINE_SERVER_PORT, "")
if env_engine_http_port != "" {
engine_http_port, err = strconv.Atoi(env_engine_http_port)
if err != nil {
return 0, err
}
}
return engine_http_port, nil
}
func getEngineGrpcPort() (engine_grpc_port int, err error) {
// Get engine grpc port from environment or use default
engine_grpc_port = DEFAULT_ENGINE_GRPC_PORT
var env_engine_grpc_port = utils.GetEnv(ENV_DEFAULT_ENGINE_SERVER_GRPC_PORT, "")
if env_engine_grpc_port != "" {
engine_grpc_port, err = strconv.Atoi(env_engine_grpc_port)
if err != nil {
return 0, err
}
}
return engine_grpc_port, nil
}
// Create all the components (Deployments, Services etc)
func (r *SeldonDeploymentReconciler) createComponents(ctx context.Context, mlDep *machinelearningv1.SeldonDeployment, securityContext *corev1.PodSecurityContext, log logr.Logger) (*components, error) {
c := components{}
c.serviceDetails = map[string]*machinelearningv1.ServiceStatus{}
seldonId := machinelearningv1.GetSeldonDeploymentName(mlDep)
namespace := getNamespace(mlDep)
engine_http_port, err := getEngineHttpPort()
if err != nil {
return nil, err
}
engine_grpc_port, err := getEngineGrpcPort()
if err != nil {
return nil, err
}
// variables to collect what ports will be exposed and whether we should expose http and grpc externally
// If one of the predictors has noEngine then only one of http or grpc should be allowed dependent on
// the type of the noEngine model: whether it is http or grpc
externalPorts := make([]httpGrpcPorts, len(mlDep.Spec.Predictors))
for i := 0; i < len(mlDep.Spec.Predictors); i++ {
p := mlDep.Spec.Predictors[i]
noEngine := strings.ToLower(p.Annotations[machinelearningv1.ANNOTATION_NO_ENGINE]) == "true"
pSvcName := machinelearningv1.GetPredictorKey(mlDep, &p)
log.Info("pSvcName", "val", pSvcName)
// SSL config is used to set ssl on each container
certSecretRefName := ""
predictorCertConfig := p.SSL
if predictorCertConfig != nil {
certSecretRefName = predictorCertConfig.CertSecretName
}
// Add engine deployment if separate
hasSeparateEnginePod := strings.ToLower(mlDep.Spec.Annotations[machinelearningv1.ANNOTATION_SEPARATE_ENGINE]) == "true"
if hasSeparateEnginePod && !noEngine {
deploy, err := createEngineDeployment(mlDep, &p, pSvcName, engine_http_port, engine_grpc_port)
if err != nil {
return nil, err
}
if securityContext != nil {
deploy.Spec.Template.Spec.SecurityContext = securityContext
}
// Add secret ref name to the container of the separate svcorch if created
if len(certSecretRefName) > 0 {
utils.MountSecretToDeploymentContainers(deploy, certSecretRefName, envDefaultCertMountPath)
certEnvVar := &corev1.EnvVar{Name: SELDON_MOUNT_PATH_ENV_NAME, Value: envDefaultCertMountPath}
utils.AddEnvVarToDeploymentContainers(deploy, certEnvVar)
}
c.deployments = append(c.deployments, deploy)
}
for j := 0; j < len(p.ComponentSpecs); j++ {
cSpec := mlDep.Spec.Predictors[i].ComponentSpecs[j]
// if no container spec then nothing to create at this point - prepackaged model server cases handled later
if len(cSpec.Spec.Containers) == 0 {
continue
}
// create Deployment from podspec
depName := machinelearningv1.GetDeploymentName(mlDep, p, cSpec, j)
if i == 0 && j == 0 {
c.defaultDeploymentName = depName
}
deploy := createDeploymentWithoutEngine(depName, seldonId, cSpec, &p, mlDep, securityContext, true)
if cSpec.KedaSpec != nil { // Add KEDA if needed
c.kedaScaledObjects = append(c.kedaScaledObjects, createKeda(cSpec, depName, seldonId, namespace))
} else if cSpec.HpaSpec != nil { // Add HPA if needed
c.hpas = append(c.hpas, createHpa(cSpec, depName, seldonId, namespace))
} else { //set replicas from more specifc to more general replicas settings in spec
if cSpec.Replicas != nil {
deploy.Spec.Replicas = cSpec.Replicas
} else if p.Replicas != nil {
deploy.Spec.Replicas = p.Replicas
} else {
deploy.Spec.Replicas = mlDep.Spec.Replicas
}
}
// Add PDB if needed
if cSpec.PdbSpec != nil {
c.pdbs = append(c.pdbs, createPdb(cSpec, depName, seldonId, namespace))
}
// create services for each container
for k := 0; k < len(cSpec.Spec.Containers); k++ {
var con *corev1.Container
// get the container on the created deployment, as createDeploymentWithoutEngine will have created as a copy of the spec in the manifest and added defaults to it
// we need the reference as we may have to modify the container when creating the Service (e.g. to add probes)
con = utils.GetContainerForDeployment(deploy, cSpec.Spec.Containers[k].Name)
pu := machinelearningv1.GetPredictiveUnit(&p.Graph, con.Name)
deploy = addLabelsToDeployment(deploy, pu, &p)
// engine will later get a special predictor service as it is entrypoint for graph
// and no need to expose tfserving container as it's accessed via proxy
if con.Name != EngineContainerName && con.Name != constants.TFServingContainerName {
// service for hitting a model directly, not via engine - also adds ports to container if needed
svc := createContainerService(deploy, p, mlDep, con, c, seldonId)
if svc != nil {
svc = addLabelsToService(svc, pu, &p)
c.services = append(c.services, svc)
} else {
// a user-supplied container may not be a pu so we may not create service for that
log.Info("Not creating container service for " + con.Name)
continue
}
if noEngine {
deploy.ObjectMeta.Labels[machinelearningv1.Label_seldon_app] = pSvcName
deploy.Spec.Selector.MatchLabels[machinelearningv1.Label_seldon_app] = pSvcName
deploy.Spec.Template.ObjectMeta.Labels[machinelearningv1.Label_seldon_app] = pSvcName
httpPort := int(svc.Spec.Ports[0].Port)
grpcPort := int(svc.Spec.Ports[1].Port)
externalPorts[i] = httpGrpcPorts{httpPort: httpPort, grpcPort: grpcPort}
psvc, err := createPredictorService(pSvcName, seldonId, &p, mlDep, httpPort, grpcPort, false, log)
if err != nil {
return nil, err
}
psvc = addLabelsToService(psvc, pu, &p)
c.services = append(c.services, psvc)
c.serviceDetails[pSvcName] = &machinelearningv1.ServiceStatus{
SvcName: pSvcName,
HttpEndpoint: pSvcName + "." + namespace + ":" + strconv.Itoa(httpPort),
GrpcEndpoint: pSvcName + "." + namespace + ":" + strconv.Itoa(grpcPort),
}
}
}
}
c.deployments = append(c.deployments, deploy)
}
pi := NewPrePackedInitializer(ctx, r.ClientSet)
err = pi.createStandaloneModelServers(mlDep, &p, &c, &p.Graph, securityContext)
if err != nil {
return nil, err
}
if !noEngine {
// Add service orchestrator to engine deployment if needed
if !hasSeparateEnginePod {
var deploy *appsv1.Deployment
found := false
// find the pu that the webhook marked as localhost as its corresponding deployment should get the engine
pu := machinelearningv1.GetEnginePredictiveUnit(&p.Graph)
if pu == nil {
// below should never happen - if it did would suggest problem in webhook
return nil, fmt.Errorf("engine not separate and no pu with localhost service - not clear where to inject engine")
}
// find the deployment with a container for the pu marked for engine
for i, _ := range c.deployments {
dep := c.deployments[i]
for _, con := range dep.Spec.Template.Spec.Containers {
if strings.Compare(con.Name, pu.Name) == 0 {
deploy = dep
found = true
}
}
}
if !found {
// by this point we should have created the Deployment corresponding to the pu marked localhost - if we haven't something has gone wrong
return nil, fmt.Errorf("engine not separate and no deployment for pu with localhost service - not clear where to inject engine")
}
err := addEngineToDeployment(mlDep, &p, engine_http_port, engine_grpc_port, pSvcName, deploy)
if err != nil {
return nil, err
}
}
// Find the current deployment and add the environment variables for the certificate
if len(certSecretRefName) > 0 {
sPodSpec, idx := utils.GetSeldonPodSpecForPredictiveUnit(&p, p.Graph.Name)
currentDeployName := machinelearningv1.GetDeploymentName(mlDep, p, sPodSpec, idx)
for i := 0; i < len(c.deployments); i++ {
d := c.deployments[i]
if strings.Compare(d.Name, currentDeployName) == 0 {
utils.MountSecretToDeploymentContainers(d, certSecretRefName, envDefaultCertMountPath)
certEnvVar := &corev1.EnvVar{Name: SELDON_MOUNT_PATH_ENV_NAME, Value: envDefaultCertMountPath}
utils.AddEnvVarToDeploymentContainers(d, certEnvVar)
break
}
}
}
psvc, err := createPredictorService(pSvcName, seldonId, &p, mlDep, engine_http_port, engine_grpc_port, false, log)
if err != nil {
return nil, err
}
c.services = append(c.services, psvc)
c.serviceDetails[pSvcName] = &machinelearningv1.ServiceStatus{
SvcName: pSvcName,
HttpEndpoint: pSvcName + "." + namespace + ":" + strconv.Itoa(engine_http_port),
GrpcEndpoint: pSvcName + "." + namespace + ":" + strconv.Itoa(engine_grpc_port),
}
externalPorts[i] = httpGrpcPorts{httpPort: engine_http_port, grpcPort: engine_grpc_port}
}
ei := NewExplainerInitializer(ctx, r.ClientSet)
err = ei.createExplainer(mlDep, &p, &c, pSvcName, securityContext, log)
if err != nil {
return nil, err
}
}
// Create the addressable as all services are created when SeldonDeployment is ready
c.addressable, err = createAddressableResource(mlDep, namespace, externalPorts)
if err != nil {
return nil, err
}
//TODO Fixme - not changed to handle per predictor scenario
if utils.GetEnv(ENV_ISTIO_ENABLED, "false") == "true" {
vsvcs, dstRule, err := createIstioResources(mlDep, seldonId, namespace, externalPorts)
if err != nil {
return nil, err
}
c.virtualServices = append(c.virtualServices, vsvcs...)
c.destinationRules = append(c.destinationRules, dstRule...)
}
return &c, nil
}
//Creates Service for Predictor - exposed externally (ambassador or istio)
func createPredictorService(pSvcName string, seldonId string, p *machinelearningv1.PredictorSpec,
mlDep *machinelearningv1.SeldonDeployment,
engine_http_port int,
engine_grpc_port int,
isExplainer bool,
log logr.Logger) (pSvc *corev1.Service, err error) {
namespace := getNamespace(mlDep)
psvc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: pSvcName,
Namespace: namespace,
Labels: map[string]string{
machinelearningv1.Label_seldon_app: pSvcName,
machinelearningv1.Label_seldon_id: seldonId,
machinelearningv1.Label_managed_by: machinelearningv1.Label_value_seldon,
},
Annotations: map[string]string{},
},
Spec: corev1.ServiceSpec{
Selector: map[string]string{machinelearningv1.Label_seldon_app: pSvcName},
SessionAffinity: corev1.ServiceAffinityNone,
Type: corev1.ServiceTypeClusterIP,
},
}
if engine_http_port != 0 && len(psvc.Spec.Ports) == 0 {
psvc.Spec.Ports = append(psvc.Spec.Ports, corev1.ServicePort{Protocol: corev1.ProtocolTCP, Port: int32(engine_http_port), TargetPort: intstr.FromInt(engine_http_port), Name: "http"})
}
if engine_grpc_port != 0 && len(psvc.Spec.Ports) < 2 {
psvc.Spec.Ports = append(psvc.Spec.Ports, corev1.ServicePort{Protocol: corev1.ProtocolTCP, Port: int32(engine_grpc_port), TargetPort: intstr.FromInt(engine_grpc_port), Name: "grpc"})
}
if utils.GetEnv("AMBASSADOR_ENABLED", "false") == "true" {
//Create top level Service
ambassadorConfig, err := getAmbassadorConfigs(mlDep, p, pSvcName, engine_http_port, engine_grpc_port, isExplainer)
if err != nil {
return nil, err
}
psvc.Annotations[AMBASSADOR_ANNOTATION] = ambassadorConfig
}
if getAnnotation(mlDep, machinelearningv1.ANNOTATION_HEADLESS_SVC, "false") != "false" {
log.Info("Creating Headless SVC")
psvc.Spec.ClusterIP = "None"
}
// Add annotations from predictorspec
for k, v := range p.Annotations {
psvc.Annotations[k] = v
}
return psvc, err
}
// service for hitting a model directly, not via engine - not exposed externally, also adds probes
func createContainerService(deploy *appsv1.Deployment,
p machinelearningv1.PredictorSpec,
mlDep *machinelearningv1.SeldonDeployment,
con *corev1.Container,
c components,
seldonId string) *corev1.Service {
containerServiceKey := machinelearningv1.Label_seldon_app_svc
containerServiceValue := machinelearningv1.GetContainerServiceName(mlDep.Name, p, con)
pSvcName := machinelearningv1.GetPredictorKey(mlDep, &p)
pu := machinelearningv1.GetPredictiveUnit(&p.Graph, con.Name)
// only create services for containers defined as pus in the graph
if pu == nil {
return nil
}
namespace := getNamespace(mlDep)
c.serviceDetails[containerServiceValue] = &machinelearningv1.ServiceStatus{
SvcName: containerServiceValue,
HttpEndpoint: containerServiceValue + "." + namespace + ":" + strconv.Itoa(int(pu.Endpoint.HttpPort)),
GrpcEndpoint: containerServiceValue + "." + namespace + ":" + strconv.Itoa(int(pu.Endpoint.GrpcPort))}
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: containerServiceValue,
Namespace: namespace,
Labels: map[string]string{
containerServiceKey: containerServiceValue,
machinelearningv1.Label_seldon_id: seldonId,
machinelearningv1.Label_seldon_app: pSvcName},
Annotations: map[string]string{},
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Protocol: corev1.ProtocolTCP,
Port: pu.Endpoint.HttpPort,
TargetPort: intstr.FromInt(int(pu.Endpoint.HttpPort)),
Name: "http",
},
{
Protocol: corev1.ProtocolTCP,
Port: pu.Endpoint.GrpcPort,
TargetPort: intstr.FromInt(int(pu.Endpoint.GrpcPort)),
Name: "grpc",
},
},
Type: corev1.ServiceTypeClusterIP,
Selector: map[string]string{containerServiceKey: containerServiceValue},
SessionAffinity: corev1.ServiceAffinityNone,
},
}
deploy.ObjectMeta.Labels[containerServiceKey] = containerServiceValue
deploy.Spec.Selector.MatchLabels[containerServiceKey] = containerServiceValue
deploy.Spec.Template.ObjectMeta.Labels[containerServiceKey] = containerServiceValue
existingHttpPort := machinelearningv1.GetPort("http", con.Ports)
if existingHttpPort == nil || con.Ports == nil {
con.Ports = append(con.Ports, corev1.ContainerPort{Name: "http", ContainerPort: pu.Endpoint.HttpPort, Protocol: corev1.ProtocolTCP})
}
existingGrpcPort := machinelearningv1.GetPort("grpc", con.Ports)
if existingGrpcPort == nil || con.Ports == nil {
con.Ports = append(con.Ports, corev1.ContainerPort{Name: "grpc", ContainerPort: pu.Endpoint.GrpcPort, Protocol: corev1.ProtocolTCP})
}
// Add annotations from predictorspec
for k, v := range p.Annotations {
svc.Annotations[k] = v
}
// Backwards compatible additions. From 1.5.0 onwards could always call httpPort as both should be available but for
// previously wrapped components need to look at transport.
// TODO: deprecate and just call httpPort
if con.LivenessProbe == nil {
if mlDep.Spec.Transport == machinelearningv1.TransportGrpc || pu.Endpoint.Type == machinelearningv1.GRPC {
con.LivenessProbe = &corev1.Probe{ProbeHandler: corev1.ProbeHandler{TCPSocket: &corev1.TCPSocketAction{Port: intstr.FromInt(int(pu.Endpoint.GrpcPort))}}, InitialDelaySeconds: 60, PeriodSeconds: 5, SuccessThreshold: 1, FailureThreshold: 3, TimeoutSeconds: 1}
} else {
con.LivenessProbe = &corev1.Probe{ProbeHandler: corev1.ProbeHandler{TCPSocket: &corev1.TCPSocketAction{Port: intstr.FromInt(int(pu.Endpoint.HttpPort))}}, InitialDelaySeconds: 60, PeriodSeconds: 5, SuccessThreshold: 1, FailureThreshold: 3, TimeoutSeconds: 1}
}
}
if con.ReadinessProbe == nil {
if mlDep.Spec.Transport == machinelearningv1.TransportGrpc || pu.Endpoint.Type == machinelearningv1.GRPC {
con.ReadinessProbe = &corev1.Probe{ProbeHandler: corev1.ProbeHandler{TCPSocket: &corev1.TCPSocketAction{Port: intstr.FromInt(int(pu.Endpoint.GrpcPort))}}, InitialDelaySeconds: 20, PeriodSeconds: 5, SuccessThreshold: 1, FailureThreshold: 3, TimeoutSeconds: 1}
} else {
con.ReadinessProbe = &corev1.Probe{ProbeHandler: corev1.ProbeHandler{TCPSocket: &corev1.TCPSocketAction{Port: intstr.FromInt(int(pu.Endpoint.HttpPort))}}, InitialDelaySeconds: 20, PeriodSeconds: 5, SuccessThreshold: 1, FailureThreshold: 3, TimeoutSeconds: 1}
}
}
// Add lifecycle probe
if con.Lifecycle == nil {
con.Lifecycle = &corev1.Lifecycle{PreStop: &corev1.LifecycleHandler{Exec: &corev1.ExecAction{Command: []string{"/bin/sh", "-c", "/bin/sleep 10"}}}}
}
//
// Backwards compatibility - set to either Http or Grpc
//
// TODO: deprecate and remove
if !utils.HasEnvVar(con.Env, machinelearningv1.ENV_PREDICTIVE_UNIT_SERVICE_PORT) {
if pu.Endpoint.Type == machinelearningv1.GRPC || mlDep.Spec.Transport == machinelearningv1.TransportGrpc {
con.Env = append(con.Env, corev1.EnvVar{Name: machinelearningv1.ENV_PREDICTIVE_UNIT_SERVICE_PORT, Value: strconv.Itoa(int(pu.Endpoint.GrpcPort))})
} else {
con.Env = append(con.Env, corev1.EnvVar{Name: machinelearningv1.ENV_PREDICTIVE_UNIT_SERVICE_PORT, Value: strconv.Itoa(int(pu.Endpoint.HttpPort))})
}
}
addPortEnvs(pu, con)
addModelEnvs(pu, con)
// Always set the predictive and deployment identifiers
labels, err := json.Marshal(p.Labels)
if err != nil {
labels = []byte("{}")
}
con.Env = append(con.Env, []corev1.EnvVar{
corev1.EnvVar{Name: machinelearningv1.ENV_PREDICTIVE_UNIT_ID, Value: con.Name},
corev1.EnvVar{Name: MLServerModelNameEnv, Value: con.Name},
corev1.EnvVar{Name: machinelearningv1.ENV_PREDICTIVE_UNIT_IMAGE, Value: con.Image},
corev1.EnvVar{Name: machinelearningv1.ENV_PREDICTOR_ID, Value: p.Name},
corev1.EnvVar{Name: machinelearningv1.ENV_PREDICTOR_LABELS, Value: string(labels)},
corev1.EnvVar{Name: machinelearningv1.ENV_SELDON_DEPLOYMENT_ID, Value: mlDep.ObjectMeta.Name},
corev1.EnvVar{Name: machinelearningv1.ENV_SELDON_EXECUTOR_ENABLED, Value: strconv.FormatBool(true)},
}...)
//Add Metric Env Var
predictiveUnitMetricsPortName := utils.GetEnv(machinelearningv1.ENV_PREDICTIVE_UNIT_METRICS_PORT_NAME, constants.DefaultMetricsPortName)
metricPort := getPort(predictiveUnitMetricsPortName, con.Ports)
if metricPort != nil {
con.Env = append(con.Env, []corev1.EnvVar{
{Name: machinelearningv1.ENV_PREDICTIVE_UNIT_SERVICE_PORT_METRICS, Value: strconv.Itoa(int(metricPort.ContainerPort))},
{Name: machinelearningv1.ENV_PREDICTIVE_UNIT_METRICS_ENDPOINT, Value: getPrometheusPath(mlDep)},
{Name: MLServerMetricsPortEnv, Value: strconv.Itoa(int(metricPort.ContainerPort))},
{Name: MLServerMetricsEndpointEnv, Value: getPrometheusPath(mlDep)},
}...)
}
return svc
}
func addModelEnvs(pu *machinelearningv1.PredictiveUnit, con *corev1.Container) {
if len(pu.Parameters) > 0 {
// Set V1 env vars
paramsEnvVar := corev1.EnvVar{
Name: machinelearningv1.ENV_PREDICTIVE_UNIT_PARAMETERS,
Value: utils.GetPredictiveUnitAsJson(pu.Parameters),
}
con.Env = utils.SetEnvVar(con.Env, paramsEnvVar, false)
}
// If storageUri is present, set model URI for V2
if len(pu.ModelURI) != 0 {
modelURIEnv := corev1.EnvVar{
Name: MLServerModelURIEnv,
Value: DefaultModelLocalMountPath,
}
con.Env = utils.SetEnvVar(con.Env, modelURIEnv, false)
}
}
func addPortEnvs(pu *machinelearningv1.PredictiveUnit, con *corev1.Container) {
// HTTP Ports
httpPort := strconv.Itoa(int(pu.Endpoint.HttpPort))
httpEnvVarNames := []string{
machinelearningv1.ENV_PREDICTIVE_UNIT_HTTP_SERVICE_PORT,
MLServerHTTPPortEnv,
}
for _, envVarName := range httpEnvVarNames {
httpEnvVar := corev1.EnvVar{
Name: envVarName,
Value: httpPort,
}
con.Env = utils.SetEnvVar(con.Env, httpEnvVar, false)
}
// gRPC Ports
grpcPort := strconv.Itoa(int(pu.Endpoint.GrpcPort))
grpcEnvVarNames := []string{
machinelearningv1.ENV_PREDICTIVE_UNIT_GRPC_SERVICE_PORT,
MLServerGRPCPortEnv,
}
for _, envVarName := range grpcEnvVarNames {
grpcEnvVar := corev1.EnvVar{
Name: envVarName,
Value: grpcPort,
}
con.Env = utils.SetEnvVar(con.Env, grpcEnvVar, false)
}
}
func createDeploymentWithoutEngine(depName string, seldonId string, seldonPodSpec *machinelearningv1.SeldonPodSpec, p *machinelearningv1.PredictorSpec, mlDep *machinelearningv1.SeldonDeployment, podSecurityContext *corev1.PodSecurityContext, metricsEnabled bool) *appsv1.Deployment {
deploy := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: depName,
Namespace: getNamespace(mlDep),
Labels: map[string]string{
machinelearningv1.Label_seldon_id: seldonId,
"app": depName,
"fluentd": "true",
},
Annotations: map[string]string{},
},
Spec: appsv1.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{machinelearningv1.Label_seldon_id: seldonId},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
machinelearningv1.Label_seldon_id: seldonId,
machinelearningv1.Label_app: depName,
machinelearningv1.Label_fluentd: "true",
},
Annotations: map[string]string{},
},
},
Strategy: appsv1.DeploymentStrategy{RollingUpdate: &appsv1.RollingUpdateDeployment{MaxUnavailable: &intstr.IntOrString{StrVal: "10%"}}},
},
}
if deploy.Spec.Template.Annotations == nil {
deploy.Spec.Template.Annotations = map[string]string{}
}
if metricsEnabled {
// Add prometheus annotations
deploy.Spec.Template.Annotations["prometheus.io/path"] = getPrometheusPath(mlDep)
deploy.Spec.Template.Annotations["prometheus.io/scrape"] = "true"
}
if p.Shadow == true {
deploy.Spec.Template.ObjectMeta.Labels[machinelearningv1.Label_shadow] = "true"
}
//Add annotations from top level
for k, v := range mlDep.Spec.Annotations {
deploy.Annotations[k] = v
deploy.Spec.Template.ObjectMeta.Annotations[k] = v
}
// Add annottaions from predictor
for k, v := range p.Annotations {
deploy.Annotations[k] = v
deploy.Spec.Template.ObjectMeta.Annotations[k] = v
}
if seldonPodSpec != nil {
deploy.Spec.Template.Spec = seldonPodSpec.Spec
// add more annotations from metadata
for k, v := range seldonPodSpec.Metadata.Annotations {
deploy.Annotations[k] = v
deploy.Spec.Template.ObjectMeta.Annotations[k] = v
}
}
// Add Pod Security Context
deploy.Spec.Template.Spec.SecurityContext = podSecurityContext
// add predictor labels
for k, v := range p.Labels {
deploy.ObjectMeta.Labels[k] = v
deploy.Spec.Template.ObjectMeta.Labels[k] = v
}
// add labels from podSpec metadata
if seldonPodSpec != nil {
for k, v := range seldonPodSpec.Metadata.Labels {
deploy.ObjectMeta.Labels[k] = v
deploy.Spec.Template.ObjectMeta.Labels[k] = v
}
}
//Add some default to help with diffs in controller
if deploy.Spec.Template.Spec.RestartPolicy == "" {
deploy.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyAlways
}
if deploy.Spec.Template.Spec.DNSPolicy == "" {
deploy.Spec.Template.Spec.DNSPolicy = corev1.DNSClusterFirst
}
if deploy.Spec.Template.Spec.SchedulerName == "" {
deploy.Spec.Template.Spec.SchedulerName = "default-scheduler"
}
// Set TerminationGracePeriodSeconds
var terminationGracePeriod int64 = 20
deploy.Spec.Template.Spec.TerminationGracePeriodSeconds = &terminationGracePeriod
if seldonPodSpec != nil && seldonPodSpec.Spec.TerminationGracePeriodSeconds != nil {
deploy.Spec.Template.Spec.TerminationGracePeriodSeconds = seldonPodSpec.Spec.TerminationGracePeriodSeconds
}
volFound := false
for _, vol := range deploy.Spec.Template.Spec.Volumes {
if vol.Name == machinelearningv1.PODINFO_VOLUME_NAME {
volFound = true
}
}
if !volFound {
var defaultMode = corev1.DownwardAPIVolumeSourceDefaultMode
//Add downwardAPI
deploy.Spec.Template.Spec.Volumes = append(deploy.Spec.Template.Spec.Volumes, corev1.Volume{Name: machinelearningv1.PODINFO_VOLUME_NAME, VolumeSource: corev1.VolumeSource{
DownwardAPI: &corev1.DownwardAPIVolumeSource{Items: []corev1.DownwardAPIVolumeFile{
{Path: "annotations", FieldRef: &corev1.ObjectFieldSelector{FieldPath: "metadata.annotations", APIVersion: "v1"}}}, DefaultMode: &defaultMode}}})