blob: 3bb779858782f0a37b969491c73b0c3d0966bdb6 [file] [log] [blame]
Scott Bakerd69e4222019-08-21 16:46:05 -07001/*
2 * Copyright 2019-present Ciena Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package commands
17
18import (
19 "context"
20 "fmt"
21 "github.com/fullstorydev/grpcurl"
22 flags "github.com/jessevdk/go-flags"
23 "github.com/jhump/protoreflect/dynamic"
24 "github.com/opencord/voltctl/pkg/format"
25 "github.com/opencord/voltctl/pkg/model"
26 "google.golang.org/grpc"
27 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28 "k8s.io/client-go/kubernetes"
29 "k8s.io/client-go/tools/clientcmd"
Scott Bakerd69e4222019-08-21 16:46:05 -070030 "strings"
31)
32
33type SetLogLevelOutput struct {
34 ComponentName string
35 Status string
36 Error string
37}
38
39type SetLogLevelOpts struct {
40 OutputOptions
41 Package string `short:"p" long:"package" description:"Package name to set filter level"`
42 Args struct {
43 Level string
44 Component []string
45 } `positional-args:"yes" required:"yes"`
46}
47
48type GetLogLevelsOpts struct {
49 ListOutputOptions
50 Args struct {
51 Component []string
52 } `positional-args:"yes" required:"yes"`
53}
54
55type ListLogLevelsOpts struct {
56 ListOutputOptions
57}
58
59type LogLevelOpts struct {
60 SetLogLevel SetLogLevelOpts `command:"set"`
61 GetLogLevels GetLogLevelsOpts `command:"get"`
62 ListLogLevels ListLogLevelsOpts `command:"list"`
63}
64
65var logLevelOpts = LogLevelOpts{}
66
67const (
68 DEFAULT_LOGLEVELS_FORMAT = "table{{ .ComponentName }}\t{{.PackageName}}\t{{.Level}}"
69 DEFAULT_SETLOGLEVEL_FORMAT = "table{{ .ComponentName }}\t{{.Status}}\t{{.Error}}"
70)
71
72func RegisterLogLevelCommands(parent *flags.Parser) {
73 _, err := parent.AddCommand("loglevel", "loglevel commands", "Get and set log levels", &logLevelOpts)
74 if err != nil {
75 panic(err)
76 }
77}
78
79func MapListAppend(m map[string][]string, name string, item string) {
80 list, okay := m[name]
81 if okay {
82 m[name] = append(list, item)
83 } else {
84 m[name] = []string{item}
85 }
86}
87
88/*
89 * A roundabout way of going of using the LogLevel enum to map from
90 * a string to an integer that we can pass into the dynamic
91 * proto.
92 *
93 * TODO: There's probably an easier way.
94 */
95func LogLevelStringToInt(logLevelString string) (int32, error) {
96 ProcessGlobalOptions() // required for GetMethod()
97
98 /*
99 * Use GetMethod() to get us a descriptor on the proto file we're
100 * interested in.
101 */
102
103 descriptor, _, err := GetMethod("update-log-level")
104 if err != nil {
105 return 0, err
106 }
107
108 /*
109 * Map string LogLevel to enumerated type LogLevel
110 * We have descriptor from above, which is a DescriptorSource
111 * We can use FindSymbol to get at the message
112 */
113
114 loggingSymbol, err := descriptor.FindSymbol("common.LogLevel")
115 if err != nil {
116 return 0, err
117 }
118
119 /*
120 * LoggingSymbol is a Descriptor, but not a MessageDescrptior,
121 * so we can't look at it's fields yet. Go back to the file,
122 * call FindMessage to get the Message, then we can get the
123 * embedded enum.
124 */
125
126 loggingFile := loggingSymbol.GetFile()
127 logLevelMessage := loggingFile.FindMessage("common.LogLevel")
128 logLevelEnumType := logLevelMessage.GetNestedEnumTypes()[0]
129 enumLogLevel := logLevelEnumType.FindValueByName(logLevelString)
130
131 if enumLogLevel == nil {
132 return 0, fmt.Errorf("Unknown log level %s", logLevelString)
133 }
134
135 return enumLogLevel.GetNumber(), nil
136}
137
138// Validate a list of component names and throw an error if any one of them is bad.
139func ValidateComponentNames(kube_to_arouter map[string][]string, names []string) error {
140 var badNames []string
141 for _, name := range names {
142 _, ok := kube_to_arouter[name]
143 if !ok {
144 badNames = append(badNames, name)
145 }
146 }
147
148 if len(badNames) > 0 {
149 return fmt.Errorf("Unknown components: %s", strings.Join(badNames, ","))
150 } else {
151 return nil
152 }
153}
154
155func BuildKubernetesNameMap() (map[string][]string, map[string]string, error) {
156 kube_to_arouter := make(map[string][]string)
157 arouter_to_kube := make(map[string]string)
158
159 // use the current context in kubeconfig
160 config, err := clientcmd.BuildConfigFromFlags("", GlobalOptions.K8sConfig)
161 if err != nil {
162 return nil, nil, err
163 }
164
165 // create the clientset
166 clientset, err := kubernetes.NewForConfig(config)
167 if err != nil {
168 return nil, nil, err
169 }
170
171 pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{
172 LabelSelector: "app.kubernetes.io/part-of=voltha",
173 })
174 if err != nil {
175 return nil, nil, err
176 }
177
178 if len(pods.Items) == 0 {
179 return nil, nil, fmt.Errorf("No Voltha pods found in Kubernetes -- verify pod is setup")
180 }
181
182 for _, pod := range pods.Items {
183 app, ok := pod.Labels["app"]
184 if !ok {
185 continue
186 }
187
188 var arouter_name string
189
190 switch app {
191 case "voltha-api-server":
192 /*
193 * Assumes a single api_server for now.
194 * TODO: Make labeling changes in charts to be able to derive name from labels
195 */
196 arouter_name = "api_server0.api_server01"
197 case "rw-core":
198 affinity_group, ok := pod.Labels["affinity-group"]
199 if !ok {
David Bainbridgea6722342019-10-24 23:55:53 +0000200 Warn.Printf("rwcore %s lacks affinity-group label", pod.Name)
Scott Bakerd69e4222019-08-21 16:46:05 -0700201 continue
202 }
203 affinity_group_core_id, ok := pod.Labels["affinity-group-core-id"]
204 if !ok {
David Bainbridgea6722342019-10-24 23:55:53 +0000205 Warn.Printf("rwcore %s lacks affinity-group-core-id label", pod.Name)
Scott Bakerd69e4222019-08-21 16:46:05 -0700206 continue
207 }
208 arouter_name = "vcore" + affinity_group + ".vcore" + affinity_group + affinity_group_core_id
209 case "ro-core":
210 /*
211 * Assumes a single rocore for now.
212 * TODO: Make labeling changes in charts to be able to derive name from labels
213 */
214 arouter_name = "ro_vcore0.ro_vcore01"
215 default:
216 // skip this pod as it's not relevant
217 continue
218 }
219
220 // Multiple ways to identify the component
221
222 // 1) The pod name. One pod name maps to exactly one pod.
223
224 arouter_to_kube[arouter_name] = pod.Name
225 MapListAppend(kube_to_arouter, pod.Name, arouter_name)
226
227 // 2) The kubernetes component name. A single component (i.e. "core") may map to multiple pods.
228
229 component, ok := pod.Labels["app.kubernetes.io/component"]
230 if ok {
231 MapListAppend(kube_to_arouter, component, arouter_name)
232 }
233
234 // 3) The voltha app label. A single app (i.e. "rwcore") may map to multiple pods.
235
236 MapListAppend(kube_to_arouter, app, arouter_name)
237
238 }
239
240 return kube_to_arouter, arouter_to_kube, nil
241}
242
243func (options *SetLogLevelOpts) Execute(args []string) error {
244 if len(options.Args.Component) == 0 {
245 return fmt.Errorf("Please specify at least one component")
246 }
247
248 kube_to_arouter, arouter_to_kube, err := BuildKubernetesNameMap()
249 if err != nil {
250 return err
251 }
252
253 var output []SetLogLevelOutput
254
255 // Validate component names, throw error now to avoid doing partial work
256 err = ValidateComponentNames(kube_to_arouter, options.Args.Component)
257 if err != nil {
258 return err
259 }
260
261 // Validate and map the logLevel string to an integer, throw error now to avoid doing partial work
262 intLogLevel, err := LogLevelStringToInt(options.Args.Level)
263 if err != nil {
264 return err
265 }
266
267 for _, kubeComponentName := range options.Args.Component {
268 var descriptor grpcurl.DescriptorSource
269 var conn *grpc.ClientConn
270 var method string
271
272 componentNameList := kube_to_arouter[kubeComponentName]
273
274 for _, componentName := range componentNameList {
275 conn, err = NewConnection()
276 if err != nil {
277 return err
278 }
279 defer conn.Close()
280 if strings.HasPrefix(componentName, "api_server") {
281 // apiserver's UpdateLogLevel is in the afrouter.Configuration gRPC package
282 descriptor, method, err = GetMethod("apiserver-update-log-level")
283 } else {
284 descriptor, method, err = GetMethod("update-log-level")
285 }
286 if err != nil {
287 return err
288 }
289
290 ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
291 defer cancel()
292
293 ll := make(map[string]interface{})
294 ll["component_name"] = componentName
295 ll["package_name"] = options.Package
296 ll["level"] = intLogLevel
297
298 h := &RpcEventHandler{
299 Fields: map[string]map[string]interface{}{"common.Logging": ll},
300 }
301 err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, []string{}, h, h.GetParams)
302 if err != nil {
303 return err
304 }
305
306 if h.Status != nil && h.Status.Err() != nil {
307 output = append(output, SetLogLevelOutput{ComponentName: arouter_to_kube[componentName], Status: "Failure", Error: h.Status.Err().Error()})
308 continue
309 }
310
311 output = append(output, SetLogLevelOutput{ComponentName: arouter_to_kube[componentName], Status: "Success"})
312 }
313 }
314
315 outputFormat := CharReplacer.Replace(options.Format)
316 if outputFormat == "" {
David Bainbridgea6722342019-10-24 23:55:53 +0000317 outputFormat = GetCommandOptionWithDefault("loglevel-set", "format", DEFAULT_SETLOGLEVEL_FORMAT)
Scott Bakerd69e4222019-08-21 16:46:05 -0700318 }
319
320 result := CommandResult{
321 Format: format.Format(outputFormat),
322 OutputAs: toOutputType(options.OutputAs),
323 NameLimit: options.NameLimit,
324 Data: output,
325 }
326
327 GenerateOutput(&result)
328 return nil
329}
330
David Bainbridgea6722342019-10-24 23:55:53 +0000331func (options *GetLogLevelsOpts) getLogLevels(methodName string, args []string) error {
Scott Bakerd69e4222019-08-21 16:46:05 -0700332 if len(options.Args.Component) == 0 {
333 return fmt.Errorf("Please specify at least one component")
334 }
335
336 kube_to_arouter, arouter_to_kube, err := BuildKubernetesNameMap()
337 if err != nil {
338 return err
339 }
340
341 var data []model.LogLevel
342
343 // Validate component names, throw error now to avoid doing partial work
344 err = ValidateComponentNames(kube_to_arouter, options.Args.Component)
345 if err != nil {
346 return err
347 }
348
349 for _, kubeComponentName := range options.Args.Component {
350 var descriptor grpcurl.DescriptorSource
351 var conn *grpc.ClientConn
352 var method string
353
354 componentNameList := kube_to_arouter[kubeComponentName]
355
356 for _, componentName := range componentNameList {
357 conn, err = NewConnection()
358 if err != nil {
359 return err
360 }
361 defer conn.Close()
362 if strings.HasPrefix(componentName, "api_server") {
363 // apiserver's UpdateLogLevel is in the afrouter.Configuration gRPC package
364 descriptor, method, err = GetMethod("apiserver-get-log-levels")
365 } else {
366 descriptor, method, err = GetMethod("get-log-levels")
367 }
368 if err != nil {
369 return err
370 }
371
372 ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
373 defer cancel()
374
375 ll := make(map[string]interface{})
376 ll["component_name"] = componentName
377
378 h := &RpcEventHandler{
379 Fields: map[string]map[string]interface{}{"common.LoggingComponent": ll},
380 }
381 err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, []string{}, h, h.GetParams)
382 if err != nil {
383 return err
384 }
385
386 if h.Status != nil && h.Status.Err() != nil {
387 return h.Status.Err()
388 }
389
390 d, err := dynamic.AsDynamicMessage(h.Response)
391 if err != nil {
392 return err
393 }
394 items, err := d.TryGetFieldByName("items")
395 if err != nil {
396 return err
397 }
398
399 for _, item := range items.([]interface{}) {
400 logLevel := model.LogLevel{}
401 logLevel.PopulateFrom(item.(*dynamic.Message))
402 logLevel.ComponentName = arouter_to_kube[logLevel.ComponentName]
403
404 data = append(data, logLevel)
405 }
406 }
407 }
408
409 outputFormat := CharReplacer.Replace(options.Format)
410 if outputFormat == "" {
David Bainbridgea6722342019-10-24 23:55:53 +0000411 outputFormat = GetCommandOptionWithDefault(methodName, "format", DEFAULT_LOGLEVELS_FORMAT)
412 }
413 orderBy := options.OrderBy
414 if orderBy == "" {
415 orderBy = GetCommandOptionWithDefault(methodName, "order", "")
Scott Bakerd69e4222019-08-21 16:46:05 -0700416 }
417
418 result := CommandResult{
419 Format: format.Format(outputFormat),
420 Filter: options.Filter,
David Bainbridgea6722342019-10-24 23:55:53 +0000421 OrderBy: orderBy,
Scott Bakerd69e4222019-08-21 16:46:05 -0700422 OutputAs: toOutputType(options.OutputAs),
423 NameLimit: options.NameLimit,
424 Data: data,
425 }
426 GenerateOutput(&result)
427 return nil
428}
429
David Bainbridgea6722342019-10-24 23:55:53 +0000430func (options *GetLogLevelsOpts) Execute(args []string) error {
431 return options.getLogLevels("loglevel-get", args)
432}
433
Scott Bakerd69e4222019-08-21 16:46:05 -0700434func (options *ListLogLevelsOpts) Execute(args []string) error {
435 var getOptions GetLogLevelsOpts
436 var podNames []string
437
438 _, arouter_to_kube, err := BuildKubernetesNameMap()
439 if err != nil {
440 return err
441 }
442
443 for _, podName := range arouter_to_kube {
444 podNames = append(podNames, podName)
445 }
446
447 // Just call GetLogLevels with a list of podnames that includes everything relevant.
448
449 getOptions.ListOutputOptions = options.ListOutputOptions
450 getOptions.Args.Component = podNames
451
David Bainbridgea6722342019-10-24 23:55:53 +0000452 return getOptions.getLogLevels("loglevel-list", args)
Scott Bakerd69e4222019-08-21 16:46:05 -0700453}