forked from SeldonIO/seldon-core
/
model_initializer_injector.go
302 lines (262 loc) · 10.4 KB
/
model_initializer_injector.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
/*
Copyright 2019 kubeflow.org.
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 (
"encoding/json"
"fmt"
"strings"
"github.com/seldonio/seldon-core/operator/controllers/resources/credentials"
"github.com/seldonio/seldon-core/operator/utils"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// TODO: change image to seldon? is at least configurable by configmap now (with fixed version there)
// TODO: check PVC
const (
DefaultModelLocalMountPath = "/mnt/models"
StorageInitializerConfigMapKeyName = "storageInitializer"
ModelInitializerContainerImage = "gcr.io/kfserving/model-initializer"
ModelInitializerContainerVersion = "latest"
PvcURIPrefix = "pvc://"
PvcSourceMountName = "kfserving-pvc-source"
PvcSourceMountPath = "/mnt/pvc"
ModelInitializerVolumeSuffix = "provision-location"
ModelInitializerContainerSuffix = "model-initializer"
)
var (
ControllerNamespace = GetEnv("POD_NAMESPACE", "seldon-system")
ControllerConfigMapName = "seldon-config"
)
type StorageInitializerConfig struct {
Image string `json:"image"`
CpuRequest string `json:"cpuRequest"`
CpuLimit string `json:"cpuLimit"`
MemoryRequest string `json:"memoryRequest"`
MemoryLimit string `json:"memoryLimit"`
}
func credentialsBuilder(Client client.Client) (credentialsBuilder *credentials.CredentialBuilder, err error) {
clientset := kubernetes.NewForConfigOrDie(ctrl.GetConfigOrDie())
configMap, err := clientset.CoreV1().ConfigMaps(ControllerNamespace).Get(ControllerConfigMapName, metav1.GetOptions{})
if err != nil {
//log.Error(err, "Failed to find config map", "name", ControllerConfigMapName)
return nil, err
}
credentialBuilder := credentials.NewCredentialBulder(Client, configMap)
return credentialBuilder, nil
}
func getStorageInitializerConfigs(Client client.Client) (*StorageInitializerConfig, error) {
clientset := kubernetes.NewForConfigOrDie(ctrl.GetConfigOrDie())
configMap, err := clientset.CoreV1().ConfigMaps(ControllerNamespace).Get(ControllerConfigMapName, metav1.GetOptions{})
if err != nil {
//log.Error(err, "Failed to find config map", "name", ControllerConfigMapName)
return nil, err
}
return getStorageInitializerConfigsFromMap(configMap)
}
func getStorageInitializerConfigsFromMap(configMap *corev1.ConfigMap) (*StorageInitializerConfig, error) {
storageInitializerConfig := &StorageInitializerConfig{}
if initializerConfig, ok := configMap.Data[StorageInitializerConfigMapKeyName]; ok {
err := json.Unmarshal([]byte(initializerConfig), &storageInitializerConfig)
if err != nil {
panic(fmt.Errorf("Unable to unmarshall %v json string due to %v ", StorageInitializerConfigMapKeyName, err))
}
}
//Ensure that we set proper values for CPU/Memory Limit/Request
resourceDefaults := []string{storageInitializerConfig.MemoryRequest,
storageInitializerConfig.MemoryLimit,
storageInitializerConfig.CpuRequest,
storageInitializerConfig.CpuLimit}
for _, key := range resourceDefaults {
_, err := resource.ParseQuantity(key)
if err != nil {
return storageInitializerConfig, err
}
}
return storageInitializerConfig, nil
}
// InjectModelInitializer injects an init container to provision model data
func InjectModelInitializer(deployment *appsv1.Deployment, containerName string, srcURI string, serviceAccountName string, envSecretRefName string, Client client.Client) (deploy *appsv1.Deployment, err error) {
if srcURI == "" {
return deployment, nil
}
userContainer := utils.GetContainerForDeployment(deployment, containerName)
if userContainer == nil {
return deployment, fmt.Errorf("Invalid configuration: cannot find container: %s", containerName)
}
ModelInitializerVolumeName := userContainer.Name + "-" + ModelInitializerVolumeSuffix
//kubernetes names limited to 63
if len(ModelInitializerVolumeName) > 63 {
ModelInitializerVolumeName = ModelInitializerVolumeName[0:63]
ModelInitializerVolumeName = strings.TrimSuffix(ModelInitializerVolumeName, "-")
}
ModelInitializerContainerName := userContainer.Name + "-" + ModelInitializerContainerSuffix
if len(ModelInitializerContainerName) > 63 {
ModelInitializerContainerName = ModelInitializerContainerName[0:63]
ModelInitializerContainerName = strings.TrimSuffix(ModelInitializerContainerName, "-")
}
// TODO: KFServing does a check for an annotation before injecting - not doing that for now
podSpec := &deployment.Spec.Template.Spec
// Dont inject if InitContianer already injected
for _, container := range podSpec.InitContainers {
if strings.Compare(container.Name, ModelInitializerContainerName) == 0 {
// make sure we have the mount on the main container
addVolumeMountToContainer(userContainer, ModelInitializerVolumeName, DefaultModelLocalMountPath)
return deployment, nil
}
}
podVolumes := []corev1.Volume{}
modelInitializerMounts := []corev1.VolumeMount{}
// For PVC source URIs we need to mount the source to be able to access it
// See design and discussion here: https://github.com/kubeflow/kfserving/issues/148
if strings.HasPrefix(srcURI, PvcURIPrefix) {
pvcName, pvcPath, err := parsePvcURI(srcURI)
if err != nil {
return nil, err
}
// add the PVC volume on the pod
pvcSourceVolume := corev1.Volume{
Name: PvcSourceMountName,
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: pvcName,
},
},
}
podVolumes = append(podVolumes, pvcSourceVolume)
// add a corresponding PVC volume mount to the INIT container
pvcSourceVolumeMount := corev1.VolumeMount{
Name: PvcSourceMountName,
MountPath: PvcSourceMountPath,
ReadOnly: true,
}
modelInitializerMounts = append(modelInitializerMounts, pvcSourceVolumeMount)
// Since the model path is linked from source pvc, userContainer also need to mount the pvc.
addVolumeMountToContainer(userContainer, PvcSourceMountName, PvcSourceMountPath)
// modify the sourceURI to point to the PVC path
srcURI = PvcSourceMountPath + "/" + pvcPath
}
// Create a volume that is shared between the model-initializer and user-container
sharedVolume := corev1.Volume{
Name: ModelInitializerVolumeName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
}
podVolumes = append(podVolumes, sharedVolume)
// Create a write mount into the shared volume
sharedVolumeWriteMount := corev1.VolumeMount{
Name: ModelInitializerVolumeName,
MountPath: DefaultModelLocalMountPath,
ReadOnly: false,
}
modelInitializerMounts = append(modelInitializerMounts, sharedVolumeWriteMount)
config, err := getStorageInitializerConfigs(Client)
if err != nil {
return nil, err
}
storageInitializerImage := ModelInitializerContainerImage + ":" + ModelInitializerContainerVersion
if config != nil && config.Image != "" {
storageInitializerImage = config.Image
}
// Add an init container to run provisioning logic to the PodSpec (with defaults to pass comparison later)
initContainer := &corev1.Container{
Name: ModelInitializerContainerName,
Image: storageInitializerImage,
ImagePullPolicy: corev1.PullIfNotPresent,
Args: []string{
srcURI,
DefaultModelLocalMountPath,
},
VolumeMounts: modelInitializerMounts,
TerminationMessagePath: "/dev/termination-log",
TerminationMessagePolicy: corev1.TerminationMessageReadFile,
Resources: corev1.ResourceRequirements{
Limits: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse(config.CpuLimit),
corev1.ResourceMemory: resource.MustParse(config.MemoryLimit),
},
Requests: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse(config.CpuRequest),
corev1.ResourceMemory: resource.MustParse(config.MemoryRequest),
},
},
}
addVolumeMountToContainer(userContainer, ModelInitializerVolumeName, DefaultModelLocalMountPath)
// Add volumes to the PodSpec
podSpec.Volumes = append(podSpec.Volumes, podVolumes...)
// Inject credentials
credentialsBuilder, err := credentialsBuilder(Client)
if err != nil {
return nil, err
}
if serviceAccountName == "" {
serviceAccountName = podSpec.ServiceAccountName
}
if err := credentialsBuilder.CreateSecretVolumeAndEnv(
deployment.Namespace,
serviceAccountName,
initContainer,
&podSpec.Volumes,
); err != nil {
return nil, err
}
// Inject credentials using secretRef
if envSecretRefName != "" {
initContainer.EnvFrom = append(initContainer.EnvFrom,
corev1.EnvFromSource{
SecretRef: &corev1.SecretEnvSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: envSecretRefName,
},
},
})
}
// Add init container to the spec
podSpec.InitContainers = append(podSpec.InitContainers, *initContainer)
return deployment, nil
}
func addVolumeMountToContainer(userContainer *corev1.Container, ModelInitializerVolumeName string, MountPath string) {
mountFound := false
for _, v := range userContainer.VolumeMounts {
if v.Name == ModelInitializerVolumeName {
mountFound = true
}
}
if !mountFound {
// Add a mount the shared volume on the user-container, update the PodSpec
sharedVolumeReadMount := &corev1.VolumeMount{
Name: ModelInitializerVolumeName,
MountPath: MountPath,
ReadOnly: true,
}
userContainer.VolumeMounts = append(userContainer.VolumeMounts, *sharedVolumeReadMount)
}
}
func parsePvcURI(srcURI string) (pvcName string, pvcPath string, err error) {
parts := strings.Split(strings.TrimPrefix(srcURI, PvcURIPrefix), "/")
if len(parts) > 1 {
pvcName = parts[0]
pvcPath = strings.Join(parts[1:], "/")
} else if len(parts) == 1 {
pvcName = parts[0]
pvcPath = ""
} else {
return "", "", fmt.Errorf("Invalid URI must be pvc://<pvcname>/[path]: %s", srcURI)
}
return pvcName, pvcPath, nil
}