-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
pod.go
452 lines (399 loc) · 14.8 KB
/
pod.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
/*
Copyright 2019 The Tekton 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 resources provides methods to convert a Build CRD to a k8s Pod
// resource.
package resources
import (
"crypto/rand"
"encoding/hex"
"flag"
"fmt"
"io"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
"github.com/tektoncd/pipeline/pkg/credentials"
"github.com/tektoncd/pipeline/pkg/credentials/dockercreds"
"github.com/tektoncd/pipeline/pkg/credentials/gitcreds"
"github.com/tektoncd/pipeline/pkg/merge"
"github.com/tektoncd/pipeline/pkg/names"
"github.com/tektoncd/pipeline/pkg/reconciler/v1alpha1/taskrun/entrypoint"
)
const (
workspaceDir = "/workspace"
homeDir = "/builder/home"
)
// These are effectively const, but Go doesn't have such an annotation.
var (
groupVersionKind = schema.GroupVersionKind{
Group: v1alpha1.SchemeGroupVersion.Group,
Version: v1alpha1.SchemeGroupVersion.Version,
Kind: "TaskRun",
}
emptyVolumeSource = corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
}
// These are injected into all of the source/step containers.
implicitEnvVars = []corev1.EnvVar{{
Name: "HOME",
Value: homeDir,
}}
implicitVolumeMounts = []corev1.VolumeMount{{
Name: "workspace",
MountPath: workspaceDir,
}, {
Name: "home",
MountPath: homeDir,
}}
implicitVolumes = []corev1.Volume{{
Name: "workspace",
VolumeSource: emptyVolumeSource,
}, {
Name: "home",
VolumeSource: emptyVolumeSource,
}}
zeroQty = resource.MustParse("0")
// Random byte reader used for pod name generation.
// var for testing.
randReader = rand.Reader
)
const (
// Prefixes to add to the name of the init containers.
containerPrefix = "step-"
unnamedInitContainerPrefix = "step-unnamed-"
// Name of the credential initialization container.
credsInit = "credential-initializer"
// Name of the working dir initialization container.
workingDirInit = "working-dir-initializer"
ReadyAnnotation = "tekton.dev/ready"
readyAnnotationValue = "READY"
)
var (
// The container used to initialize credentials before the build runs.
credsImage = flag.String("creds-image", "override-with-creds:latest",
"The container image for preparing our Build's credentials.")
)
func makeCredentialInitializer(serviceAccountName, namespace string, kubeclient kubernetes.Interface) (*corev1.Container, []corev1.Volume, error) {
if serviceAccountName == "" {
serviceAccountName = "default"
}
sa, err := kubeclient.CoreV1().ServiceAccounts(namespace).Get(serviceAccountName, metav1.GetOptions{})
if err != nil {
return nil, nil, err
}
builders := []credentials.Builder{dockercreds.NewBuilder(), gitcreds.NewBuilder()}
// Collect the volume declarations, there mounts into the cred-init container, and the arguments to it.
volumes := []corev1.Volume{}
volumeMounts := implicitVolumeMounts
args := []string{}
for _, secretEntry := range sa.Secrets {
secret, err := kubeclient.CoreV1().Secrets(namespace).Get(secretEntry.Name, metav1.GetOptions{})
if err != nil {
return nil, nil, err
}
matched := false
for _, b := range builders {
if sa := b.MatchingAnnotations(secret); len(sa) > 0 {
matched = true
args = append(args, sa...)
}
}
if matched {
name := names.SimpleNameGenerator.RestrictLengthWithRandomSuffix(fmt.Sprintf("secret-volume-%s", secret.Name))
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: name,
MountPath: credentials.VolumeName(secret.Name),
})
volumes = append(volumes, corev1.Volume{
Name: name,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: secret.Name,
},
},
})
}
}
return &corev1.Container{
Name: names.SimpleNameGenerator.RestrictLengthWithRandomSuffix(containerPrefix + credsInit),
Image: *credsImage,
Command: []string{"/ko-app/creds-init"},
Args: args,
VolumeMounts: volumeMounts,
Env: implicitEnvVars,
WorkingDir: workspaceDir,
}, volumes, nil
}
func makeWorkingDirScript(workingDirs map[string]bool) string {
script := ""
var orderedDirs []string
for wd := range workingDirs {
if wd != "" {
orderedDirs = append(orderedDirs, wd)
}
}
sort.Strings(orderedDirs)
for _, wd := range orderedDirs {
p := filepath.Clean(wd)
if rel, err := filepath.Rel(workspaceDir, p); err == nil && !strings.HasPrefix(rel, ".") {
if script == "" {
script = fmt.Sprintf("mkdir -p %s", p)
} else {
script = fmt.Sprintf("%s %s", script, p)
}
}
}
return script
}
func makeWorkingDirInitializer(steps []corev1.Container) *corev1.Container {
workingDirs := make(map[string]bool)
for _, step := range steps {
workingDirs[step.WorkingDir] = true
}
if script := makeWorkingDirScript(workingDirs); script != "" {
return &corev1.Container{
Name: names.SimpleNameGenerator.RestrictLengthWithRandomSuffix(containerPrefix + workingDirInit),
Image: *v1alpha1.BashNoopImage,
Command: []string{"/ko-app/bash"},
Args: []string{"-args", script},
VolumeMounts: implicitVolumeMounts,
Env: implicitEnvVars,
WorkingDir: workspaceDir,
}
}
return nil
}
// initOutputResourcesDefaultDir checks if there are any output image resources expecting a default path
// and creates an init container to create that folder
func initOutputResourcesDefaultDir(taskRun *v1alpha1.TaskRun, taskSpec v1alpha1.TaskSpec) []corev1.Container {
makeDirSteps := []corev1.Container{}
if len(taskRun.Spec.Outputs.Resources) > 0 {
for _, r := range taskRun.Spec.Outputs.Resources {
for _, o := range taskSpec.Outputs.Resources {
if o.Name == r.Name {
if strings.HasPrefix(o.OutputImageDir, v1alpha1.TaskOutputImageDefaultDir) {
cn := v1alpha1.CreateDirContainer("default-image-output", fmt.Sprintf("%s/%s", v1alpha1.TaskOutputImageDefaultDir, r.Name))
cn.VolumeMounts = append(cn.VolumeMounts, implicitVolumeMounts...)
makeDirSteps = append(makeDirSteps, cn)
}
}
}
}
}
return makeDirSteps
}
// GetPod returns the Pod for the given pod name
type GetPod func(string, metav1.GetOptions) (*corev1.Pod, error)
// TryGetPod fetches the TaskRun's pod, returning nil if it has not been created or it does not exist.
func TryGetPod(taskRunStatus v1alpha1.TaskRunStatus, gp GetPod) (*corev1.Pod, error) {
if taskRunStatus.PodName == "" {
return nil, nil
}
pod, err := gp(taskRunStatus.PodName, metav1.GetOptions{})
if err == nil || errors.IsNotFound(err) {
return pod, nil
}
return nil, err
}
// MakePod converts TaskRun and TaskSpec objects to a Pod which implements the taskrun specified
// by the supplied CRD.
func MakePod(taskRun *v1alpha1.TaskRun, taskSpec v1alpha1.TaskSpec, kubeclient kubernetes.Interface, cache *entrypoint.Cache, logger *zap.SugaredLogger) (*corev1.Pod, error) {
cred, secrets, err := makeCredentialInitializer(taskRun.Spec.ServiceAccount, taskRun.Namespace, kubeclient)
if err != nil {
return nil, err
}
initContainers := []corev1.Container{*cred}
podContainers := []corev1.Container{}
if workingDir := makeWorkingDirInitializer(taskSpec.Steps); workingDir != nil {
initContainers = append(initContainers, *workingDir)
}
initContainers = append(initContainers, initOutputResourcesDefaultDir(taskRun, taskSpec)...)
maxIndicesByResource := findMaxResourceRequest(taskSpec.Steps, corev1.ResourceCPU, corev1.ResourceMemory, corev1.ResourceEphemeralStorage)
for i := range taskSpec.Steps {
step := &taskSpec.Steps[i]
step.Env = append(implicitEnvVars, step.Env...)
// TODO(mattmoor): Check that volumeMounts match volumes.
// Add implicit volume mounts, unless the user has requested
// their own volume mount at that path.
requestedVolumeMounts := map[string]bool{}
for _, vm := range step.VolumeMounts {
requestedVolumeMounts[filepath.Clean(vm.MountPath)] = true
}
for _, imp := range implicitVolumeMounts {
if !requestedVolumeMounts[filepath.Clean(imp.MountPath)] {
step.VolumeMounts = append(step.VolumeMounts, imp)
}
}
if step.WorkingDir == "" {
step.WorkingDir = workspaceDir
}
if step.Name == "" {
step.Name = fmt.Sprintf("%v%d", unnamedInitContainerPrefix, i)
} else {
step.Name = names.SimpleNameGenerator.RestrictLength(fmt.Sprintf("%v%v", containerPrefix, step.Name))
}
// use the step name to add the entrypoint biary as an init container
if step.Name == names.SimpleNameGenerator.RestrictLength(fmt.Sprintf("%v%v", containerPrefix, entrypoint.InitContainerName)) {
initContainers = append(initContainers, *step)
} else {
zeroNonMaxResourceRequests(step, i, maxIndicesByResource)
podContainers = append(podContainers, *step)
}
}
// Add our implicit volumes and any volumes needed for secrets to the explicitly
// declared user volumes.
volumes := append(taskSpec.Volumes, implicitVolumes...)
volumes = append(volumes, secrets...)
if err := v1alpha1.ValidateVolumes(volumes); err != nil {
return nil, err
}
// Generate a short random hex string.
b, err := ioutil.ReadAll(io.LimitReader(randReader, 3))
if err != nil {
return nil, err
}
gibberish := hex.EncodeToString(b)
mergedInitContainers, err := merge.CombineStepsWithStepTemplate(taskSpec.StepTemplate, initContainers)
if err != nil {
return nil, err
}
mergedPodContainers, err := merge.CombineStepsWithStepTemplate(taskSpec.StepTemplate, podContainers)
if err != nil {
return nil, err
}
// The ContainerTemplate field is deprecated (#977)
mergedInitContainers, err = merge.CombineStepsWithStepTemplate(taskSpec.ContainerTemplate, mergedInitContainers)
if err != nil {
return nil, err
}
mergedPodContainers, err = merge.CombineStepsWithStepTemplate(taskSpec.ContainerTemplate, mergedPodContainers)
if err != nil {
return nil, err
}
return &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
// We execute the build's pod in the same namespace as where the build was
// created so that it can access colocated resources.
Namespace: taskRun.Namespace,
// Generate a unique name based on the build's name.
// Add a unique suffix to avoid confusion when a build
// is deleted and re-created with the same name.
// We don't use RestrictLengthWithRandomSuffix here because k8s fakes don't support it.
Name: fmt.Sprintf("%s-pod-%s", taskRun.Name, gibberish),
// If our parent TaskRun is deleted, then we should be as well.
OwnerReferences: []metav1.OwnerReference{
*metav1.NewControllerRef(taskRun, groupVersionKind),
},
Annotations: makeAnnotations(taskRun),
Labels: makeLabels(taskRun),
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyNever,
InitContainers: mergedInitContainers,
Containers: mergedPodContainers,
ServiceAccountName: taskRun.Spec.ServiceAccount,
Volumes: volumes,
NodeSelector: taskRun.Spec.NodeSelector,
Tolerations: taskRun.Spec.Tolerations,
Affinity: taskRun.Spec.Affinity,
},
}, nil
}
type UpdatePod func(*corev1.Pod) (*corev1.Pod, error)
// AddReadyAnnotation adds the ready annotation if it is not present.
// Returns any error that comes back from the passed-in update func.
func AddReadyAnnotation(p *corev1.Pod, update UpdatePod) error {
if p.ObjectMeta.Annotations == nil {
p.ObjectMeta.Annotations = make(map[string]string)
}
if p.ObjectMeta.Annotations[ReadyAnnotation] != readyAnnotationValue {
p.ObjectMeta.Annotations[ReadyAnnotation] = readyAnnotationValue
_, err := update(p)
return err
}
return nil
}
func IsContainerStep(name string) bool {
return strings.HasPrefix(name, containerPrefix)
}
// makeLabels constructs the labels we will propagate from TaskRuns to Pods.
func makeLabels(s *v1alpha1.TaskRun) map[string]string {
labels := make(map[string]string, len(s.ObjectMeta.Labels)+1)
for k, v := range s.ObjectMeta.Labels {
labels[k] = v
}
labels[pipeline.GroupName+pipeline.TaskRunLabelKey] = s.Name
return labels
}
// makeAnnotations constructs the annotations we will propagate from TaskRuns to Pods
// and adds any other annotations that will be needed to initialize a Pod.
func makeAnnotations(s *v1alpha1.TaskRun) map[string]string {
annotations := make(map[string]string, len(s.ObjectMeta.Annotations)+1)
for k, v := range s.ObjectMeta.Annotations {
annotations[k] = v
}
annotations[ReadyAnnotation] = ""
return annotations
}
// zeroNonMaxResourceRequests zeroes out the container's cpu, memory, or
// ephemeral storage resource requests if the container does not have the
// largest request out of all containers in the pod. This is done because Tekton
// overwrites each container's entrypoint to make containers effectively execute
// one at a time, so we want pods to only request the maximum resources needed
// at any single point in time. If no container has an explicit resource
// request, all requests are set to 0.
func zeroNonMaxResourceRequests(container *corev1.Container, containerIndex int, maxIndicesByResource map[corev1.ResourceName]int) {
if container.Resources.Requests == nil {
container.Resources.Requests = corev1.ResourceList{}
}
for name, maxIdx := range maxIndicesByResource {
if maxIdx != containerIndex {
container.Resources.Requests[name] = zeroQty
}
}
}
// findMaxResourceRequest returns the index of the container with the maximum
// request for the given resource from among the given set of containers.
func findMaxResourceRequest(containers []corev1.Container, resourceNames ...corev1.ResourceName) map[corev1.ResourceName]int {
maxIdxs := make(map[corev1.ResourceName]int, len(resourceNames))
maxReqs := make(map[corev1.ResourceName]resource.Quantity, len(resourceNames))
for _, name := range resourceNames {
maxIdxs[name] = -1
maxReqs[name] = zeroQty
}
for i, c := range containers {
for _, name := range resourceNames {
maxReq := maxReqs[name]
req, exists := c.Resources.Requests[name]
if exists && req.Cmp(maxReq) > 0 {
maxIdxs[name] = i
maxReqs[name] = req
}
}
}
return maxIdxs
}
// TrimContainerNamePrefix trim the container name prefix to get the corresponding step name
func TrimContainerNamePrefix(containerName string) string {
return strings.TrimPrefix(containerName, containerPrefix)
}