-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
reconcile_resources.go
197 lines (173 loc) · 7.64 KB
/
reconcile_resources.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
/*
Copyright 2018 The Knative 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 revision
import (
"context"
"fmt"
"go.uber.org/zap"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/kmeta"
"knative.dev/pkg/kmp"
"knative.dev/pkg/logging"
"knative.dev/pkg/logging/logkey"
v1 "knative.dev/serving/pkg/apis/serving/v1"
"knative.dev/serving/pkg/reconciler/revision/resources"
resourcenames "knative.dev/serving/pkg/reconciler/revision/resources/names"
)
func (c *Reconciler) reconcileDeployment(ctx context.Context, rev *v1.Revision) error {
ns := rev.Namespace
deploymentName := resourcenames.Deployment(rev)
logger := logging.FromContext(ctx).With(zap.String(logkey.Deployment, deploymentName))
deployment, err := c.deploymentLister.Deployments(ns).Get(deploymentName)
if apierrs.IsNotFound(err) {
// Deployment does not exist. Create it.
rev.Status.MarkResourcesAvailableUnknown(v1.ReasonDeploying, "")
rev.Status.MarkContainerHealthyUnknown(v1.ReasonDeploying, "")
deployment, err = c.createDeployment(ctx, rev)
if err != nil {
return fmt.Errorf("failed to create deployment %q: %w", deploymentName, err)
}
logger.Infof("Created deployment %q", deploymentName)
} else if err != nil {
return fmt.Errorf("failed to get deployment %q: %w", deploymentName, err)
} else if !metav1.IsControlledBy(deployment, rev) {
// Surface an error in the revision's status, and return an error.
rev.Status.MarkResourcesAvailableFalse(v1.ReasonNotOwned, v1.ResourceNotOwnedMessage("Deployment", deploymentName))
return fmt.Errorf("revision: %q does not own Deployment: %q", rev.Name, deploymentName)
} else {
// The deployment exists, but make sure that it has the shape that we expect.
deployment, err = c.checkAndUpdateDeployment(ctx, rev, deployment)
if err != nil {
return fmt.Errorf("failed to update deployment %q: %w", deploymentName, err)
}
// Now that we have a Deployment, determine whether there is any relevant
// status to surface in the Revision.
//
// TODO(jonjohnsonjr): Should we check Generation != ObservedGeneration?
// The autoscaler mutates the deployment pretty often, which would cause us
// to flip back and forth between Ready and Unknown every time we scale up
// or down.
if !rev.Status.IsActivationRequired() {
rev.Status.PropagateDeploymentStatus(&deployment.Status)
}
}
// If a container keeps crashing (no active pods in the deployment although we want some)
if *deployment.Spec.Replicas > 0 && deployment.Status.AvailableReplicas == 0 {
pods, err := c.kubeclient.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{LabelSelector: metav1.FormatLabelSelector(deployment.Spec.Selector)})
if err != nil {
logger.Errorw("Error getting pods", zap.Error(err))
return nil
}
if len(pods.Items) > 0 {
// Arbitrarily grab the very first pod, as they all should be crashing
pod := pods.Items[0]
// Update the revision status if pod cannot be scheduled (possibly resource constraints)
// If pod cannot be scheduled then we expect the container status to be empty.
for _, cond := range pod.Status.Conditions {
if cond.Type == corev1.PodScheduled && cond.Status == corev1.ConditionFalse {
rev.Status.MarkResourcesAvailableFalse(cond.Reason, cond.Message)
break
}
}
for _, status := range pod.Status.ContainerStatuses {
if status.Name == rev.Spec.GetContainer().Name {
if t := status.LastTerminationState.Terminated; t != nil {
logger.Infof("marking exiting with: %d/%s", t.ExitCode, t.Message)
rev.Status.MarkContainerHealthyFalse(v1.ExitCodeReason(t.ExitCode), v1.RevisionContainerExitingMessage(t.Message))
} else if w := status.State.Waiting; w != nil && hasDeploymentTimedOut(deployment) {
logger.Infof("marking resources unavailable with: %s: %s", w.Reason, w.Message)
rev.Status.MarkResourcesAvailableFalse(w.Reason, w.Message)
}
break
}
}
}
}
return nil
}
func (c *Reconciler) reconcileImageCache(ctx context.Context, rev *v1.Revision) error {
logger := logging.FromContext(ctx)
ns := rev.Namespace
// Revisions are immutable.
// Updating image results to new revision so there won't be any chance of resource leak.
for _, container := range rev.Status.ContainerStatuses {
imageName := kmeta.ChildName(resourcenames.ImageCache(rev), "-"+container.Name)
if _, err := c.imageLister.Images(ns).Get(imageName); apierrs.IsNotFound(err) {
if _, err := c.createImageCache(ctx, rev, container.Name, container.ImageDigest); err != nil {
return fmt.Errorf("failed to create image cache %q: %w", imageName, err)
}
logger.Infof("Created image cache %q", imageName)
} else if err != nil {
return fmt.Errorf("failed to get image cache %q: %w", imageName, err)
}
}
return nil
}
func (c *Reconciler) reconcilePA(ctx context.Context, rev *v1.Revision) error {
ns := rev.Namespace
paName := resourcenames.PA(rev)
logger := logging.FromContext(ctx)
logger.Info("Reconciling PA: ", paName)
pa, err := c.podAutoscalerLister.PodAutoscalers(ns).Get(paName)
if apierrs.IsNotFound(err) {
// PA does not exist. Create it.
pa, err = c.createPA(ctx, rev)
if err != nil {
return fmt.Errorf("failed to create PA %q: %w", paName, err)
}
logger.Info("Created PA: ", paName)
} else if err != nil {
return fmt.Errorf("failed to get PA %q: %w", paName, err)
} else if !metav1.IsControlledBy(pa, rev) {
// Surface an error in the revision's status, and return an error.
rev.Status.MarkResourcesAvailableFalse(v1.ReasonNotOwned, v1.ResourceNotOwnedMessage("PodAutoscaler", paName))
return fmt.Errorf("revision: %q does not own PodAutoscaler: %q", rev.Name, paName)
}
// Perhaps tha PA spec changed underneath ourselves?
// We no longer require immutability, so need to reconcile PA each time.
tmpl := resources.MakePA(rev)
logger.Debugf("Desired PASpec: %#v", tmpl.Spec)
if !equality.Semantic.DeepEqual(tmpl.Spec, pa.Spec) {
diff, _ := kmp.SafeDiff(tmpl.Spec, pa.Spec) // Can't realistically fail on PASpec.
logger.Infof("PA %s needs reconciliation, diff(-want,+got):\n%s", pa.Name, diff)
want := pa.DeepCopy()
want.Spec = tmpl.Spec
if pa, err = c.client.AutoscalingV1alpha1().PodAutoscalers(ns).Update(ctx, want, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("failed to update PA %q: %w", paName, err)
}
}
// The public service name is always equal to the revision name itself.
// Historically it's been acquired from the PA object, so the assignment is here.
rev.Status.ServiceName = rev.Name
logger.Debugf("Observed PA Status=%#v", pa.Status)
rev.Status.PropagateAutoscalerStatus(&pa.Status)
return nil
}
func hasDeploymentTimedOut(deployment *appsv1.Deployment) bool {
// as per https://kubernetes.io/docs/concepts/workloads/controllers/deployment
for _, cond := range deployment.Status.Conditions {
// Look for a condition with status False
if cond.Status != corev1.ConditionFalse {
continue
}
// with Type Progressing and Reason Timeout
if cond.Type == appsv1.DeploymentProgressing && cond.Reason == v1.ReasonProgressDeadlineExceeded {
return true
}
}
return false
}