-
Notifications
You must be signed in to change notification settings - Fork 88
/
supportbundle.go
338 lines (283 loc) · 9.82 KB
/
supportbundle.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
package supportbundle
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/mholt/archiver"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/kotskinds/client/kotsclientset/scheme"
"github.com/replicatedhq/kots/pkg/kotsutil"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/redact"
"github.com/replicatedhq/kots/pkg/render/helper"
"github.com/replicatedhq/kots/pkg/store"
"github.com/replicatedhq/kots/pkg/supportbundle/types"
troubleshootanalyze "github.com/replicatedhq/troubleshoot/pkg/analyze"
troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2"
"github.com/replicatedhq/troubleshoot/pkg/convert"
"github.com/segmentio/ksuid"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sjson "k8s.io/apimachinery/pkg/runtime/serializer/json"
)
const (
SpecDataKey = "support-bundle-spec"
)
// Collect will queue collection of a new support bundle.
// It returns the ID of the support bundle so that the status can be queried by the
// front end.
func Collect(appID string, clusterID string) (string, error) {
supportBundle, err := createSupportBundleDependencies(appID, clusterID)
if err != nil {
return "", errors.Wrap(err, "could not generate support bundle dependencies")
}
supportBundle.ID = strings.ToLower(ksuid.New().String())
supportBundle.Slug = supportBundle.ID
store.GetStore().CreateInProgressSupportBundle(supportBundle)
progressChan := executeUpdateRoutine(supportBundle)
executeSupportBundleCollectRoutine(supportBundle, progressChan)
return supportBundle.ID, nil
}
// CreateBundle will create a support bundle in the store, attempting to use the
// requestedID. This function uploads the archive and creates the record.
func CreateBundle(requestedID string, appID string, archivePath string) (*types.SupportBundle, error) {
id := ksuid.New().String()
if requestedID != "" {
id = requestedID
}
fileTree, err := archiveToFileTree(archivePath)
if err != nil {
return nil, errors.Wrap(err, "failed to generate file tree")
}
marshalledTree, err := json.Marshal(fileTree.Nodes)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal tree index")
}
return store.GetStore().CreateSupportBundle(id, appID, archivePath, marshalledTree)
}
// GetFilesContents will return the file contents for filenames matching the filenames
// parameter.
func GetFilesContents(bundleID string, filenames []string) (map[string][]byte, error) {
bundleArchive, err := store.GetStore().GetSupportBundleArchive(bundleID)
if err != nil {
return nil, errors.Wrap(err, "failed to get bundle")
}
defer os.RemoveAll(bundleArchive)
bundleDir, err := ioutil.TempDir("", "kots")
if err != nil {
return nil, errors.Wrap(err, "failed to create tmp dir")
}
defer os.RemoveAll(bundleDir)
tarGz := archiver.TarGz{
Tar: &archiver.Tar{
ImplicitTopLevelFolder: false,
},
}
if err := tarGz.Unarchive(bundleArchive, bundleDir); err != nil {
return nil, errors.Wrap(err, "failed to unarchive")
}
files := map[string][]byte{}
err = filepath.Walk(bundleDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if len(path) <= len(bundleDir) {
return nil
}
if info.IsDir() {
return nil
}
// the following tries to find the actual file path of the desired files in the support bundle
// this is needed to handle old and new support bundle formats
// where old support bundles don't include a top level subdirectory and the new ones do
// this basically compares file paths after trimming the subdirectory path from both (if exists)
relPath, err := filepath.Rel(bundleDir, path)
if err != nil {
return errors.Wrap(err, "failed to get relative path")
}
trimmedRelPath := SupportBundleNameRegex.ReplaceAllString(relPath, "")
trimmedRelPath = strings.TrimPrefix(trimmedRelPath, string(os.PathSeparator))
if trimmedRelPath == "" {
return nil
}
for _, filename := range filenames {
trimmedFileName := SupportBundleNameRegex.ReplaceAllString(filename, "")
trimmedFileName = strings.TrimPrefix(trimmedFileName, string(os.PathSeparator))
if trimmedFileName == "" {
continue
}
if trimmedRelPath == trimmedFileName {
content, err := ioutil.ReadFile(path)
if err != nil {
return errors.Wrap(err, "failed to read file")
}
files[filename] = content
return nil
}
}
return nil
})
if err != nil {
return nil, errors.Wrap(err, "failed to walk")
}
return files, nil
}
func GetSpecSecretName(appSlug string) string {
return fmt.Sprintf("kotsadm-%s-supportbundle", appSlug)
}
func GetSpecURI(appSlug string) string {
return fmt.Sprintf("secret/%s/%s", os.Getenv("POD_NAMESPACE"), GetSpecSecretName(appSlug))
}
func GetBundleCommand(appSlug string) []string {
redactURIs := []string{redact.GetKotsadmRedactSpecURI(), redact.GetAppRedactSpecURI(appSlug)}
redactors := strings.Join(redactURIs, ",")
command := []string{
"curl https://krew.sh/support-bundle | bash",
fmt.Sprintf("kubectl support-bundle %s --redactors=%s\n", GetSpecURI(appSlug), redactors),
}
return command
}
// createSupportBundleDependencies generates k8s secrets for the support bundle spec and redactors.
// These resources will be used when executing a support bundle collection
func createSupportBundleDependencies(appID string, clusterID string) (*types.SupportBundle, error) {
a, err := store.GetStore().GetApp(appID)
if err != nil {
return nil, errors.Wrapf(err, "failed to get app %s", appID)
}
sequence := int64(0)
currentVersion, err := store.GetStore().GetCurrentVersion(a.ID, clusterID)
if err != nil {
return nil, errors.Wrap(err, "failed to get current downstream version")
}
if currentVersion != nil {
sequence = currentVersion.Sequence
}
archivePath, err := ioutil.TempDir("", "kotsadm")
if err != nil {
return nil, errors.Wrap(err, "failed to create temp dir")
}
defer os.RemoveAll(archivePath)
err = store.GetStore().GetAppVersionArchive(a.ID, sequence, archivePath)
if err != nil {
return nil, errors.Wrap(err, "failed to get current archive")
}
kotsKinds, err := kotsutil.LoadKotsKindsFromPath(archivePath)
if err != nil {
return nil, errors.Wrap(err, "failed to load current kotskinds")
}
defaultOpts := DefaultTroubleshootOpts{
DisableUpload: true,
}
supportBundle, err := CreateRenderedSpec(a.ID, sequence, kotsKinds, defaultOpts)
if err != nil {
return nil, errors.Wrap(err, "failed to create rendered support bundle spec")
}
err = redact.GenerateKotsadmRedactSpec()
if err != nil {
return nil, errors.Wrap(err, "failed to write kotsadm redact spec configmap")
}
redactURIs := []string{redact.GetKotsadmRedactSpecURI()}
err = redact.CreateRenderedAppRedactSpec(a.ID, sequence, kotsKinds)
if err != nil {
return nil, errors.Wrap(err, "failed to write app redact spec configmap")
}
redactURIs = append(redactURIs, redact.GetAppRedactSpecURI(a.Slug))
supportBundleObj := types.SupportBundle{
AppID: appID,
URI: GetSpecURI(a.Slug),
RedactURIs: redactURIs,
Progress: types.SupportBundleProgress{
CollectorCount: len(supportBundle.Spec.Collectors),
},
}
return &supportBundleObj, nil
}
// CreateSupportBundleAnalysis takes a support bundle, unpacks to analyze then adds the analysis to
// the support bundle secret
func CreateSupportBundleAnalysis(appID string, archivePath string, bundle *types.SupportBundle) error {
// we need the app archive to get the analyzers
foundApp, err := store.GetStore().GetApp(appID)
if err != nil {
err = errors.Wrap(err, "failed to get app")
logger.Error(err)
return err
}
archiveDir, err := ioutil.TempDir("", "kotsadm")
if err != nil {
err = errors.Wrap(err, "failed to create temp dir")
logger.Error(err)
return err
}
defer os.RemoveAll(archiveDir)
err = store.GetStore().GetAppVersionArchive(foundApp.ID, foundApp.CurrentSequence, archiveDir)
if err != nil {
err = errors.Wrap(err, "failed to get app version archive")
logger.Error(err)
return err
}
kotsKinds, err := kotsutil.LoadKotsKindsFromPath(archiveDir)
if err != nil {
err = errors.Wrap(err, "failed to load kots kinds from archive")
logger.Error(err)
return err
}
analyzer := kotsKinds.Analyzer
// SupportBundle overwrites Analyzer if defined
if kotsKinds.SupportBundle != nil {
analyzer = kotsutil.SupportBundleToAnalyzer(kotsKinds.SupportBundle)
}
if analyzer == nil {
analyzer = &troubleshootv1beta2.Analyzer{
TypeMeta: metav1.TypeMeta{
APIVersion: "troubleshoot.sh/v1beta2",
Kind: "Analyzer",
},
ObjectMeta: metav1.ObjectMeta{
Name: "default-analyzers",
},
Spec: troubleshootv1beta2.AnalyzerSpec{
Analyzers: []*troubleshootv1beta2.Analyze{},
},
}
}
if err := InjectDefaultAnalyzers(analyzer); err != nil {
err = errors.Wrap(err, "failed to inject analyzers")
logger.Error(err)
return err
}
s := k8sjson.NewYAMLSerializer(k8sjson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
var b bytes.Buffer
if err := s.Encode(analyzer, &b); err != nil {
err = errors.Wrap(err, "failed to encode analyzers")
logger.Error(err)
return err
}
renderedAnalyzers, err := helper.RenderAppFile(foundApp, nil, b.Bytes(), kotsKinds, os.Getenv("POD_NAMESPACE"))
if err != nil {
err = errors.Wrap(err, "failed to render analyzers")
logger.Error(err)
return err
}
analyzeResult, err := troubleshootanalyze.DownloadAndAnalyze(archivePath, string(renderedAnalyzers))
if err != nil {
err = errors.Wrap(err, "failed to analyze")
logger.Error(err)
return err
}
data := convert.FromAnalyzerResult(analyzeResult)
insights, err := json.MarshalIndent(data, "", " ")
if err != nil {
err = errors.Wrap(err, "failed to marshal result")
logger.Error(err)
return err
}
if err := store.GetStore().SetSupportBundleAnalysis(bundle.ID, insights); err != nil {
err = errors.Wrap(err, "failed to save result")
logger.Error(err)
return err
}
return nil
}