-
Notifications
You must be signed in to change notification settings - Fork 87
/
supportbundle.go
320 lines (270 loc) · 9.89 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
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"
"github.com/replicatedhq/kots/pkg/util"
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) {
sequence := int64(0)
currentVersion, err := store.GetStore().GetCurrentVersion(appID, clusterID)
if err != nil {
return "", errors.Wrap(err, "failed to get current downstream version")
}
if currentVersion != nil {
sequence = currentVersion.Sequence
}
opts := types.TroubleshootOptions{
DisableUpload: true,
}
supportBundle, err := CreateSupportBundleDependencies(appID, sequence, opts)
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)
}
func GetSpecSecretName(appSlug string) string {
return fmt.Sprintf("kotsadm-%s-supportbundle", appSlug)
}
func GetSpecURI(appSlug string) string {
return fmt.Sprintf("secret/%s/%s", util.PodNamespace, 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 and configmaps for the support bundle spec and redactors.
// These resources will be used when executing a support bundle collection
func CreateSupportBundleDependencies(appID string, sequence int64, opts types.TroubleshootOptions) (*types.SupportBundle, error) {
a, err := store.GetStore().GetApp(appID)
if err != nil {
return nil, errors.Wrapf(err, "failed to get app %s", appID)
}
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")
}
supportBundle, err := CreateRenderedSpec(a.ID, sequence, kotsKinds, opts)
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
}
func getAnalysisFromBundle(archivePath string) ([]byte, error) {
bundleDir, err := ioutil.TempDir("", "kots")
if err != nil {
return nil, errors.Wrap(err, "failed to create temp dir")
}
defer os.RemoveAll(bundleDir)
tarGz := archiver.TarGz{
Tar: &archiver.Tar{
ImplicitTopLevelFolder: false,
},
}
if err := tarGz.Unarchive(archivePath, bundleDir); err != nil {
return nil, errors.Wrap(err, "failed to unarchive")
}
var analysis []byte
err = filepath.Walk(bundleDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
// trim the directory and subdirectory from the path
// for example: "support-bundle-2021-09-10T18_50_35/support-bundle-2021-09-10T18_50_35/analysis.json"
relPath, err := filepath.Rel(bundleDir, path) // becomes: "support-bundle-2021-09-10T18_50_35/analysis.json"
if err != nil {
return errors.Wrap(err, "failed to get relative path")
}
trimmedRelPath := SupportBundleNameRegex.ReplaceAllString(relPath, "") // becomes: "analysis.json"
trimmedRelPath = strings.TrimPrefix(trimmedRelPath, string(os.PathSeparator)) // extra measure to ensure no leading slashes. for example: "/analysis.json"
if trimmedRelPath == "analysis.json" {
b, err := ioutil.ReadFile(path)
if err != nil {
return errors.Wrap(err, "failed to read analysis file")
}
analysis = b
}
return nil
})
if err != nil {
return nil, errors.Wrap(err, "failed to walk")
}
return analysis, nil
}
// CreateSupportBundleAnalysis adds the analysis to the support bundle secret.
// if the support bundle archive already includes analysis, the secret will be updated with that. (which is the case for new support bundles)
// if not, the support bundle archive will be unpacked and analyzed and then the secret will be updated with the results. (which is the case for older support bundles formats)
func CreateSupportBundleAnalysis(appID string, archivePath string, bundle *types.SupportBundle) error {
analysis, err := getAnalysisFromBundle(archivePath)
if err != nil {
return errors.Wrap(err, "failed to check if support bundle includes analysis")
}
if len(analysis) > 0 {
// new support bundles include the analysis as part of the bundle
if err := store.GetStore().SetSupportBundleAnalysis(bundle.ID, analysis); err != nil {
return errors.Wrap(err, "failed to set support bundle analysis")
}
return nil
}
// 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{},
},
}
}
analyzer.Spec.Analyzers = append(analyzer.Spec.Analyzers, getDefaultAnalyzers()...)
analyzer.Spec.Analyzers = append(analyzer.Spec.Analyzers, getDefaultDynamicAnalyzers(foundApp)...)
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, util.PodNamespace)
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
}