-
Notifications
You must be signed in to change notification settings - Fork 315
/
command.go
349 lines (290 loc) · 8.72 KB
/
command.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
339
340
341
342
343
344
345
346
347
348
349
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package loglevel
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"github.com/posener/complete"
helmCLI "helm.sh/helm/v3/pkg/cli"
"k8s.io/apimachinery/pkg/api/validation"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"github.com/hashicorp/consul-k8s/cli/common"
"github.com/hashicorp/consul-k8s/cli/common/envoy"
"github.com/hashicorp/consul-k8s/cli/common/flag"
"github.com/hashicorp/consul-k8s/cli/common/terminal"
)
const (
defaultAdminPort = 19000
flagNameNamespace = "namespace"
flagNameUpdateLevel = "update-level"
flagNameReset = "reset"
flagNameKubeConfig = "kubeconfig"
flagNameKubeContext = "context"
)
var ErrIncorrectArgFormat = errors.New("Exactly one positional argument is required: <pod-name>")
type LoggerConfig map[string]string
var levelToColor = map[string]string{
"trace": terminal.Green,
"debug": terminal.HiWhite,
"info": terminal.Blue,
"warning": terminal.Yellow,
"error": terminal.Red,
"critical": terminal.Magenta,
"off": "",
}
type LogLevelCommand struct {
*common.BaseCommand
kubernetes kubernetes.Interface
set *flag.Sets
// Command Flags
podName string
namespace string
level string
reset bool
kubeConfig string
kubeContext string
once sync.Once
help string
restConfig *rest.Config
envoyLoggingCaller func(context.Context, common.PortForwarder, *envoy.LoggerParams) (map[string]string, error)
}
func (l *LogLevelCommand) init() {
l.Log.ResetNamed("loglevel")
l.set = flag.NewSets()
f := l.set.NewSet("Command Options")
f.StringVar(&flag.StringVar{
Name: flagNameNamespace,
Target: &l.namespace,
Usage: "The namespace where the target Pod can be found.",
Aliases: []string{"n"},
})
f.StringVar(&flag.StringVar{
Name: flagNameUpdateLevel,
Target: &l.level,
Usage: "Update the level for the logger. Can be either `-update-level warning` to change all loggers to warning, or a comma delineated list of loggers with level can be passed like `-update-level grpc:warning,http:info` to only modify specific loggers.",
Aliases: []string{"u"},
})
f.BoolVar(&flag.BoolVar{
Name: flagNameReset,
Target: &l.reset,
Usage: "Reset the log level for all loggers in a pod to the Envoy default (info).",
Aliases: []string{"r"},
})
f = l.set.NewSet("Global Options")
f.StringVar(&flag.StringVar{
Name: flagNameKubeConfig,
Aliases: []string{"c"},
Target: &l.kubeConfig,
Usage: "Set the path to kubeconfig file.",
})
f.StringVar(&flag.StringVar{
Name: flagNameKubeContext,
Target: &l.kubeContext,
Usage: "Set the Kubernetes context to use.",
})
l.help = l.set.Help()
}
func (l *LogLevelCommand) Run(args []string) int {
l.once.Do(l.init)
defer common.CloseWithError(l.BaseCommand)
err := l.parseFlags(args)
if err != nil {
return l.logOutputAndDie(err)
}
err = l.validateFlags()
if err != nil {
return l.logOutputAndDie(err)
}
// if we're resetting the default log level for envoy is info: https://www.envoyproxy.io/docs/envoy/latest/start/quick-start/run-envoy#debugging-envoy
if l.reset {
l.level = "info"
}
if l.envoyLoggingCaller == nil {
l.envoyLoggingCaller = envoy.CallLoggingEndpoint
}
err = l.initKubernetes()
if err != nil {
return l.logOutputAndDie(err)
}
adminPorts, err := l.fetchAdminPorts()
if err != nil {
return l.logOutputAndDie(err)
}
err = l.fetchOrSetLogLevels(adminPorts)
if err != nil {
return l.logOutputAndDie(err)
}
return 0
}
func (l *LogLevelCommand) parseFlags(args []string) error {
if len(args) == 0 {
return ErrIncorrectArgFormat
}
positional := []string{}
// Separate positional args from keyed args
for _, arg := range args {
if strings.HasPrefix(arg, "-") {
break
}
positional = append(positional, arg)
}
keyed := args[len(positional):]
if len(positional) != 1 {
return ErrIncorrectArgFormat
}
l.podName = positional[0]
err := l.set.Parse(keyed)
if err != nil {
return err
}
return nil
}
func (l *LogLevelCommand) validateFlags() error {
if l.level != "" && l.reset {
return fmt.Errorf("cannot set log level to %q and reset to 'info' at the same time", l.level)
}
if l.namespace == "" {
return nil
}
errs := validation.ValidateNamespaceName(l.namespace, false)
if len(errs) > 0 {
return fmt.Errorf("invalid namespace name passed for -namespace/-n: %v", strings.Join(errs, "; "))
}
return nil
}
func (l *LogLevelCommand) initKubernetes() error {
settings := helmCLI.New()
var err error
if l.kubeConfig != "" {
settings.KubeConfig = l.kubeConfig
}
if l.kubeContext != "" {
settings.KubeContext = l.kubeContext
}
if l.restConfig == nil {
l.restConfig, err = settings.RESTClientGetter().ToRESTConfig()
if err != nil {
return fmt.Errorf("error creating Kubernetes REST config %v", err)
}
}
if l.kubernetes == nil {
l.kubernetes, err = kubernetes.NewForConfig(l.restConfig)
if err != nil {
return fmt.Errorf("error creating Kubernetes client %v", err)
}
}
if l.namespace == "" {
l.namespace = settings.Namespace()
}
return nil
}
// fetchAdminPorts retrieves all admin ports for Envoy Proxies running in a pod given namespace.
func (l *LogLevelCommand) fetchAdminPorts() (map[string]int, error) {
adminPorts := make(map[string]int, 0)
pod, err := l.kubernetes.CoreV1().Pods(l.namespace).Get(l.Ctx, l.podName, metav1.GetOptions{})
if err != nil {
return adminPorts, err
}
connectService, isMultiport := pod.Annotations["consul.hashicorp.com/connect-service"]
if !isMultiport {
// Return the default port configuration.
adminPorts[l.podName] = defaultAdminPort
return adminPorts, nil
}
for idx, svc := range strings.Split(connectService, ",") {
adminPorts[svc] = defaultAdminPort + idx
}
return adminPorts, nil
}
func (l *LogLevelCommand) fetchOrSetLogLevels(adminPorts map[string]int) error {
loggers := make(map[string]LoggerConfig, 0)
for name, port := range adminPorts {
pf := common.PortForward{
Namespace: l.namespace,
PodName: l.podName,
RemotePort: port,
KubeClient: l.kubernetes,
RestConfig: l.restConfig,
}
params, err := parseParams(l.level)
if err != nil {
return err
}
logLevels, err := l.envoyLoggingCaller(l.Ctx, &pf, params)
if err != nil {
return err
}
loggers[name] = logLevels
}
l.outputLevels(loggers)
return nil
}
func parseParams(params string) (*envoy.LoggerParams, error) {
loggerParams := envoy.NewLoggerParams()
if len(params) == 0 {
return loggerParams, nil
}
// contains global log level change
if !strings.Contains(params, ":") {
err := loggerParams.SetGlobalLoggerLevel(params)
if err != nil {
return nil, err
}
return loggerParams, nil
}
// contains changes to at least 1 specific log level
loggerChanges := strings.Split(params, ",")
for _, logger := range loggerChanges {
levelValues := strings.Split(logger, ":")
err := loggerParams.SetLoggerLevel(levelValues[0], levelValues[1])
if err != nil {
return nil, err
}
}
return loggerParams, nil
}
func (l *LogLevelCommand) outputLevels(logLevels map[string]LoggerConfig) {
l.UI.Output(fmt.Sprintf("Envoy log configuration for %s in namespace default:", l.podName))
for n, levels := range logLevels {
l.UI.Output(fmt.Sprintf("Log Levels for %s", n), terminal.WithHeaderStyle())
table := terminal.NewTable("Name", "Level")
for name, level := range levels {
table.AddRow([]string{name, level}, []string{"", levelToColor[level]})
}
l.UI.Table(table)
l.UI.Output("")
}
}
func (l *LogLevelCommand) Help() string {
l.once.Do(l.init)
return fmt.Sprintf("%s\n\nUsage: consul-k8s proxy log <pod-name> [flags]\n\n%s", l.Synopsis(), l.help)
}
func (l *LogLevelCommand) Synopsis() string {
return "Inspect and Modify the Envoy Log configuration for a given Pod."
}
// AutocompleteFlags returns a mapping of supported flags and autocomplete
// options for this command. The map key for the Flags map should be the
// complete flag such as "-foo" or "--foo".
func (l *LogLevelCommand) AutocompleteFlags() complete.Flags {
return complete.Flags{
fmt.Sprintf("-%s", flagNameNamespace): complete.PredictNothing,
fmt.Sprintf("-%s", flagNameKubeConfig): complete.PredictFiles("*"),
fmt.Sprintf("-%s", flagNameKubeContext): complete.PredictNothing,
}
}
// AutocompleteArgs returns the argument predictor for this command.
// Since argument completion is not supported, this will return
// complete.PredictNothing.
func (l *LogLevelCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictNothing
}
func (l *LogLevelCommand) logOutputAndDie(err error) int {
l.UI.Output(err.Error(), terminal.WithErrorStyle())
l.UI.Output(fmt.Sprintf("\n%s", l.Help()))
return 1
}