blob: c56e3a414ff4d4a826590d7869a524daab9663d1 [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":
Scott Bakerc9091fc2019-12-05 11:23:49 -0800207 affinity_group, affinity_group_ok := pod.Labels["affinity-group"]
208 affinity_group_core_id, affinity_group_core_ok := pod.Labels["affinity-group-core-id"]
209
210 if affinity_group_ok && affinity_group_core_ok {
211 // api-server is part of the deployment
212 arouter_name = "vcore" + affinity_group + ".vcore" + affinity_group + affinity_group_core_id
213 } else if !affinity_group_ok && !affinity_group_core_ok {
214 // api-server is not part of the deployment. Any name will do since we're talking
215 // directly to the core and not routing through the api-server.
216 arouter_name = app
217 } else {
218 // labeling is inconsistent; something is messed up
219 Warn.Printf("rwcore %s has one of affinity-group-core-id, affinity-group label but not the other", pod.Name)
Scott Bakerd69e4222019-08-21 16:46:05 -0700220 continue
221 }
Scott Bakerd69e4222019-08-21 16:46:05 -0700222 case "ro-core":
223 /*
224 * Assumes a single rocore for now.
225 * TODO: Make labeling changes in charts to be able to derive name from labels
226 */
227 arouter_name = "ro_vcore0.ro_vcore01"
228 default:
229 // skip this pod as it's not relevant
230 continue
231 }
232
233 // Multiple ways to identify the component
234
235 // 1) The pod name. One pod name maps to exactly one pod.
236
237 arouter_to_kube[arouter_name] = pod.Name
238 MapListAppend(kube_to_arouter, pod.Name, arouter_name)
239
240 // 2) The kubernetes component name. A single component (i.e. "core") may map to multiple pods.
241
242 component, ok := pod.Labels["app.kubernetes.io/component"]
243 if ok {
244 MapListAppend(kube_to_arouter, component, arouter_name)
245 }
246
247 // 3) The voltha app label. A single app (i.e. "rwcore") may map to multiple pods.
248
249 MapListAppend(kube_to_arouter, app, arouter_name)
250
251 }
252
253 return kube_to_arouter, arouter_to_kube, nil
254}
255
256func (options *SetLogLevelOpts) Execute(args []string) error {
257 if len(options.Args.Component) == 0 {
258 return fmt.Errorf("Please specify at least one component")
259 }
260
261 kube_to_arouter, arouter_to_kube, err := BuildKubernetesNameMap()
262 if err != nil {
263 return err
264 }
265
266 var output []SetLogLevelOutput
267
268 // Validate component names, throw error now to avoid doing partial work
269 err = ValidateComponentNames(kube_to_arouter, options.Args.Component)
270 if err != nil {
271 return err
272 }
273
274 // Validate and map the logLevel string to an integer, throw error now to avoid doing partial work
275 intLogLevel, err := LogLevelStringToInt(options.Args.Level)
276 if err != nil {
277 return err
278 }
279
280 for _, kubeComponentName := range options.Args.Component {
281 var descriptor grpcurl.DescriptorSource
282 var conn *grpc.ClientConn
283 var method string
284
285 componentNameList := kube_to_arouter[kubeComponentName]
286
287 for _, componentName := range componentNameList {
288 conn, err = NewConnection()
289 if err != nil {
290 return err
291 }
292 defer conn.Close()
293 if strings.HasPrefix(componentName, "api_server") {
294 // apiserver's UpdateLogLevel is in the afrouter.Configuration gRPC package
295 descriptor, method, err = GetMethod("apiserver-update-log-level")
296 } else {
297 descriptor, method, err = GetMethod("update-log-level")
298 }
299 if err != nil {
300 return err
301 }
302
303 ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
304 defer cancel()
305
306 ll := make(map[string]interface{})
307 ll["component_name"] = componentName
308 ll["package_name"] = options.Package
309 ll["level"] = intLogLevel
310
311 h := &RpcEventHandler{
312 Fields: map[string]map[string]interface{}{"common.Logging": ll},
313 }
314 err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, []string{}, h, h.GetParams)
315 if err != nil {
316 return err
317 }
318
319 if h.Status != nil && h.Status.Err() != nil {
320 output = append(output, SetLogLevelOutput{ComponentName: arouter_to_kube[componentName], Status: "Failure", Error: h.Status.Err().Error()})
321 continue
322 }
323
324 output = append(output, SetLogLevelOutput{ComponentName: arouter_to_kube[componentName], Status: "Success"})
325 }
326 }
327
328 outputFormat := CharReplacer.Replace(options.Format)
329 if outputFormat == "" {
David Bainbridgea6722342019-10-24 23:55:53 +0000330 outputFormat = GetCommandOptionWithDefault("loglevel-set", "format", DEFAULT_SETLOGLEVEL_FORMAT)
Scott Bakerd69e4222019-08-21 16:46:05 -0700331 }
332
333 result := CommandResult{
334 Format: format.Format(outputFormat),
335 OutputAs: toOutputType(options.OutputAs),
336 NameLimit: options.NameLimit,
337 Data: output,
338 }
339
340 GenerateOutput(&result)
341 return nil
342}
343
David Bainbridgea6722342019-10-24 23:55:53 +0000344func (options *GetLogLevelsOpts) getLogLevels(methodName string, args []string) error {
Scott Bakerd69e4222019-08-21 16:46:05 -0700345 if len(options.Args.Component) == 0 {
346 return fmt.Errorf("Please specify at least one component")
347 }
348
349 kube_to_arouter, arouter_to_kube, err := BuildKubernetesNameMap()
350 if err != nil {
351 return err
352 }
353
354 var data []model.LogLevel
355
356 // Validate component names, throw error now to avoid doing partial work
357 err = ValidateComponentNames(kube_to_arouter, options.Args.Component)
358 if err != nil {
359 return err
360 }
361
362 for _, kubeComponentName := range options.Args.Component {
363 var descriptor grpcurl.DescriptorSource
364 var conn *grpc.ClientConn
365 var method string
366
367 componentNameList := kube_to_arouter[kubeComponentName]
368
369 for _, componentName := range componentNameList {
370 conn, err = NewConnection()
371 if err != nil {
372 return err
373 }
374 defer conn.Close()
375 if strings.HasPrefix(componentName, "api_server") {
376 // apiserver's UpdateLogLevel is in the afrouter.Configuration gRPC package
377 descriptor, method, err = GetMethod("apiserver-get-log-levels")
378 } else {
379 descriptor, method, err = GetMethod("get-log-levels")
380 }
381 if err != nil {
382 return err
383 }
384
385 ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
386 defer cancel()
387
388 ll := make(map[string]interface{})
389 ll["component_name"] = componentName
390
391 h := &RpcEventHandler{
392 Fields: map[string]map[string]interface{}{"common.LoggingComponent": ll},
393 }
394 err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, []string{}, h, h.GetParams)
395 if err != nil {
396 return err
397 }
398
399 if h.Status != nil && h.Status.Err() != nil {
400 return h.Status.Err()
401 }
402
403 d, err := dynamic.AsDynamicMessage(h.Response)
404 if err != nil {
405 return err
406 }
407 items, err := d.TryGetFieldByName("items")
408 if err != nil {
409 return err
410 }
411
412 for _, item := range items.([]interface{}) {
413 logLevel := model.LogLevel{}
414 logLevel.PopulateFrom(item.(*dynamic.Message))
415 logLevel.ComponentName = arouter_to_kube[logLevel.ComponentName]
416
417 data = append(data, logLevel)
418 }
419 }
420 }
421
422 outputFormat := CharReplacer.Replace(options.Format)
423 if outputFormat == "" {
David Bainbridgea6722342019-10-24 23:55:53 +0000424 outputFormat = GetCommandOptionWithDefault(methodName, "format", DEFAULT_LOGLEVELS_FORMAT)
425 }
426 orderBy := options.OrderBy
427 if orderBy == "" {
428 orderBy = GetCommandOptionWithDefault(methodName, "order", "")
Scott Bakerd69e4222019-08-21 16:46:05 -0700429 }
430
431 result := CommandResult{
432 Format: format.Format(outputFormat),
433 Filter: options.Filter,
David Bainbridgea6722342019-10-24 23:55:53 +0000434 OrderBy: orderBy,
Scott Bakerd69e4222019-08-21 16:46:05 -0700435 OutputAs: toOutputType(options.OutputAs),
436 NameLimit: options.NameLimit,
437 Data: data,
438 }
439 GenerateOutput(&result)
440 return nil
441}
442
David Bainbridgea6722342019-10-24 23:55:53 +0000443func (options *GetLogLevelsOpts) Execute(args []string) error {
444 return options.getLogLevels("loglevel-get", args)
445}
446
Scott Bakerd69e4222019-08-21 16:46:05 -0700447func (options *ListLogLevelsOpts) Execute(args []string) error {
448 var getOptions GetLogLevelsOpts
449 var podNames []string
450
451 _, arouter_to_kube, err := BuildKubernetesNameMap()
452 if err != nil {
453 return err
454 }
455
456 for _, podName := range arouter_to_kube {
457 podNames = append(podNames, podName)
458 }
459
460 // Just call GetLogLevels with a list of podnames that includes everything relevant.
461
462 getOptions.ListOutputOptions = options.ListOutputOptions
463 getOptions.Args.Component = podNames
464
David Bainbridgea6722342019-10-24 23:55:53 +0000465 return getOptions.getLogLevels("loglevel-list", args)
Scott Bakerd69e4222019-08-21 16:46:05 -0700466}