-
Notifications
You must be signed in to change notification settings - Fork 288
/
podbuilder.go
368 lines (314 loc) · 9.3 KB
/
podbuilder.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
package podbuilder
import (
"fmt"
"testing"
"time"
"github.com/docker/distribution/reference"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/validation"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"github.com/windmilleng/tilt/internal/container"
"github.com/windmilleng/tilt/internal/k8s"
"github.com/windmilleng/tilt/pkg/model"
)
const FakeDeployID = model.DeployID(1234567890)
const fakeContainerID = container.ID("myTestContainer")
func FakeContainerID() container.ID {
return FakeContainerIDAtIndex(0)
}
func FakeContainerIDAtIndex(index int) container.ID {
indexSuffix := ""
if index != 0 {
indexSuffix = fmt.Sprintf("-%d", index)
}
return container.ID(fmt.Sprintf("%s%s", fakeContainerID, indexSuffix))
}
func FakeContainerIDSet(size int) map[container.ID]bool {
result := container.NewIDSet()
for i := 0; i < size; i++ {
result[FakeContainerIDAtIndex(i)] = true
}
return result
}
// Builds Pod objects for testing
//
// The pod model should be internally well-formed (e.g., the containers
// in the PodSpec object should match the containers in the PodStatus object).
//
// The pod model should also be consistent with the Manifest (e.g., if the Manifest
// specifies a Deployment with labels in a PodTemplateSpec, then any Pods should also
// have those labels).
//
// The PodBuilder is responsible for making sure we create well-formed Pods for
// testing. Tests should never modify the pod directly, but instead use the PodBuilder
// methods to ensure that the pod is consistent.
type PodBuilder struct {
t testing.TB
manifest model.Manifest
podID string
phase string
creationTime time.Time
deletionTime time.Time
deployID model.DeployID
restartCount int
extraPodLabels map[string]string
deploymentUID types.UID
// keyed by container index -- i.e. the first container will have image: imageRefs[0] and ID: cIDs[0], etc.
// If there's no entry at index i, we'll use a dummy value.
imageRefs map[int]string
cIDs map[int]string
}
func New(t testing.TB, manifest model.Manifest) PodBuilder {
return PodBuilder{
t: t,
manifest: manifest,
imageRefs: make(map[int]string),
cIDs: make(map[int]string),
extraPodLabels: make(map[string]string),
}
}
func (b PodBuilder) WithPodLabel(key, val string) PodBuilder {
b.extraPodLabels[key] = val
return b
}
func (b PodBuilder) ManifestName() model.ManifestName {
return b.manifest.Name
}
func (b PodBuilder) RestartCount() int {
return b.restartCount
}
func (b PodBuilder) WithRestartCount(restartCount int) PodBuilder {
b.restartCount = restartCount
return b
}
func (b PodBuilder) WithPodID(podID string) PodBuilder {
msgs := validation.NameIsDNSSubdomain(podID, false)
if len(msgs) != 0 {
b.t.Fatalf("pod id %q is invalid: %s", podID, msgs)
}
b.podID = podID
return b
}
func (b PodBuilder) WithPhase(phase string) PodBuilder {
b.phase = phase
return b
}
func (b PodBuilder) WithImage(image string) PodBuilder {
return b.WithImageAtIndex(image, 0)
}
func (b PodBuilder) WithImageAtIndex(image string, index int) PodBuilder {
b.imageRefs[index] = image
return b
}
func (b PodBuilder) WithContainerID(cID container.ID) PodBuilder {
return b.WithContainerIDAtIndex(cID, 0)
}
func (b PodBuilder) WithContainerIDAtIndex(cID container.ID, index int) PodBuilder {
if cID == "" {
b.cIDs[index] = ""
} else {
b.cIDs[index] = fmt.Sprintf("%s%s", k8s.ContainerIDPrefix, cID)
}
return b
}
func (b PodBuilder) WithCreationTime(creationTime time.Time) PodBuilder {
b.creationTime = creationTime
return b
}
func (b PodBuilder) WithDeletionTime(deletionTime time.Time) PodBuilder {
b.deletionTime = deletionTime
return b
}
func (b PodBuilder) WithDeployID(deployID model.DeployID) PodBuilder {
b.deployID = deployID
return b
}
func (b PodBuilder) PodID() string {
if b.podID != "" {
return b.podID
}
return "fakePodID"
}
func (b PodBuilder) buildPodUID() types.UID {
return types.UID(fmt.Sprintf("%s-fakeUID", b.PodID()))
}
func (b PodBuilder) WithDeploymentUID(deploymentUID types.UID) PodBuilder {
b.deploymentUID = deploymentUID
return b
}
func (b PodBuilder) buildReplicaSetName() string {
return fmt.Sprintf("%s-replicaset", b.manifest.Name)
}
func (b PodBuilder) buildReplicaSetUID() types.UID {
return types.UID(fmt.Sprintf("%s-fakeUID", b.buildReplicaSetName()))
}
func (b PodBuilder) buildDeploymentName() string {
return b.manifest.Name.String()
}
func (b PodBuilder) DeploymentUID() types.UID {
if b.deploymentUID != "" {
return b.deploymentUID
}
return types.UID(fmt.Sprintf("%s-fakeUID", b.buildDeploymentName()))
}
func (b PodBuilder) buildDeployment() *appsv1.Deployment {
return &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: b.buildDeploymentName(),
Labels: k8s.NewTiltLabelMap(),
UID: b.DeploymentUID(),
},
}
}
func (b PodBuilder) buildReplicaSet() *appsv1.ReplicaSet {
dep := b.buildDeployment()
return &appsv1.ReplicaSet{
ObjectMeta: metav1.ObjectMeta{
Name: b.buildReplicaSetName(),
UID: b.buildReplicaSetUID(),
Labels: k8s.NewTiltLabelMap(),
OwnerReferences: []metav1.OwnerReference{
k8s.RuntimeObjToOwnerRef(dep),
},
},
}
}
func (b PodBuilder) buildCreationTime() metav1.Time {
if !b.creationTime.IsZero() {
return metav1.Time{Time: b.creationTime}
}
return metav1.Time{Time: time.Now()}
}
func (b PodBuilder) buildDeletionTime() *metav1.Time {
if !b.deletionTime.IsZero() {
return &metav1.Time{Time: b.deletionTime}
}
return nil
}
func (b PodBuilder) buildLabels(tSpec *v1.PodTemplateSpec) map[string]string {
deployID := b.deployID
if deployID.Empty() {
deployID = FakeDeployID
}
labels := k8s.NewTiltLabelMap()
for k, v := range tSpec.Labels {
labels[k] = v
}
for k, v := range b.extraPodLabels {
labels[k] = v
}
return labels
}
func (b PodBuilder) buildImage(imageSpec string, index int) string {
image, ok := b.imageRefs[index]
if ok {
return image
}
imageSpecRef := container.MustParseNamed(imageSpec)
// Use the pod ID as the image tag. This is kind of weird, but gets at the semantics
// we want (e.g., a new pod ID indicates that this is a new build).
// Tests that don't want this behavior should replace the image with setImage(pod, imageName)
return fmt.Sprintf("%s:%s", imageSpecRef.Name(), b.PodID())
}
func (b PodBuilder) buildContainerID(index int) string {
cID, ok := b.cIDs[index]
if ok {
return cID
}
return fmt.Sprintf("%s%s", k8s.ContainerIDPrefix, FakeContainerIDAtIndex(index))
}
func (b PodBuilder) buildPhase() v1.PodPhase {
if b.phase == "" {
return v1.PodPhase("Running")
}
return v1.PodPhase(b.phase)
}
func (b PodBuilder) buildContainerStatuses(spec v1.PodSpec) []v1.ContainerStatus {
result := make([]v1.ContainerStatus, len(spec.Containers))
for i, cSpec := range spec.Containers {
restartCount := 0
if i == 0 {
restartCount = b.restartCount
}
result[i] = v1.ContainerStatus{
Name: cSpec.Name,
Image: b.buildImage(cSpec.Image, i),
Ready: true,
ContainerID: b.buildContainerID(i),
RestartCount: int32(restartCount),
}
}
return result
}
func (b PodBuilder) validateImageRefs(numContainers int) {
for index, img := range b.imageRefs {
if index >= numContainers {
b.t.Fatalf("Image %q specified at index %d. Pod only has %d containers", img, index, numContainers)
}
}
}
func (b PodBuilder) validateContainerIDs(numContainers int) {
for index, cID := range b.cIDs {
if index >= numContainers {
b.t.Fatalf("Container ID %q specified at index %d. Pod only has %d containers", cID, index, numContainers)
}
}
}
// Simulates a Pod -> ReplicaSet -> Deployment ref tree
func (b PodBuilder) ObjectTreeEntities() []k8s.K8sEntity {
pod := b.Build()
rs := b.buildReplicaSet()
dep := b.buildDeployment()
return []k8s.K8sEntity{
k8s.NewK8sEntity(pod),
k8s.NewK8sEntity(rs),
k8s.NewK8sEntity(dep),
}
}
func (b PodBuilder) Build() *v1.Pod {
entities, err := parseYAMLFromManifest(b.manifest)
if err != nil {
b.t.Fatal(fmt.Errorf("PodBuilder YAML parser: %v", err))
}
tSpecs, err := k8s.ExtractPodTemplateSpec(entities)
if err != nil {
b.t.Fatal(fmt.Errorf("PodBuilder extract pod templates: %v", err))
}
if len(tSpecs) != 1 {
b.t.Fatalf("PodBuilder only works with Manifests with exactly 1 PodTemplateSpec: %v", tSpecs)
}
tSpec := tSpecs[0]
spec := tSpec.Spec
numContainers := len(spec.Containers)
b.validateImageRefs(numContainers)
b.validateContainerIDs(numContainers)
for i, container := range spec.Containers {
container.Image = b.buildImage(container.Image, i)
spec.Containers[i] = container
}
return &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: b.PodID(),
CreationTimestamp: b.buildCreationTime(),
DeletionTimestamp: b.buildDeletionTime(),
Labels: b.buildLabels(tSpec),
UID: b.buildPodUID(),
OwnerReferences: []metav1.OwnerReference{
k8s.RuntimeObjToOwnerRef(b.buildReplicaSet()),
},
},
Spec: spec,
Status: v1.PodStatus{
Phase: b.buildPhase(),
ContainerStatuses: b.buildContainerStatuses(spec),
},
}
}
func imageNameForManifest(manifestName string) reference.Named {
return container.MustParseNamed(manifestName)
}
func parseYAMLFromManifest(m model.Manifest) ([]k8s.K8sEntity, error) {
return k8s.ParseYAMLFromString(m.K8sTarget().YAML)
}