-
Notifications
You must be signed in to change notification settings - Fork 26
/
app.go
297 lines (268 loc) · 9.2 KB
/
app.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
// Copyright 2022 Google LLC
//
// 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
//
// https://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 app implements application management features
package app
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"reflect"
"github.com/fatih/color"
cfg "github.com/google/gke-policy-automation/internal/config"
"github.com/google/gke-policy-automation/internal/gke"
"github.com/google/gke-policy-automation/internal/inputs"
"github.com/google/gke-policy-automation/internal/log"
"github.com/google/gke-policy-automation/internal/outputs"
"github.com/google/gke-policy-automation/internal/policy"
"github.com/google/gke-policy-automation/internal/version"
)
const (
regoPackageBaseBestPractices = "gke.policy"
regoPackageBaseScalability = "gke.scalability"
)
var errNoPolicies = errors.New("no policies to check against")
var consoleInfoColorF = color.New(color.Bold, color.FgHiWhite).Sprintf
var consoleWarnColorF = color.New(color.Bold, color.FgHiYellow).Sprintf
type PolicyAutomation interface {
LoadCliConfig(cliConfig *CliConfig, defaultsFn setConfigDefaults, validateFn validateConfig) error
Close() error
Check() error
CheckBestPractices() error
CheckScalability() error
ClusterJSONData() error
Version() error
PolicyCheck() error
PolicyGenerateDocumentation() error
ConfigureSCC(orgNumber string) error
}
type evaluationResults struct {
m map[string]*policy.PolicyEvaluationResult
}
func (r *evaluationResults) Add(result *policy.PolicyEvaluationResult) *evaluationResults {
if r.m == nil {
r.m = make(map[string]*policy.PolicyEvaluationResult)
}
currentResult, ok := r.m[result.ClusterID]
if !ok {
r.m[result.ClusterID] = result
return r
}
currentResult.Policies = append(currentResult.Policies, result.Policies...)
return r
}
func (r *evaluationResults) List() []*policy.PolicyEvaluationResult {
values := make([]*policy.PolicyEvaluationResult, 0, len(r.m))
for _, value := range r.m {
values = append(values, value)
}
return values
}
type PolicyAutomationApp struct {
ctx context.Context
config *cfg.Config
out *outputs.Output
inputs []inputs.Input
collectors []outputs.ValidationResultCollector
clusterDumpCollectors []outputs.ClusterDumpCollector
discovery gke.DiscoveryClient
policyDocsFile string
}
func NewPolicyAutomationApp() PolicyAutomation {
out := outputs.NewSilentOutput()
return &PolicyAutomationApp{
ctx: context.Background(),
config: &cfg.Config{},
out: out,
collectors: []outputs.ValidationResultCollector{outputs.NewConsoleResultCollector(out)},
}
}
func (p *PolicyAutomationApp) Close() error {
errors := make([]error, 0)
for _, i := range p.inputs {
if err := i.Close(); err != nil {
log.Warnf("error when closing input %s: %s", i.GetID(), err)
errors = append(errors, err)
}
}
if p.discovery != nil {
if err := p.discovery.Close(); err != nil {
log.Warnf("error when closing discovery client: %s", err)
errors = append(errors, err)
}
}
if len(errors) > 0 {
return errors[0]
}
return nil
}
func (p *PolicyAutomationApp) Check() error {
return p.evaluateClusters([]string{regoPackageBaseBestPractices})
}
func (p *PolicyAutomationApp) CheckBestPractices() error {
return p.evaluateClusters([]string{regoPackageBaseBestPractices})
}
func (p *PolicyAutomationApp) CheckScalability() error {
p.out.Printf("%s %s\n",
outputs.IconInfo,
consoleWarnColorF("Running scalability check requires metrics from kube-state-metrics!"),
)
docsTitle := fmt.Sprintf("%s \x1b]8;;%s\x07%s\x1b]8;;\x07", outputs.IconHyperlink, "https://github.com/google/gke-policy-automation/blob/scalability-docs/docs/user-guide.md#checking-scalability-limits", "documentation")
p.out.Printf("%s %s\n",
outputs.IconInfo,
consoleWarnColorF("Check the %s for more details", docsTitle),
)
return p.evaluateClusters([]string{regoPackageBaseScalability})
}
func (p *PolicyAutomationApp) ClusterJSONData() error {
clusterIds, err := p.getClusters()
if err != nil {
p.out.ErrorPrint("could not get clusters", err)
log.Errorf("could not get clusters: %s", err)
}
//for dumping JSON data - create gkeInput
var gkeInput inputs.Input
if p.config.CredentialsFile != "" {
gkeInput, err = inputs.NewGKEApiInputWithCredentials(p.ctx, p.config.CredentialsFile)
if err != nil {
return err
}
} else {
gkeInput, err = inputs.NewGKEApiInput(p.ctx)
if err != nil {
return err
}
}
p.inputs = append(p.inputs, gkeInput)
clusterData, errors := inputs.GetAllInputsData(p.inputs, clusterIds)
if len(errors) > 0 {
p.out.ErrorPrint("could not fetch the cluster details", errors[0])
log.Errorf("could not fetch cluster details: %s", errors[0])
return errors[0]
}
val, err := json.MarshalIndent(clusterData, "", " ")
log.Debugf("[DEBUG] cluster: " + string(val))
for _, cluster := range clusterData {
if err != nil {
p.out.ErrorPrint("could not fetch the cluster details", err)
log.Errorf("could not fetch cluster details: %s", err)
return err
}
val, err := json.MarshalIndent(cluster, "", " ")
if err != nil {
log.Debugf("could not format cluster details: %s", err)
}
log.Debugf("cluster: " + string(val))
for _, dumpCollector := range p.clusterDumpCollectors {
log.Debugf("registering cluster data with cluster dump collector %s", reflect.TypeOf(dumpCollector).String())
dumpCollector.RegisterCluster(cluster)
}
}
for _, dumpCollector := range p.clusterDumpCollectors {
colType := reflect.TypeOf(dumpCollector).String()
log.Debugf("closing cluster dump collector %s", colType)
p.out.Printf("%s %s\n",
outputs.IconInfo,
consoleInfoColorF("Closing cluster dump collector ..."),
)
if err := dumpCollector.Close(); err != nil {
log.Errorf("failed to close cluster dump collector %s due to %s", colType, err)
return err
}
}
return nil
}
func (p *PolicyAutomationApp) Version() error {
p.out.Printf("%s\n", version.Version)
return nil
}
func (p *PolicyAutomationApp) PolicyCheck() error {
files, err := p.loadPolicyFiles()
if err != nil {
p.out.ErrorPrint("loading policy files failed: ", err)
log.Errorf("loading policy files failed: %s", err)
return err
}
pa := policy.NewPolicyAgent(p.ctx)
if err := pa.WithFiles(files, p.config.PolicyExclusions); err != nil {
p.out.ErrorPrint("could not parse policy files", err)
log.Errorf("could not parse policy files: %s", err)
return err
}
correctF := color.New(color.Bold, color.FgHiGreen).Sprint
p.out.Printf("%s\n", correctF("All policies validated correctly"))
log.Info("All policies validated correctly")
return nil
}
func (p *PolicyAutomationApp) PolicyGenerateDocumentation() error {
w, err := os.OpenFile(p.policyDocsFile, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
p.out.ErrorPrint("could not open output file for writing: ", err)
log.Errorf("could not open output file for writing: %s", err)
return err
}
defer w.Close()
files, err := p.loadPolicyFiles()
if err != nil {
p.out.ErrorPrint("loading policy files failed: ", err)
log.Errorf("loading policy files failed: %s", err)
return err
}
pa := policy.NewPolicyAgent(p.ctx)
if err := pa.WithFiles(files, p.config.PolicyExclusions); err != nil {
p.out.ErrorPrint("could not parse policy files", err)
log.Errorf("could not parse policy files: %s", err)
return err
}
documentationGenerator := outputs.NewMarkdownPolicyDocumentation(pa.GetPolicies())
p.out.Printf("%s %s\n",
outputs.IconInfo,
consoleInfoColorF("Writing policy documentation ... [%s]", p.policyDocsFile),
)
log.Infof("Writing policy documentation to file %s", p.policyDocsFile)
if _, err := w.Write([]byte(documentationGenerator.GenerateDocumentation())); err != nil {
p.out.ErrorPrint("could not write documentation file", err)
log.Errorf("could not write documentation file: %s", err)
return err
}
return nil
}
func (p *PolicyAutomationApp) loadPolicyFiles() ([]*policy.PolicyFile, error) {
policyFiles := make([]*policy.PolicyFile, 0)
for _, policyConfig := range p.config.Policies {
var policySrc policy.PolicySource
if policyConfig.LocalDirectory != "" {
policySrc = policy.NewLocalPolicySource(policyConfig.LocalDirectory)
}
if policyConfig.GitRepository != "" {
policySrc = policy.NewGitPolicySource(policyConfig.GitRepository,
policyConfig.GitBranch,
policyConfig.GitDirectory)
}
p.out.Printf("%s %s\n",
outputs.IconInfo,
consoleInfoColorF("Reading policy files... [%s]", policySrc),
)
log.Infof("Reading policy files from %s", policySrc)
files, err := policySrc.GetPolicyFiles()
if err != nil {
p.out.ErrorPrint("could not read policy files", err)
log.Errorf("could not read policy files: %s", err)
return nil, err
}
policyFiles = append(policyFiles, files...)
}
return policyFiles, nil
}