/
update.go
280 lines (240 loc) · 8.32 KB
/
update.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
/*
Copyright 2018 Heptio Inc.
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 aggregation
import (
"context"
"encoding/json"
"fmt"
"sync"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"github.com/vmware-tanzu/sonobuoy/pkg/plugin"
)
const (
StatusAnnotationName = "sonobuoy.hept.io/status"
DefaultStatusPodName = "sonobuoy"
)
// NoPodWithLabelError represents an error encountered when a pod with a given label can't be found
type NoPodWithLabelError string
func (n NoPodWithLabelError) Error() string {
return string(n)
}
// updater manages setting the Aggregator annotation with the current status
type updater struct {
sync.RWMutex
positionLookup map[string]*PluginStatus
status Status
namespace string
client kubernetes.Interface
}
// newUpdater creates an an updater that expects ExpectedResult.
func newUpdater(expected []plugin.ExpectedResult, namespace string, client kubernetes.Interface) *updater {
u := &updater{
positionLookup: make(map[string]*PluginStatus),
status: Status{
Plugins: make([]PluginStatus, len(expected)),
Status: RunningStatus,
},
namespace: namespace,
client: client,
}
for i, result := range expected {
u.status.Plugins[i] = PluginStatus{
Node: result.NodeName,
Plugin: result.ResultType,
Status: RunningStatus,
}
u.positionLookup[result.ID()] = &u.status.Plugins[i]
}
return u
}
// Receive updates the updater's internal status of an individual plugin.
func (u *updater) Receive(update *PluginStatus) error {
u.Lock()
defer u.Unlock()
status, ok := u.positionLookup[update.Key()]
if !ok {
return fmt.Errorf("couldn't find key for %v", update.Key())
}
// Updating status updates the u.status object.
deepCopyPluginStatus(status, update)
return u.status.updateStatus()
}
func deepCopyPluginStatus(dst, src *PluginStatus) {
dst.Plugin = src.Plugin
dst.Node = src.Node
dst.Status = src.Status
dst.ResultStatus = src.ResultStatus
if src.ResultStatusCounts != nil {
dst.ResultStatusCounts = map[string]int{}
for k, v := range src.ResultStatusCounts {
dst.ResultStatusCounts[k] = v
}
}
if src.Progress != nil {
dst.Progress = &plugin.ProgressUpdate{
PluginName: src.Progress.PluginName,
Node: src.Progress.Node,
Timestamp: src.Progress.Timestamp,
Message: src.Progress.Message,
Total: src.Progress.Total,
Completed: src.Progress.Completed,
}
if src.Progress.Errors != nil {
dst.Progress.Errors = make([]string, len(src.Progress.Errors))
copy(dst.Progress.Errors, src.Progress.Errors)
}
if src.Progress.Failures != nil {
dst.Progress.Failures = make([]string, len(src.Progress.Failures))
copy(dst.Progress.Failures, src.Progress.Failures)
}
}
}
// Serialize json-encodes the status object.
func (u *updater) Serialize() (string, error) {
u.RLock()
defer u.RUnlock()
bytes, err := json.Marshal(u.status)
return string(bytes), errors.Wrap(err, "couldn't marshall status")
}
// Annotate serializes the status json, then annotates the aggregator pod with the status.
func (u *updater) Annotate(results map[string]*plugin.Result, progressUpdates map[string]*plugin.ProgressUpdate) error {
u.ReceiveAll(results, progressUpdates)
u.RLock()
defer u.RUnlock()
str, err := u.Serialize()
if err != nil {
return errors.Wrap(err, "couldn't serialize status")
}
patch := GetPatch(str)
bytes, err := json.Marshal(patch)
if err != nil {
return errors.Wrap(err, "couldn't encode patch")
}
// Determine sonobuoy pod name
podName, err := GetAggregatorPodName(u.client, u.namespace)
if err != nil {
return errors.Wrap(err, "failed to get name of the aggregator pod to annotate")
}
_, err = u.client.CoreV1().Pods(u.namespace).Patch(context.TODO(), podName, types.MergePatchType, bytes, metav1.PatchOptions{})
return errors.Wrap(err, "couldn't patch pod annotation")
}
// TODO (tstclair): Evaluate if this should be exported.
// ReceiveAll takes a map of plugin.Result and plugin.ProgressUpdates and uses Recieve to turn
// update the updater's status.
func (u *updater) ReceiveAll(results map[string]*plugin.Result, progressUpdates map[string]*plugin.ProgressUpdate) {
// With the addition of progress updates we have two maps of data; iterate once to get all the keys then once to process.
keys := map[string]struct{}{}
for k := range results {
keys[k] = struct{}{}
}
for k := range progressUpdates {
keys[k] = struct{}{}
}
// Could have race conditions, but will be eventually consistent
for k := range keys {
update := PluginStatus{}
result, hasResult := results[k]
switch {
case !hasResult:
update.Status = "running"
update.Plugin = progressUpdates[k].PluginName
update.Node = progressUpdates[k].Node
case result.Error != "":
update.Status = "failed"
update.Plugin = results[k].ResultType
update.Node = results[k].NodeName
default:
update.Status = "complete"
update.Plugin = results[k].ResultType
update.Node = results[k].NodeName
}
update.Progress = progressUpdates[k]
if err := u.Receive(&update); err != nil {
logrus.WithFields(
logrus.Fields{
"node": update.Node,
"plugin": update.Plugin,
"status": update.Status,
},
).WithError(err).Info("couldn't update plugin")
}
}
}
// GetPatch takes a json encoded string and creates a map which can be used as
// a patch to indicate the Sonobuoy status.
func GetPatch(annotation string) map[string]interface{} {
return map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]string{
StatusAnnotationName: annotation,
},
},
}
}
// GetAggregatorPod gets the sonobuoy aggregator pod based on its label.
// It returns NoPodWithLabelError in the case where a pod with sonobuoy aggregator label could not be found.
func GetAggregatorPod(client kubernetes.Interface, namespace string) (*v1.Pod, error) {
getPodWithLabel := func(label string) (*v1.Pod, error) {
listOptions := metav1.ListOptions{
LabelSelector: label,
}
podList, err := client.CoreV1().Pods(namespace).List(context.TODO(), listOptions)
if err != nil {
return nil, errors.Wrapf(err, "unable to list pods with label %q", label)
}
switch {
case len(podList.Items) == 0:
logrus.Warningf("no pods found with label %q in namespace %s", label, namespace)
return nil, NoPodWithLabelError(fmt.Sprintf("no pods found with label %q in namespace %s", label, namespace))
case len(podList.Items) > 1:
logrus.Warningf("Found more than one pod with label %q. Using pod with name %q", label, podList.Items[0].GetName())
return &podList.Items[0], nil
default:
return &podList.Items[0], nil
}
}
aggregatorPodLabel := "sonobuoy-component=aggregator"
deprecatedAggregatorPodLabel := "run=sonobuoy-master"
pod, err := getPodWithLabel(aggregatorPodLabel)
if err != nil || pod == nil {
if _, ok := err.(NoPodWithLabelError); !ok {
// If we encountered an error which doesn't correspond to no pods existing,
// log the error as a warning.
logrus.Warning(err)
}
// In either case, retry using the deprecated aggregator pod label.
logrus.Warningf("retrying with deprecated label %q", deprecatedAggregatorPodLabel)
pod, err = getPodWithLabel(deprecatedAggregatorPodLabel)
}
return pod, err
}
// GetAggregatorPodName gets the sonobuoy aggregator pod name. It returns the default pod name
// if the pod cannot be found.
func GetAggregatorPodName(client kubernetes.Interface, namespace string) (string, error) {
ap, err := GetAggregatorPod(client, namespace)
if err != nil {
switch err.(type) {
case NoPodWithLabelError:
logrus.Warningf("Aggregator pod not found, using default pod name %q: %v", DefaultStatusPodName, err)
return DefaultStatusPodName, nil
default:
return "", errors.Wrap(err, "failed to get aggregator pod")
}
}
return ap.GetName(), nil
}