-
Notifications
You must be signed in to change notification settings - Fork 342
/
discovery.go
180 lines (149 loc) · 5.54 KB
/
discovery.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
/*
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 discovery
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"time"
"github.com/heptio/sonobuoy/pkg/config"
"github.com/heptio/sonobuoy/pkg/errlog"
"github.com/pkg/errors"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"github.com/viniciuschiele/tarx"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
pluginaggregation "github.com/heptio/sonobuoy/pkg/plugin/aggregation"
)
// Run is the main entrypoint for discovery.
func Run(restConf *rest.Config, cfg *config.Config) (errCount int) {
t := time.Now()
kubeClient, err := kubernetes.NewForConfig(restConf)
if err != nil {
errlog.LogError(errors.Wrap(err, "could not create kubernetes client"))
return errCount + 1
}
crdClient, err := apiextensionsclient.NewForConfig(restConf)
if err != nil {
errlog.LogError(errors.Wrap(err, "could not create apiextensions client"))
return errCount + 1
}
// 1. Create the directory which will store the results, including the
// `meta` directory inside it (which we always need regardless of
// config)
outpath := path.Join(cfg.ResultsDir, cfg.UUID)
metapath := path.Join(outpath, MetaLocation)
err = os.MkdirAll(metapath, 0755)
if err != nil {
errlog.LogError(errors.Wrap(err, "could not create directory to store results"))
return errCount + 1
}
// Write logs to the configured results location. All log levels
// should write to the same log file
pathmap := make(lfshook.PathMap)
logfile := path.Join(metapath, "run.log")
for _, level := range logrus.AllLevels {
pathmap[level] = logfile
}
hook := lfshook.NewHook(pathmap, &logrus.JSONFormatter{})
logrus.AddHook(hook)
// Unset all hooks as we exit the Run function
defer func() {
logrus.StandardLogger().Hooks = make(logrus.LevelHooks)
}()
// closure used to collect and report errors.
trackErrorsFor := func(action string) func(error) {
return func(err error) {
if err != nil {
errCount++
errlog.LogError(errors.Wrapf(err, "error %v", action))
}
}
}
// 2. Get the list of namespaces and apply the regex filter on the namespace
nsfilter := fmt.Sprintf("%s|%s", cfg.Filters.Namespaces, cfg.Namespace)
logrus.Infof("Filtering namespaces based on the following regex:%s", nsfilter)
nslist, err := FilterNamespaces(kubeClient, nsfilter)
if err != nil {
errlog.LogError(errors.Wrap(err, "could not filter namespaces"))
return errCount + 1
}
// 3. Dump the config.json we used to run our test
if blob, err := json.Marshal(cfg); err == nil {
if err = ioutil.WriteFile(path.Join(metapath, "config.json"), blob, 0644); err != nil {
errlog.LogError(errors.Wrap(err, "could not write config.json file"))
return errCount + 1
}
}
// 4. Run the plugin aggregator
trackErrorsFor("running plugins")(
pluginaggregation.Run(kubeClient, cfg.LoadedPlugins, cfg.Aggregation, cfg.Namespace, outpath),
)
// 5. Run the queries
recorder := NewQueryRecorder()
trackErrorsFor("querying cluster resources")(
QueryClusterResources(kubeClient, crdClient, recorder, cfg),
)
for _, ns := range nslist {
trackErrorsFor("querying resources under namespace " + ns)(
QueryNSResources(kubeClient, recorder, ns, cfg),
)
}
// 6. Dump the query times
trackErrorsFor("recording query times")(
recorder.DumpQueryData(path.Join(metapath, "query-time.json")),
)
// 7. Clean up after the plugins
pluginaggregation.Cleanup(kubeClient, cfg.LoadedPlugins)
// 8. tarball up results YYYYMMDDHHMM_sonobuoy_UID.tar.gz
tb := cfg.ResultsDir + "/" + t.Format("200601021504") + "_sonobuoy_" + cfg.UUID + ".tar.gz"
err = tarx.Compress(tb, outpath, &tarx.CompressOptions{Compression: tarx.Gzip})
if err == nil {
defer os.RemoveAll(outpath)
}
trackErrorsFor("assembling results tarball")(err)
// 9. Mark final annotation stating the results are available and status is completed.
trackErrorsFor("updating pod status")(
updateStatus(kubeClient, cfg.Namespace, pluginaggregation.CompleteStatus),
)
logrus.Infof("Results available at %v", tb)
return errCount
}
// updateStatus changes the summary status of the sonobuoy pod in order to
// effect the finalized status the user sees. This does not change the status
// of individual plugins.
func updateStatus(client kubernetes.Interface, namespace string, status string) error {
podStatus, err := pluginaggregation.GetStatus(client, namespace)
if err != nil {
return errors.Wrap(err, "failed to get the existing status")
}
// Update status
podStatus.Status = status
// Marshal back into json, inject into the patch, then serialize again.
statusBytes, err := json.Marshal(podStatus)
if err != nil {
return errors.Wrap(err, "failed to marshal the status")
}
patch := pluginaggregation.GetPatch(string(statusBytes))
patchBytes, err := json.Marshal(patch)
if err != nil {
return errors.Wrap(err, "failed to marshal the patch")
}
_, err = client.CoreV1().Pods(namespace).Patch(pluginaggregation.StatusPodName, types.MergePatchType, patchBytes)
return err
}