blob: 93944a860f147fb7f52f175123e452449a9777ba [file] [log] [blame]
Zack Williamse940c7a2019-08-21 14:25:39 -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 (
David K. Bainbridge1d946442021-03-19 16:45:52 +000019 "context"
20 "crypto/tls"
Zack Williamse940c7a2019-08-21 14:25:39 -070021 "encoding/json"
Scott Baker9173ed82020-05-19 08:30:12 -070022 "errors"
Zack Williamse940c7a2019-08-21 14:25:39 -070023 "fmt"
serkant.uluderyad3daa902020-05-21 22:49:25 -070024 "io/ioutil"
25 "log"
serkant.uluderyad3daa902020-05-21 22:49:25 -070026 "os"
27 "path/filepath"
28 "reflect"
29 "regexp"
30 "strconv"
31 "strings"
32 "time"
33
Scott Baker9173ed82020-05-19 08:30:12 -070034 "github.com/golang/protobuf/jsonpb"
35 "github.com/golang/protobuf/proto"
David K. Bainbridge1d946442021-03-19 16:45:52 +000036 configv1 "github.com/opencord/voltctl/internal/pkg/apis/config/v1"
37 configv2 "github.com/opencord/voltctl/internal/pkg/apis/config/v2"
David K. Bainbridge9189c632021-03-26 21:52:21 +000038 configv3 "github.com/opencord/voltctl/internal/pkg/apis/config/v3"
Scott Baker2b0ad652019-08-21 14:57:07 -070039 "github.com/opencord/voltctl/pkg/filter"
40 "github.com/opencord/voltctl/pkg/format"
41 "github.com/opencord/voltctl/pkg/order"
Zack Williamse940c7a2019-08-21 14:25:39 -070042 "google.golang.org/grpc"
David K. Bainbridge1d946442021-03-19 16:45:52 +000043 "google.golang.org/grpc/credentials"
44 yaml "gopkg.in/yaml.v2"
Zack Williamse940c7a2019-08-21 14:25:39 -070045)
46
47type OutputType uint8
48
49const (
50 OUTPUT_TABLE OutputType = iota
51 OUTPUT_JSON
52 OUTPUT_YAML
divyadesai19009132020-03-04 12:58:08 +000053
divyadesai19009132020-03-04 12:58:08 +000054 supportedKvStoreType = "etcd"
Zack Williamse940c7a2019-08-21 14:25:39 -070055)
56
Zack Williamse940c7a2019-08-21 14:25:39 -070057var (
58 ParamNames = map[string]map[string]string{
59 "v1": {
60 "ID": "voltha.ID",
61 },
62 "v2": {
63 "ID": "common.ID",
64 },
kesavand12cd8eb2020-01-20 22:25:22 -050065 "v3": {
Dinesh Belwalkarc9aa6d82020-03-04 15:22:17 -080066 "ID": "common.ID",
67 "port": "voltha.Port",
68 "ValueSpecifier": "common.ValueSpecifier",
kesavand12cd8eb2020-01-20 22:25:22 -050069 },
Zack Williamse940c7a2019-08-21 14:25:39 -070070 }
71
72 CharReplacer = strings.NewReplacer("\\t", "\t", "\\n", "\n")
73
David K. Bainbridge9189c632021-03-26 21:52:21 +000074 GlobalConfig = configv3.NewDefaultConfig()
Zack Williamse940c7a2019-08-21 14:25:39 -070075
David Bainbridgea6722342019-10-24 23:55:53 +000076 GlobalCommandOptions = make(map[string]map[string]string)
77
Zack Williamse940c7a2019-08-21 14:25:39 -070078 GlobalOptions struct {
divyadesai19009132020-03-04 12:58:08 +000079 Config string `short:"c" long:"config" env:"VOLTCONFIG" value-name:"FILE" default:"" description:"Location of client config file"`
David K. Bainbridge9189c632021-03-26 21:52:21 +000080 Stack string `short:"v" long:"stack" env:"STACK" value-name:"STACK" default:"" description:"Name of stack to use in multistack deployment"`
divyadesai19009132020-03-04 12:58:08 +000081 Server string `short:"s" long:"server" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of VOLTHA"`
82 Kafka string `short:"k" long:"kafka" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of Kafka"`
83 KvStore string `short:"e" long:"kvstore" env:"KVSTORE" value-name:"SERVER:PORT" description:"IP/Host and port of KV store (etcd)"`
84
David K. Bainbridge2b627612020-02-18 14:50:13 -080085 // nolint: staticcheck
serkant.uluderyad3daa902020-05-21 22:49:25 -070086 Debug bool `short:"d" long:"debug" description:"Enable debug mode"`
87 Timeout string `short:"t" long:"timeout" description:"API call timeout duration" value-name:"DURATION" default:""`
88 UseTLS bool `long:"tls" description:"Use TLS"`
89 CACert string `long:"tlscacert" value-name:"CA_CERT_FILE" description:"Trust certs signed only by this CA"`
90 Cert string `long:"tlscert" value-name:"CERT_FILE" description:"Path to TLS vertificate file"`
91 Key string `long:"tlskey" value-name:"KEY_FILE" description:"Path to TLS key file"`
92 Verify bool `long:"tlsverify" description:"Use TLS and verify the remote"`
93 K8sConfig string `short:"8" long:"k8sconfig" env:"KUBECONFIG" value-name:"FILE" default:"" description:"Location of Kubernetes config file"`
94 KvStoreTimeout string `long:"kvstoretimeout" env:"KVSTORE_TIMEOUT" value-name:"DURATION" default:"" description:"timeout for calls to KV store"`
95 CommandOptions string `short:"o" long:"command-options" env:"VOLTCTL_COMMAND_OPTIONS" value-name:"FILE" default:"" description:"Location of command options default configuration file"`
96 MaxCallRecvMsgSize string `short:"m" long:"maxcallrecvmsgsize" description:"Max GRPC Client request size limit in bytes (eg: 4MB)" value-name:"SIZE" default:"4M"`
Zack Williamse940c7a2019-08-21 14:25:39 -070097 }
David Bainbridgea6722342019-10-24 23:55:53 +000098
99 Debug = log.New(os.Stdout, "DEBUG: ", 0)
100 Info = log.New(os.Stdout, "INFO: ", 0)
101 Warn = log.New(os.Stderr, "WARN: ", 0)
102 Error = log.New(os.Stderr, "ERROR: ", 0)
Zack Williamse940c7a2019-08-21 14:25:39 -0700103)
104
105type OutputOptions struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800106 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
107 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
108 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700109 OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
110 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
111}
112
Maninder045921e2020-09-29 16:46:02 +0530113type FlowIdOptions struct {
114 HexId bool `short:"x" long:"hex-id" description:"Output Ids in hex format"`
115}
116
Zack Williamse940c7a2019-08-21 14:25:39 -0700117type ListOutputOptions struct {
118 OutputOptions
119 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
120 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
121}
122
123type OutputOptionsJson struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800124 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
125 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
126 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700127 OutputAs string `short:"o" long:"outputas" default:"json" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
128 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
129}
130
131type ListOutputOptionsJson struct {
132 OutputOptionsJson
133 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
134 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
135}
136
137func toOutputType(in string) OutputType {
138 switch in {
139 case "table":
140 fallthrough
141 default:
142 return OUTPUT_TABLE
143 case "json":
144 return OUTPUT_JSON
145 case "yaml":
146 return OUTPUT_YAML
147 }
148}
149
150type CommandResult struct {
151 Format format.Format
152 Filter string
153 OrderBy string
154 OutputAs OutputType
155 NameLimit int
156 Data interface{}
157}
158
David Bainbridgea6722342019-10-24 23:55:53 +0000159func GetCommandOptionWithDefault(name, option, defaultValue string) string {
160 if cmd, ok := GlobalCommandOptions[name]; ok {
161 if val, ok := cmd[option]; ok {
162 return CharReplacer.Replace(val)
163 }
164 }
165 return defaultValue
166}
167
serkant.uluderyad3daa902020-05-21 22:49:25 -0700168var sizeParser = regexp.MustCompile(`^([0-9]+)([PETGMK]?)I?B?$`)
169
170func parseSize(size string) (uint64, error) {
171
172 parts := sizeParser.FindAllStringSubmatch(strings.ToUpper(size), -1)
173 if len(parts) == 0 {
174 return 0, fmt.Errorf("size: invalid size '%s'", size)
175 }
176 value, err := strconv.ParseUint(parts[0][1], 10, 64)
177 if err != nil {
178 return 0, fmt.Errorf("size: invalid size '%s'", size)
179 }
180 switch parts[0][2] {
181 case "E":
182 value = value * 1024 * 1024 * 1024 * 1024 * 1024 * 1024
183 case "P":
184 value = value * 1024 * 1024 * 1024 * 1024 * 1024
185 case "T":
186 value = value * 1024 * 1024 * 1024 * 1024
187 case "G":
188 value = value * 1024 * 1024 * 1024
189 case "M":
190 value = value * 1024 * 1024
191 case "K":
192 value = value * 1024
193 default:
194 }
195 return value, nil
196}
197
Zack Williamse940c7a2019-08-21 14:25:39 -0700198func ProcessGlobalOptions() {
David K. Bainbridge9189c632021-03-26 21:52:21 +0000199 ReadConfig()
200
201 // If a stack is selected via command line set it
202 if GlobalOptions.Stack != "" {
203 if GlobalConfig.StackByName(GlobalOptions.Stack) == nil {
204 Error.Fatalf("stack specified, '%s', not found in configuration",
205 GlobalOptions.Stack)
Zack Williamse940c7a2019-08-21 14:25:39 -0700206 }
David K. Bainbridge9189c632021-03-26 21:52:21 +0000207 GlobalConfig.CurrentStack = GlobalOptions.Stack
Zack Williamse940c7a2019-08-21 14:25:39 -0700208 }
209
David K. Bainbridge9189c632021-03-26 21:52:21 +0000210 ApplyOptionOverrides(GlobalConfig.Current())
serkant.uluderyad3daa902020-05-21 22:49:25 -0700211
Zack Williamse940c7a2019-08-21 14:25:39 -0700212 // If a k8s cert/key were not specified, then attempt to read it from
213 // any $HOME/.kube/config if it exists
214 if len(GlobalOptions.K8sConfig) == 0 {
215 home, err := os.UserHomeDir()
216 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000217 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700218 home = "~"
219 }
220 GlobalOptions.K8sConfig = filepath.Join(home, ".kube", "config")
221 }
David Bainbridgea6722342019-10-24 23:55:53 +0000222
223 if len(GlobalOptions.CommandOptions) == 0 {
224 home, err := os.UserHomeDir()
225 if err != nil {
226 Warn.Printf("Unable to discover the user's home directory: %s", err)
227 home = "~"
228 }
229 GlobalOptions.CommandOptions = filepath.Join(home, ".volt", "command_options")
230 }
231
232 if info, err := os.Stat(GlobalOptions.CommandOptions); err == nil && !info.IsDir() {
233 optionsFile, err := ioutil.ReadFile(GlobalOptions.CommandOptions)
234 if err != nil {
235 Error.Fatalf("Unable to read command options configuration file '%s' : %s",
236 GlobalOptions.CommandOptions, err.Error())
237 }
238 if err = yaml.Unmarshal(optionsFile, &GlobalCommandOptions); err != nil {
239 Error.Fatalf("Unable to parse the command line options configuration file '%s': %s",
240 GlobalOptions.CommandOptions, err.Error())
241 }
242 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700243}
244
David K. Bainbridge9189c632021-03-26 21:52:21 +0000245func ApplyOptionOverrides(stack *configv3.StackConfigSpec) {
246
247 if stack == nil {
248 // nothing to do
249 return
250 }
251 // Override from command line
252 if GlobalOptions.Server != "" {
253 stack.Server = GlobalOptions.Server
254 }
255
256 if GlobalOptions.UseTLS {
257 stack.Tls.UseTls = true
258 }
259
260 if GlobalOptions.Verify {
261 stack.Tls.Verify = true
262 }
263
264 if GlobalOptions.Kafka != "" {
265 stack.Kafka = GlobalOptions.Kafka
266 }
267
268 if GlobalOptions.KvStore != "" {
269 stack.KvStore = GlobalOptions.KvStore
270 }
271
272 if GlobalOptions.KvStoreTimeout != "" {
273 timeout, err := time.ParseDuration(GlobalOptions.KvStoreTimeout)
274 if err != nil {
275 Error.Fatalf("Unable to parse specified KV strore timeout duration '%s': %s",
276 GlobalOptions.KvStoreTimeout, err.Error())
277 }
278 stack.KvStoreConfig.Timeout = timeout
279 }
280
281 if GlobalOptions.Timeout != "" {
282 timeout, err := time.ParseDuration(GlobalOptions.Timeout)
283 if err != nil {
284 Error.Fatalf("Unable to parse specified timeout duration '%s': %s",
285 GlobalOptions.Timeout, err.Error())
286 }
287 stack.Grpc.Timeout = timeout
288 }
289
290 if GlobalOptions.MaxCallRecvMsgSize != "" {
291 stack.Grpc.MaxCallRecvMsgSize = GlobalOptions.MaxCallRecvMsgSize
292 }
293}
294
295func ReadConfig() {
296 if len(GlobalOptions.Config) == 0 {
297 home, err := os.UserHomeDir()
298 if err != nil {
299 Warn.Printf("Unable to discover the user's home directory: %s", err)
300 home = "~"
301 }
302 GlobalOptions.Config = filepath.Join(home, ".volt", "config")
303 }
304
305 if info, err := os.Stat(GlobalOptions.Config); err == nil && !info.IsDir() {
306 configFile, err := ioutil.ReadFile(GlobalOptions.Config)
307 if err != nil {
308 Error.Fatalf("Unable to read the configuration file '%s': %s",
309 GlobalOptions.Config, err.Error())
310 }
311 // First try the latest version of the config api then work
312 // backwards
313 if err = yaml.Unmarshal(configFile, &GlobalConfig); err != nil {
314 GlobalConfigV2 := configv2.NewDefaultConfig()
315 if err = yaml.Unmarshal(configFile, &GlobalConfigV2); err != nil {
316 GlobalConfigV1 := configv1.NewDefaultConfig()
317 if err = yaml.Unmarshal(configFile, &GlobalConfigV1); err != nil {
318 Error.Fatalf("Unable to parse the configuration file '%s': %s",
319 GlobalOptions.Config, err.Error())
320 }
321 GlobalConfig = configv3.FromConfigV1(GlobalConfigV1)
322 } else {
323 GlobalConfig = configv3.FromConfigV2(GlobalConfigV2)
324 }
325 }
326 }
327
328}
329
Zack Williamse940c7a2019-08-21 14:25:39 -0700330func NewConnection() (*grpc.ClientConn, error) {
331 ProcessGlobalOptions()
serkant.uluderyad3daa902020-05-21 22:49:25 -0700332
333 // convert grpc.msgSize into bytes
David K. Bainbridge9189c632021-03-26 21:52:21 +0000334 n, err := parseSize(GlobalConfig.Current().Grpc.MaxCallRecvMsgSize)
serkant.uluderyad3daa902020-05-21 22:49:25 -0700335 if err != nil {
David K. Bainbridge9189c632021-03-26 21:52:21 +0000336 Error.Fatalf("Cannot convert msgSize %s to bytes", GlobalConfig.Current().Grpc.MaxCallRecvMsgSize)
serkant.uluderyad3daa902020-05-21 22:49:25 -0700337 }
338
David K. Bainbridge1d946442021-03-19 16:45:52 +0000339 var opts []grpc.DialOption
340
341 opts = append(opts,
342 grpc.WithDisableRetry(),
343 grpc.WithBlock(),
344 grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(n))))
345
David K. Bainbridge9189c632021-03-26 21:52:21 +0000346 if GlobalConfig.Current().Tls.UseTls {
David K. Bainbridge1d946442021-03-19 16:45:52 +0000347 creds := credentials.NewTLS(&tls.Config{
David K. Bainbridge9189c632021-03-26 21:52:21 +0000348 InsecureSkipVerify: !GlobalConfig.Current().Tls.Verify})
David K. Bainbridge1d946442021-03-19 16:45:52 +0000349 opts = append(opts, grpc.WithTransportCredentials(creds))
350 } else {
351 opts = append(opts, grpc.WithInsecure())
352 }
353 ctx, cancel := context.WithTimeout(context.TODO(),
David K. Bainbridge9189c632021-03-26 21:52:21 +0000354 GlobalConfig.Current().Grpc.ConnectTimeout)
David K. Bainbridge1d946442021-03-19 16:45:52 +0000355 defer cancel()
David K. Bainbridge9189c632021-03-26 21:52:21 +0000356 return grpc.DialContext(ctx, GlobalConfig.Current().Server, opts...)
Zack Williamse940c7a2019-08-21 14:25:39 -0700357}
358
Scott Baker9173ed82020-05-19 08:30:12 -0700359func ConvertJsonProtobufArray(data_in interface{}) (string, error) {
360 result := ""
361
362 slice := reflect.ValueOf(data_in)
363 if slice.Kind() != reflect.Slice {
364 return "", errors.New("Not a slice")
365 }
366
367 result = result + "["
368
369 marshaler := jsonpb.Marshaler{EmitDefaults: true}
370 for i := 0; i < slice.Len(); i++ {
371 item := slice.Index(i).Interface()
372 protoMessage, okay := item.(proto.Message)
373 if !okay {
374 return "", errors.New("Failed to convert item to a proto.Message")
375 }
376 asJson, err := marshaler.MarshalToString(protoMessage)
377 if err != nil {
378 return "", fmt.Errorf("Failed to marshal the json: %s", err)
379 }
380
381 result = result + asJson
382
383 if i < slice.Len()-1 {
384 result = result + ","
385 }
386 }
387
388 result = result + "]"
389
390 return result, nil
391}
392
Zack Williamse940c7a2019-08-21 14:25:39 -0700393func GenerateOutput(result *CommandResult) {
394 if result != nil && result.Data != nil {
395 data := result.Data
396 if result.Filter != "" {
397 f, err := filter.Parse(result.Filter)
398 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000399 Error.Fatalf("Unable to parse specified output filter '%s': %s", result.Filter, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700400 }
401 data, err = f.Process(data)
402 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000403 Error.Fatalf("Unexpected error while filtering command results: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700404 }
405 }
406 if result.OrderBy != "" {
407 s, err := order.Parse(result.OrderBy)
408 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000409 Error.Fatalf("Unable to parse specified sort specification '%s': %s", result.OrderBy, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700410 }
411 data, err = s.Process(data)
412 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000413 Error.Fatalf("Unexpected error while sorting command result: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700414 }
415 }
416 if result.OutputAs == OUTPUT_TABLE {
417 tableFormat := format.Format(result.Format)
David Bainbridge12f036f2019-10-15 22:09:04 +0000418 if err := tableFormat.Execute(os.Stdout, true, result.NameLimit, data); err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000419 Error.Fatalf("Unexpected error while attempting to format results as table : %s", err.Error())
David Bainbridge12f036f2019-10-15 22:09:04 +0000420 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700421 } else if result.OutputAs == OUTPUT_JSON {
Scott Baker9173ed82020-05-19 08:30:12 -0700422 // first try to convert it as an array of protobufs
423 asJson, err := ConvertJsonProtobufArray(data)
Zack Williamse940c7a2019-08-21 14:25:39 -0700424 if err != nil {
Scott Baker9173ed82020-05-19 08:30:12 -0700425 // if that fails, then just do a standard json conversion
426 asJsonB, err := json.Marshal(&data)
427 if err != nil {
428 Error.Fatalf("Unexpected error while processing command results to JSON: %s", err.Error())
429 }
430 asJson = string(asJsonB)
Zack Williamse940c7a2019-08-21 14:25:39 -0700431 }
432 fmt.Printf("%s", asJson)
433 } else if result.OutputAs == OUTPUT_YAML {
434 asYaml, err := yaml.Marshal(&data)
435 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000436 Error.Fatalf("Unexpected error while processing command results to YAML: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700437 }
438 fmt.Printf("%s", asYaml)
439 }
440 }
441}