...
1
16
17 package kuberuntime
18
19 import (
20 "time"
21
22 v1 "k8s.io/api/core/v1"
23
24 "k8s.io/kubernetes/pkg/kubelet/types"
25 )
26
27
28
29
30 type terminationOrdering struct {
31
32
33 terminated map[string]chan struct{}
34
35
36 prereqs map[string][]chan struct{}
37 }
38
39
40 func newTerminationOrdering(pod *v1.Pod, runningContainerNames []string) *terminationOrdering {
41 to := &terminationOrdering{
42 prereqs: map[string][]chan struct{}{},
43 terminated: map[string]chan struct{}{},
44 }
45
46 runningContainers := map[string]struct{}{}
47 for _, name := range runningContainerNames {
48 runningContainers[name] = struct{}{}
49 }
50
51 var mainContainerChannels []chan struct{}
52
53
54 for _, c := range pod.Spec.Containers {
55 channel := make(chan struct{})
56 to.terminated[c.Name] = channel
57 mainContainerChannels = append(mainContainerChannels, channel)
58
59
60 if _, isRunning := runningContainers[c.Name]; !isRunning {
61 close(channel)
62 }
63 }
64
65 var previousSidecarName string
66 for i := range pod.Spec.InitContainers {
67
68 ic := pod.Spec.InitContainers[len(pod.Spec.InitContainers)-i-1]
69
70 to.terminated[ic.Name] = make(chan struct{})
71
72 if types.IsRestartableInitContainer(&ic) {
73
74 to.prereqs[ic.Name] = append(to.prereqs[ic.Name], mainContainerChannels...)
75
76
77 if previousSidecarName != "" {
78 to.prereqs[ic.Name] = append(to.prereqs[ic.Name], to.terminated[previousSidecarName])
79 }
80 previousSidecarName = ic.Name
81 }
82 }
83 return to
84 }
85
86
87
88 func (o *terminationOrdering) waitForTurn(name string, gracePeriod int64) float64 {
89
90 if gracePeriod <= 0 {
91 return 0
92 }
93
94 start := time.Now()
95 remainingGrace := time.NewTimer(time.Duration(gracePeriod) * time.Second)
96
97 for _, c := range o.prereqs[name] {
98 select {
99 case <-c:
100 case <-remainingGrace.C:
101
102 return time.Since(start).Seconds()
103 }
104 }
105
106 return time.Since(start).Seconds()
107 }
108
109
110 func (o *terminationOrdering) containerTerminated(name string) {
111 if ch, ok := o.terminated[name]; ok {
112 close(ch)
113 }
114 }
115
View as plain text