/
config.go
320 lines (287 loc) · 9 KB
/
config.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
package container
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
apiv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
fv1 "github.com/fission/fission/pkg/apis/core/v1"
"github.com/fission/fission/pkg/fetcher"
"github.com/fission/fission/pkg/utils"
"github.com/fission/fission/pkg/utils/otel"
)
type Config struct {
fetcherImage string
fetcherImagePullPolicy apiv1.PullPolicy
resourceRequirements apiv1.ResourceRequirements
// used by generic pool when creating env deployment to specify the share volume path for fetcher & env
// change this may break v1 compatibility, since most of the v1 environments have hard-coded "/userfunc" in loading path
sharedMountPath string
sharedSecretPath string
sharedCfgMapPath string
serviceAccount string
}
func getFetcherResources() (apiv1.ResourceRequirements, error) {
resourceReqs := apiv1.ResourceRequirements{
Requests: map[apiv1.ResourceName]resource.Quantity{},
Limits: map[apiv1.ResourceName]resource.Quantity{},
}
errs := utils.MultiErrorWithFormat()
errs = multierror.Append(errs,
parseResources("FETCHER_MINCPU", resourceReqs.Requests, apiv1.ResourceCPU),
parseResources("FETCHER_MINMEM", resourceReqs.Requests, apiv1.ResourceMemory),
parseResources("FETCHER_MAXCPU", resourceReqs.Limits, apiv1.ResourceCPU),
parseResources("FETCHER_MAXMEM", resourceReqs.Limits, apiv1.ResourceMemory),
)
return resourceReqs, errs.ErrorOrNil()
}
func parseResources(env string, resourceReqs map[apiv1.ResourceName]resource.Quantity, resName apiv1.ResourceName) error {
val := os.Getenv(env)
if len(val) > 0 {
quantity, err := resource.ParseQuantity(val)
if err != nil {
return err
}
resourceReqs[resName] = quantity
}
return nil
}
func MakeFetcherConfig(sharedMountPath string) (*Config, error) {
resources, err := getFetcherResources()
if err != nil {
return nil, err
}
fetcherImage := os.Getenv("FETCHER_IMAGE")
if len(fetcherImage) == 0 {
fetcherImage = "fission/fetcher"
}
fetcherImagePullPolicy := os.Getenv("FETCHER_IMAGE_PULL_POLICY")
if len(fetcherImagePullPolicy) == 0 {
fetcherImagePullPolicy = "IfNotPresent"
}
return &Config{
resourceRequirements: resources,
fetcherImage: fetcherImage,
fetcherImagePullPolicy: utils.GetImagePullPolicy(fetcherImagePullPolicy),
sharedMountPath: sharedMountPath,
sharedSecretPath: "/secrets",
sharedCfgMapPath: "/configs",
serviceAccount: fv1.FissionFetcherSA,
}, nil
}
func (cfg *Config) SharedMountPath() string {
return cfg.sharedMountPath
}
func (cfg *Config) NewSpecializeRequest(fn *fv1.Function, env *fv1.Environment) fetcher.FunctionSpecializeRequest {
targetFilename := "user"
if env.Spec.Version >= 2 {
if env.Spec.AllowedFunctionsPerContainer == fv1.AllowedFunctionsPerContainerInfinite {
// workflow loads multiple functions into one function pod,
// we have to use a Function UID to separate the function code
// to avoid overwriting.
targetFilename = string(fn.ObjectMeta.UID)
} else {
// set target file name to fix pattern for
// easy accessing.
targetFilename = "deployarchive"
}
}
return fetcher.FunctionSpecializeRequest{
FetchReq: fetcher.FunctionFetchRequest{
FetchType: fv1.FETCH_DEPLOYMENT,
Package: metav1.ObjectMeta{
Namespace: fn.Spec.Package.PackageRef.Namespace,
Name: fn.Spec.Package.PackageRef.Name,
ResourceVersion: fn.Spec.Package.PackageRef.ResourceVersion,
},
Filename: targetFilename,
Secrets: fn.Spec.Secrets,
ConfigMaps: fn.Spec.ConfigMaps,
KeepArchive: env.Spec.KeepArchive,
},
LoadReq: fetcher.FunctionLoadRequest{
FilePath: filepath.Join(cfg.sharedMountPath, targetFilename),
FunctionName: fn.Spec.Package.FunctionName,
FunctionMetadata: &fn.ObjectMeta,
EnvVersion: env.Spec.Version,
},
}
}
func (cfg *Config) AddFetcherToPodSpec(podSpec *apiv1.PodSpec, mainContainerName string) error {
return cfg.addFetcherToPodSpecWithCommand(podSpec, mainContainerName, cfg.fetcherCommand())
}
func (cfg *Config) AddSpecializingFetcherToPodSpec(podSpec *apiv1.PodSpec, mainContainerName string, fn *fv1.Function, env *fv1.Environment) error {
specializeReq := cfg.NewSpecializeRequest(fn, env)
specializePayload, err := json.Marshal(specializeReq)
if err != nil {
return err
}
return cfg.addFetcherToPodSpecWithCommand(
podSpec,
mainContainerName,
cfg.fetcherCommand(
"-specialize-on-startup",
"-specialize-request", string(specializePayload),
),
)
}
func (cfg *Config) fetcherCommand(extraArgs ...string) []string {
command := []string{"/fetcher",
"-secret-dir", cfg.sharedSecretPath,
"-cfgmap-dir", cfg.sharedCfgMapPath,
}
command = append(command, extraArgs...)
command = append(command, cfg.sharedMountPath)
return command
}
func (cfg *Config) volumesWithMounts() ([]apiv1.Volume, []apiv1.VolumeMount) {
items := make([]apiv1.DownwardAPIVolumeFile, 0)
podNameFieldSelector := apiv1.ObjectFieldSelector{
FieldPath: "metadata.name",
}
podNamespaceFieldSelector := apiv1.ObjectFieldSelector{
FieldPath: "metadata.namespace",
}
podName := apiv1.DownwardAPIVolumeFile{
Path: "name",
FieldRef: &podNameFieldSelector,
}
podNamespace := apiv1.DownwardAPIVolumeFile{
Path: "namespace",
FieldRef: &podNamespaceFieldSelector,
}
items = append(items, podName, podNamespace)
dwAPIVol := apiv1.DownwardAPIVolumeSource{Items: items}
volumes := []apiv1.Volume{
{
Name: fv1.SharedVolumeUserfunc,
VolumeSource: apiv1.VolumeSource{
EmptyDir: &apiv1.EmptyDirVolumeSource{},
},
},
{
Name: fv1.SharedVolumeSecrets,
VolumeSource: apiv1.VolumeSource{
EmptyDir: &apiv1.EmptyDirVolumeSource{},
},
},
{
Name: fv1.SharedVolumeConfigmaps,
VolumeSource: apiv1.VolumeSource{
EmptyDir: &apiv1.EmptyDirVolumeSource{},
},
},
{
Name: fv1.PodInfoVolume,
VolumeSource: apiv1.VolumeSource{
DownwardAPI: &dwAPIVol,
},
},
}
mounts := []apiv1.VolumeMount{
{
Name: fv1.SharedVolumeUserfunc,
MountPath: cfg.sharedMountPath,
},
{
Name: fv1.SharedVolumeSecrets,
MountPath: cfg.sharedSecretPath,
},
{
Name: fv1.SharedVolumeConfigmaps,
MountPath: cfg.sharedCfgMapPath,
},
{
Name: fv1.PodInfoVolume,
MountPath: fv1.PodInfoMount,
},
}
return volumes, mounts
}
func (cfg *Config) addFetcherToPodSpecWithCommand(podSpec *apiv1.PodSpec, mainContainerName string, command []string) error {
volumes, mounts := cfg.volumesWithMounts()
c := apiv1.Container{
Name: "fetcher",
Command: command,
Image: cfg.fetcherImage,
ImagePullPolicy: cfg.fetcherImagePullPolicy,
TerminationMessagePath: "/dev/termination-log",
VolumeMounts: mounts,
Resources: cfg.resourceRequirements,
ReadinessProbe: &apiv1.Probe{
InitialDelaySeconds: 1,
PeriodSeconds: 1,
FailureThreshold: 30,
ProbeHandler: apiv1.ProbeHandler{
HTTPGet: &apiv1.HTTPGetAction{
Path: "/readiness-healthz",
Port: intstr.IntOrString{
Type: intstr.Int,
IntVal: 8000,
},
},
},
},
LivenessProbe: &apiv1.Probe{
InitialDelaySeconds: 1,
PeriodSeconds: 5,
ProbeHandler: apiv1.ProbeHandler{
HTTPGet: &apiv1.HTTPGetAction{
Path: "/healthz",
Port: intstr.IntOrString{
Type: intstr.Int,
IntVal: 8000,
},
},
},
},
Env: otel.OtelEnvForContainer(),
}
// Pod is removed from endpoints list for service when it's
// state became "Termination". We used preStop hook as the
// workaround for connection draining since pod maybe shutdown
// before grace period expires.
// https://kubernetes.io/docs/concepts/workloads/pods/pod/#termination-of-pods
// https://github.com/kubernetes/kubernetes/issues/47576#issuecomment-308900172
if podSpec.TerminationGracePeriodSeconds != nil {
c.Lifecycle = &apiv1.Lifecycle{
PreStop: &apiv1.LifecycleHandler{
Exec: &apiv1.ExecAction{
Command: []string{
"/bin/sleep",
fmt.Sprintf("%v", *podSpec.TerminationGracePeriodSeconds),
},
},
},
}
}
found := false
for ix, container := range podSpec.Containers {
if container.Name != mainContainerName {
continue
}
found = true
container.VolumeMounts = append(container.VolumeMounts, mounts...)
podSpec.Containers[ix] = container
}
if !found {
existingContainerNames := make([]string, len(podSpec.Containers))
for _, existingContainer := range podSpec.Containers {
existingContainerNames = append(existingContainerNames, existingContainer.Name)
}
return errors.Errorf("could not find main container '%s' in given PodSpec. Found: %v",
mainContainerName,
existingContainerNames)
}
podSpec.Volumes = append(podSpec.Volumes, volumes...)
podSpec.Containers = append(podSpec.Containers, c)
if podSpec.ServiceAccountName == "" {
podSpec.ServiceAccountName = fv1.FissionFetcherSA
}
return nil
}