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