blob: 5da4e1280c13fd8e200601e0abf0b9fe47d7f067 [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
Scott Baker3fe09602019-10-25 10:27:16 -070041 Package string `short:"p" long:"package" description:"Package name to set log level"`
Scott Bakerd69e4222019-08-21 16:46:05 -070042 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 {
David Bainbridge0f758d42019-10-26 05:17:48 +000075 Error.Fatalf("Unable to register log level commands with voltctl command parser: %s", err.Error())
Scott Bakerd69e4222019-08-21 16:46:05 -070076 }
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 {
Scott Baker3fe09602019-10-25 10:27:16 -0700149 allowedNames := make([]string, len(kube_to_arouter))
150 i := 0
151 for k := range kube_to_arouter {
152 allowedNames[i] = k
153 i++
154 }
155
156 return fmt.Errorf("Unknown component(s): %s.\n (Allowed values for component names: \n %s)",
157 strings.Join(badNames, ", "),
158 strings.Join(allowedNames, ",\n "))
Scott Bakerd69e4222019-08-21 16:46:05 -0700159 } else {
160 return nil
161 }
162}
163
164func BuildKubernetesNameMap() (map[string][]string, map[string]string, error) {
165 kube_to_arouter := make(map[string][]string)
166 arouter_to_kube := make(map[string]string)
167
168 // use the current context in kubeconfig
169 config, err := clientcmd.BuildConfigFromFlags("", GlobalOptions.K8sConfig)
170 if err != nil {
171 return nil, nil, err
172 }
173
174 // create the clientset
175 clientset, err := kubernetes.NewForConfig(config)
176 if err != nil {
177 return nil, nil, err
178 }
179
180 pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{
181 LabelSelector: "app.kubernetes.io/part-of=voltha",
182 })
183 if err != nil {
184 return nil, nil, err
185 }
186
187 if len(pods.Items) == 0 {
188 return nil, nil, fmt.Errorf("No Voltha pods found in Kubernetes -- verify pod is setup")
189 }
190
191 for _, pod := range pods.Items {
192 app, ok := pod.Labels["app"]
193 if !ok {
194 continue
195 }
196
197 var arouter_name string
198
199 switch app {
200 case "voltha-api-server":
201 /*
202 * Assumes a single api_server for now.
203 * TODO: Make labeling changes in charts to be able to derive name from labels
204 */
205 arouter_name = "api_server0.api_server01"
206 case "rw-core":
207 affinity_group, ok := pod.Labels["affinity-group"]
208 if !ok {
David Bainbridgea6722342019-10-24 23:55:53 +0000209 Warn.Printf("rwcore %s lacks affinity-group label", pod.Name)
Scott Bakerd69e4222019-08-21 16:46:05 -0700210 continue
211 }
212 affinity_group_core_id, ok := pod.Labels["affinity-group-core-id"]
213 if !ok {
David Bainbridgea6722342019-10-24 23:55:53 +0000214 Warn.Printf("rwcore %s lacks affinity-group-core-id label", pod.Name)
Scott Bakerd69e4222019-08-21 16:46:05 -0700215 continue
216 }
217 arouter_name = "vcore" + affinity_group + ".vcore" + affinity_group + affinity_group_core_id
218 case "ro-core":
219 /*
220 * Assumes a single rocore for now.
221 * TODO: Make labeling changes in charts to be able to derive name from labels
222 */
223 arouter_name = "ro_vcore0.ro_vcore01"
224 default:
225 // skip this pod as it's not relevant
226 continue
227 }
228
229 // Multiple ways to identify the component
230
231 // 1) The pod name. One pod name maps to exactly one pod.
232
233 arouter_to_kube[arouter_name] = pod.Name
234 MapListAppend(kube_to_arouter, pod.Name, arouter_name)
235
236 // 2) The kubernetes component name. A single component (i.e. "core") may map to multiple pods.
237
238 component, ok := pod.Labels["app.kubernetes.io/component"]
239 if ok {
240 MapListAppend(kube_to_arouter, component, arouter_name)
241 }
242
243 // 3) The voltha app label. A single app (i.e. "rwcore") may map to multiple pods.
244
245 MapListAppend(kube_to_arouter, app, arouter_name)
246
247 }
248
249 return kube_to_arouter, arouter_to_kube, nil
250}
251
252func (options *SetLogLevelOpts) Execute(args []string) error {
253 if len(options.Args.Component) == 0 {
254 return fmt.Errorf("Please specify at least one component")
255 }
256
257 kube_to_arouter, arouter_to_kube, err := BuildKubernetesNameMap()
258 if err != nil {
259 return err
260 }
261
262 var output []SetLogLevelOutput
263
264 // Validate component names, throw error now to avoid doing partial work
265 err = ValidateComponentNames(kube_to_arouter, options.Args.Component)
266 if err != nil {
267 return err
268 }
269
270 // Validate and map the logLevel string to an integer, throw error now to avoid doing partial work
271 intLogLevel, err := LogLevelStringToInt(options.Args.Level)
272 if err != nil {
273 return err
274 }
275
276 for _, kubeComponentName := range options.Args.Component {
277 var descriptor grpcurl.DescriptorSource
278 var conn *grpc.ClientConn
279 var method string
280
281 componentNameList := kube_to_arouter[kubeComponentName]
282
283 for _, componentName := range componentNameList {
284 conn, err = NewConnection()
285 if err != nil {
286 return err
287 }
288 defer conn.Close()
289 if strings.HasPrefix(componentName, "api_server") {
290 // apiserver's UpdateLogLevel is in the afrouter.Configuration gRPC package
291 descriptor, method, err = GetMethod("apiserver-update-log-level")
292 } else {
293 descriptor, method, err = GetMethod("update-log-level")
294 }
295 if err != nil {
296 return err
297 }
298
299 ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
300 defer cancel()
301
302 ll := make(map[string]interface{})
303 ll["component_name"] = componentName
304 ll["package_name"] = options.Package
305 ll["level"] = intLogLevel
306
307 h := &RpcEventHandler{
308 Fields: map[string]map[string]interface{}{"common.Logging": ll},
309 }
310 err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, []string{}, h, h.GetParams)
311 if err != nil {
312 return err
313 }
314
315 if h.Status != nil && h.Status.Err() != nil {
316 output = append(output, SetLogLevelOutput{ComponentName: arouter_to_kube[componentName], Status: "Failure", Error: h.Status.Err().Error()})
317 continue
318 }
319
320 output = append(output, SetLogLevelOutput{ComponentName: arouter_to_kube[componentName], Status: "Success"})
321 }
322 }
323
324 outputFormat := CharReplacer.Replace(options.Format)
325 if outputFormat == "" {
David Bainbridgea6722342019-10-24 23:55:53 +0000326 outputFormat = GetCommandOptionWithDefault("loglevel-set", "format", DEFAULT_SETLOGLEVEL_FORMAT)
Scott Bakerd69e4222019-08-21 16:46:05 -0700327 }
328
329 result := CommandResult{
330 Format: format.Format(outputFormat),
331 OutputAs: toOutputType(options.OutputAs),
332 NameLimit: options.NameLimit,
333 Data: output,
334 }
335
336 GenerateOutput(&result)
337 return nil
338}
339
David Bainbridgea6722342019-10-24 23:55:53 +0000340func (options *GetLogLevelsOpts) getLogLevels(methodName string, args []string) error {
Scott Bakerd69e4222019-08-21 16:46:05 -0700341 if len(options.Args.Component) == 0 {
342 return fmt.Errorf("Please specify at least one component")
343 }
344
345 kube_to_arouter, arouter_to_kube, err := BuildKubernetesNameMap()
346 if err != nil {
347 return err
348 }
349
350 var data []model.LogLevel
351
352 // Validate component names, throw error now to avoid doing partial work
353 err = ValidateComponentNames(kube_to_arouter, options.Args.Component)
354 if err != nil {
355 return err
356 }
357
358 for _, kubeComponentName := range options.Args.Component {
359 var descriptor grpcurl.DescriptorSource
360 var conn *grpc.ClientConn
361 var method string
362
363 componentNameList := kube_to_arouter[kubeComponentName]
364
365 for _, componentName := range componentNameList {
366 conn, err = NewConnection()
367 if err != nil {
368 return err
369 }
370 defer conn.Close()
371 if strings.HasPrefix(componentName, "api_server") {
372 // apiserver's UpdateLogLevel is in the afrouter.Configuration gRPC package
373 descriptor, method, err = GetMethod("apiserver-get-log-levels")
374 } else {
375 descriptor, method, err = GetMethod("get-log-levels")
376 }
377 if err != nil {
378 return err
379 }
380
381 ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
382 defer cancel()
383
384 ll := make(map[string]interface{})
385 ll["component_name"] = componentName
386
387 h := &RpcEventHandler{
388 Fields: map[string]map[string]interface{}{"common.LoggingComponent": ll},
389 }
390 err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, []string{}, h, h.GetParams)
391 if err != nil {
392 return err
393 }
394
395 if h.Status != nil && h.Status.Err() != nil {
396 return h.Status.Err()
397 }
398
399 d, err := dynamic.AsDynamicMessage(h.Response)
400 if err != nil {
401 return err
402 }
403 items, err := d.TryGetFieldByName("items")
404 if err != nil {
405 return err
406 }
407
408 for _, item := range items.([]interface{}) {
409 logLevel := model.LogLevel{}
410 logLevel.PopulateFrom(item.(*dynamic.Message))
411 logLevel.ComponentName = arouter_to_kube[logLevel.ComponentName]
412
413 data = append(data, logLevel)
414 }
415 }
416 }
417
418 outputFormat := CharReplacer.Replace(options.Format)
419 if outputFormat == "" {
David Bainbridgea6722342019-10-24 23:55:53 +0000420 outputFormat = GetCommandOptionWithDefault(methodName, "format", DEFAULT_LOGLEVELS_FORMAT)
421 }
422 orderBy := options.OrderBy
423 if orderBy == "" {
424 orderBy = GetCommandOptionWithDefault(methodName, "order", "")
Scott Bakerd69e4222019-08-21 16:46:05 -0700425 }
426
427 result := CommandResult{
428 Format: format.Format(outputFormat),
429 Filter: options.Filter,
David Bainbridgea6722342019-10-24 23:55:53 +0000430 OrderBy: orderBy,
Scott Bakerd69e4222019-08-21 16:46:05 -0700431 OutputAs: toOutputType(options.OutputAs),
432 NameLimit: options.NameLimit,
433 Data: data,
434 }
435 GenerateOutput(&result)
436 return nil
437}
438
David Bainbridgea6722342019-10-24 23:55:53 +0000439func (options *GetLogLevelsOpts) Execute(args []string) error {
440 return options.getLogLevels("loglevel-get", args)
441}
442
Scott Bakerd69e4222019-08-21 16:46:05 -0700443func (options *ListLogLevelsOpts) Execute(args []string) error {
444 var getOptions GetLogLevelsOpts
445 var podNames []string
446
447 _, arouter_to_kube, err := BuildKubernetesNameMap()
448 if err != nil {
449 return err
450 }
451
452 for _, podName := range arouter_to_kube {
453 podNames = append(podNames, podName)
454 }
455
456 // Just call GetLogLevels with a list of podnames that includes everything relevant.
457
458 getOptions.ListOutputOptions = options.ListOutputOptions
459 getOptions.Args.Component = podNames
460
David Bainbridgea6722342019-10-24 23:55:53 +0000461 return getOptions.getLogLevels("loglevel-list", args)
Scott Bakerd69e4222019-08-21 16:46:05 -0700462}