blob: d5a2785d2aac14c75bb1a295a4ee717a02cff339 [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 (
19 "encoding/json"
Scott Baker9173ed82020-05-19 08:30:12 -070020 "errors"
Zack Williamse940c7a2019-08-21 14:25:39 -070021 "fmt"
serkant.uluderyad3daa902020-05-21 22:49:25 -070022 "io/ioutil"
23 "log"
24 "net"
25 "os"
26 "path/filepath"
27 "reflect"
28 "regexp"
29 "strconv"
30 "strings"
31 "time"
32
Scott Baker9173ed82020-05-19 08:30:12 -070033 "github.com/golang/protobuf/jsonpb"
34 "github.com/golang/protobuf/proto"
Scott Baker2b0ad652019-08-21 14:57:07 -070035 "github.com/opencord/voltctl/pkg/filter"
36 "github.com/opencord/voltctl/pkg/format"
37 "github.com/opencord/voltctl/pkg/order"
Zack Williamse940c7a2019-08-21 14:25:39 -070038 "google.golang.org/grpc"
39 "gopkg.in/yaml.v2"
Zack Williamse940c7a2019-08-21 14:25:39 -070040)
41
42type OutputType uint8
43
44const (
45 OUTPUT_TABLE OutputType = iota
46 OUTPUT_JSON
47 OUTPUT_YAML
divyadesai19009132020-03-04 12:58:08 +000048
49 defaultApiHost = "localhost"
50 defaultApiPort = 55555
51
52 defaultKafkaHost = "localhost"
53 defaultKafkaPort = 9092
54
55 supportedKvStoreType = "etcd"
56 defaultKvHost = "localhost"
57 defaultKvPort = 2379
58 defaultKvTimeout = time.Second * 5
59
serkant.uluderyad3daa902020-05-21 22:49:25 -070060 defaultGrpcTimeout = time.Minute * 5
61 defaultGrpcMaxCallRecvMsgSize = "4MB"
Zack Williamse940c7a2019-08-21 14:25:39 -070062)
63
64type GrpcConfigSpec struct {
serkant.uluderyad3daa902020-05-21 22:49:25 -070065 Timeout time.Duration `yaml:"timeout"`
66 MaxCallRecvMsgSize string `yaml:"maxCallRecvMsgSize"`
Zack Williamse940c7a2019-08-21 14:25:39 -070067}
68
divyadesai19009132020-03-04 12:58:08 +000069type KvStoreConfigSpec struct {
70 Timeout time.Duration `yaml:"timeout"`
71}
72
Zack Williamse940c7a2019-08-21 14:25:39 -070073type TlsConfigSpec struct {
74 UseTls bool `yaml:"useTls"`
75 CACert string `yaml:"caCert"`
76 Cert string `yaml:"cert"`
77 Key string `yaml:"key"`
78 Verify string `yaml:"verify"`
79}
80
81type GlobalConfigSpec struct {
divyadesai19009132020-03-04 12:58:08 +000082 Server string `yaml:"server"`
83 Kafka string `yaml:"kafka"`
84 KvStore string `yaml:"kvstore"`
85 Tls TlsConfigSpec `yaml:"tls"`
86 Grpc GrpcConfigSpec `yaml:"grpc"`
87 KvStoreConfig KvStoreConfigSpec `yaml:"kvstoreconfig"`
88 K8sConfig string `yaml:"-"`
Zack Williamse940c7a2019-08-21 14:25:39 -070089}
90
91var (
92 ParamNames = map[string]map[string]string{
93 "v1": {
94 "ID": "voltha.ID",
95 },
96 "v2": {
97 "ID": "common.ID",
98 },
kesavand12cd8eb2020-01-20 22:25:22 -050099 "v3": {
Dinesh Belwalkarc9aa6d82020-03-04 15:22:17 -0800100 "ID": "common.ID",
101 "port": "voltha.Port",
102 "ValueSpecifier": "common.ValueSpecifier",
kesavand12cd8eb2020-01-20 22:25:22 -0500103 },
Zack Williamse940c7a2019-08-21 14:25:39 -0700104 }
105
106 CharReplacer = strings.NewReplacer("\\t", "\t", "\\n", "\n")
107
108 GlobalConfig = GlobalConfigSpec{
Scott Baker80126ab2020-06-04 11:49:07 -0700109 Server: "localhost:55555",
110 Kafka: "",
111 KvStore: "localhost:2379",
Zack Williamse940c7a2019-08-21 14:25:39 -0700112 Tls: TlsConfigSpec{
113 UseTls: false,
114 },
115 Grpc: GrpcConfigSpec{
serkant.uluderyad3daa902020-05-21 22:49:25 -0700116 Timeout: defaultGrpcTimeout,
117 MaxCallRecvMsgSize: defaultGrpcMaxCallRecvMsgSize,
divyadesai19009132020-03-04 12:58:08 +0000118 },
119 KvStoreConfig: KvStoreConfigSpec{
120 Timeout: defaultKvTimeout,
Zack Williamse940c7a2019-08-21 14:25:39 -0700121 },
122 }
123
David Bainbridgea6722342019-10-24 23:55:53 +0000124 GlobalCommandOptions = make(map[string]map[string]string)
125
Zack Williamse940c7a2019-08-21 14:25:39 -0700126 GlobalOptions struct {
divyadesai19009132020-03-04 12:58:08 +0000127 Config string `short:"c" long:"config" env:"VOLTCONFIG" value-name:"FILE" default:"" description:"Location of client config file"`
128 Server string `short:"s" long:"server" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of VOLTHA"`
129 Kafka string `short:"k" long:"kafka" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of Kafka"`
130 KvStore string `short:"e" long:"kvstore" env:"KVSTORE" value-name:"SERVER:PORT" description:"IP/Host and port of KV store (etcd)"`
131
David K. Bainbridge2b627612020-02-18 14:50:13 -0800132 // nolint: staticcheck
serkant.uluderyad3daa902020-05-21 22:49:25 -0700133 Debug bool `short:"d" long:"debug" description:"Enable debug mode"`
134 Timeout string `short:"t" long:"timeout" description:"API call timeout duration" value-name:"DURATION" default:""`
135 UseTLS bool `long:"tls" description:"Use TLS"`
136 CACert string `long:"tlscacert" value-name:"CA_CERT_FILE" description:"Trust certs signed only by this CA"`
137 Cert string `long:"tlscert" value-name:"CERT_FILE" description:"Path to TLS vertificate file"`
138 Key string `long:"tlskey" value-name:"KEY_FILE" description:"Path to TLS key file"`
139 Verify bool `long:"tlsverify" description:"Use TLS and verify the remote"`
140 K8sConfig string `short:"8" long:"k8sconfig" env:"KUBECONFIG" value-name:"FILE" default:"" description:"Location of Kubernetes config file"`
141 KvStoreTimeout string `long:"kvstoretimeout" env:"KVSTORE_TIMEOUT" value-name:"DURATION" default:"" description:"timeout for calls to KV store"`
142 CommandOptions string `short:"o" long:"command-options" env:"VOLTCTL_COMMAND_OPTIONS" value-name:"FILE" default:"" description:"Location of command options default configuration file"`
143 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 -0700144 }
David Bainbridgea6722342019-10-24 23:55:53 +0000145
146 Debug = log.New(os.Stdout, "DEBUG: ", 0)
147 Info = log.New(os.Stdout, "INFO: ", 0)
148 Warn = log.New(os.Stderr, "WARN: ", 0)
149 Error = log.New(os.Stderr, "ERROR: ", 0)
Zack Williamse940c7a2019-08-21 14:25:39 -0700150)
151
152type OutputOptions struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800153 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
154 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
155 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700156 OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
157 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
158}
159
160type ListOutputOptions struct {
161 OutputOptions
162 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
163 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
164}
165
166type OutputOptionsJson struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800167 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
168 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
169 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700170 OutputAs string `short:"o" long:"outputas" default:"json" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
171 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
172}
173
174type ListOutputOptionsJson struct {
175 OutputOptionsJson
176 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
177 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
178}
179
180func toOutputType(in string) OutputType {
181 switch in {
182 case "table":
183 fallthrough
184 default:
185 return OUTPUT_TABLE
186 case "json":
187 return OUTPUT_JSON
188 case "yaml":
189 return OUTPUT_YAML
190 }
191}
192
divyadesai19009132020-03-04 12:58:08 +0000193func splitEndpoint(ep, defaultHost string, defaultPort int) (string, int, error) {
194 port := defaultPort
195 host, sPort, err := net.SplitHostPort(ep)
196 if err != nil {
197 if addrErr, ok := err.(*net.AddrError); ok {
198 if addrErr.Err != "missing port in address" {
199 return "", 0, err
200 }
201 host = ep
202 } else {
203 return "", 0, err
204 }
205 } else if len(strings.TrimSpace(sPort)) > 0 {
206 val, err := strconv.Atoi(sPort)
207 if err != nil {
208 return "", 0, err
209 }
210 port = val
211 }
212 if len(strings.TrimSpace(host)) == 0 {
213 host = defaultHost
214 }
215 return strings.Trim(host, "]["), port, nil
216}
217
Zack Williamse940c7a2019-08-21 14:25:39 -0700218type CommandResult struct {
219 Format format.Format
220 Filter string
221 OrderBy string
222 OutputAs OutputType
223 NameLimit int
224 Data interface{}
225}
226
David Bainbridgea6722342019-10-24 23:55:53 +0000227func GetCommandOptionWithDefault(name, option, defaultValue string) string {
228 if cmd, ok := GlobalCommandOptions[name]; ok {
229 if val, ok := cmd[option]; ok {
230 return CharReplacer.Replace(val)
231 }
232 }
233 return defaultValue
234}
235
serkant.uluderyad3daa902020-05-21 22:49:25 -0700236var sizeParser = regexp.MustCompile(`^([0-9]+)([PETGMK]?)I?B?$`)
237
238func parseSize(size string) (uint64, error) {
239
240 parts := sizeParser.FindAllStringSubmatch(strings.ToUpper(size), -1)
241 if len(parts) == 0 {
242 return 0, fmt.Errorf("size: invalid size '%s'", size)
243 }
244 value, err := strconv.ParseUint(parts[0][1], 10, 64)
245 if err != nil {
246 return 0, fmt.Errorf("size: invalid size '%s'", size)
247 }
248 switch parts[0][2] {
249 case "E":
250 value = value * 1024 * 1024 * 1024 * 1024 * 1024 * 1024
251 case "P":
252 value = value * 1024 * 1024 * 1024 * 1024 * 1024
253 case "T":
254 value = value * 1024 * 1024 * 1024 * 1024
255 case "G":
256 value = value * 1024 * 1024 * 1024
257 case "M":
258 value = value * 1024 * 1024
259 case "K":
260 value = value * 1024
261 default:
262 }
263 return value, nil
264}
265
Zack Williamse940c7a2019-08-21 14:25:39 -0700266func ProcessGlobalOptions() {
267 if len(GlobalOptions.Config) == 0 {
268 home, err := os.UserHomeDir()
269 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000270 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700271 home = "~"
272 }
273 GlobalOptions.Config = filepath.Join(home, ".volt", "config")
274 }
275
David Bainbridgea6722342019-10-24 23:55:53 +0000276 if info, err := os.Stat(GlobalOptions.Config); err == nil && !info.IsDir() {
Zack Williamse940c7a2019-08-21 14:25:39 -0700277 configFile, err := ioutil.ReadFile(GlobalOptions.Config)
278 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000279 Error.Fatalf("Unable to read the configuration file '%s': %s",
280 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700281 }
David Bainbridgea6722342019-10-24 23:55:53 +0000282 if err = yaml.Unmarshal(configFile, &GlobalConfig); err != nil {
283 Error.Fatalf("Unable to parse the configuration file '%s': %s",
284 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700285 }
286 }
287
288 // Override from command line
289 if GlobalOptions.Server != "" {
290 GlobalConfig.Server = GlobalOptions.Server
291 }
divyadesai19009132020-03-04 12:58:08 +0000292 host, port, err := splitEndpoint(GlobalConfig.Server, defaultApiHost, defaultApiPort)
293 if err != nil {
294 Error.Fatalf("voltha API endport incorrectly specified '%s':%s",
295 GlobalConfig.Server, err)
296 }
297 GlobalConfig.Server = net.JoinHostPort(host, strconv.Itoa(port))
298
Scott Bakered4efab2020-01-13 19:12:25 -0800299 if GlobalOptions.Kafka != "" {
300 GlobalConfig.Kafka = GlobalOptions.Kafka
301 }
divyadesai19009132020-03-04 12:58:08 +0000302 host, port, err = splitEndpoint(GlobalConfig.Kafka, defaultKafkaHost, defaultKafkaPort)
303 if err != nil {
304 Error.Fatalf("Kafka endport incorrectly specified '%s':%s",
305 GlobalConfig.Kafka, err)
306 }
307 GlobalConfig.Kafka = net.JoinHostPort(host, strconv.Itoa(port))
308
309 if GlobalOptions.KvStore != "" {
310 GlobalConfig.KvStore = GlobalOptions.KvStore
311 }
312 host, port, err = splitEndpoint(GlobalConfig.KvStore, defaultKvHost, defaultKvPort)
313 if err != nil {
314 Error.Fatalf("KV store endport incorrectly specified '%s':%s",
315 GlobalConfig.KvStore, err)
316 }
317 GlobalConfig.KvStore = net.JoinHostPort(host, strconv.Itoa(port))
318
divyadesai19009132020-03-04 12:58:08 +0000319 if GlobalOptions.KvStoreTimeout != "" {
320 timeout, err := time.ParseDuration(GlobalOptions.KvStoreTimeout)
321 if err != nil {
322 Error.Fatalf("Unable to parse specified KV strore timeout duration '%s': %s",
323 GlobalOptions.KvStoreTimeout, err.Error())
324 }
325 GlobalConfig.KvStoreConfig.Timeout = timeout
326 }
327
David K. Bainbridge402f8482020-02-26 17:14:46 -0800328 if GlobalOptions.Timeout != "" {
329 timeout, err := time.ParseDuration(GlobalOptions.Timeout)
330 if err != nil {
331 Error.Fatalf("Unable to parse specified timeout duration '%s': %s",
332 GlobalOptions.Timeout, err.Error())
333 }
334 GlobalConfig.Grpc.Timeout = timeout
335 }
336
serkant.uluderyad3daa902020-05-21 22:49:25 -0700337 if GlobalOptions.MaxCallRecvMsgSize != "" {
338 GlobalConfig.Grpc.MaxCallRecvMsgSize = GlobalOptions.MaxCallRecvMsgSize
339 }
340
Zack Williamse940c7a2019-08-21 14:25:39 -0700341 // If a k8s cert/key were not specified, then attempt to read it from
342 // any $HOME/.kube/config if it exists
343 if len(GlobalOptions.K8sConfig) == 0 {
344 home, err := os.UserHomeDir()
345 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000346 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700347 home = "~"
348 }
349 GlobalOptions.K8sConfig = filepath.Join(home, ".kube", "config")
350 }
David Bainbridgea6722342019-10-24 23:55:53 +0000351
352 if len(GlobalOptions.CommandOptions) == 0 {
353 home, err := os.UserHomeDir()
354 if err != nil {
355 Warn.Printf("Unable to discover the user's home directory: %s", err)
356 home = "~"
357 }
358 GlobalOptions.CommandOptions = filepath.Join(home, ".volt", "command_options")
359 }
360
361 if info, err := os.Stat(GlobalOptions.CommandOptions); err == nil && !info.IsDir() {
362 optionsFile, err := ioutil.ReadFile(GlobalOptions.CommandOptions)
363 if err != nil {
364 Error.Fatalf("Unable to read command options configuration file '%s' : %s",
365 GlobalOptions.CommandOptions, err.Error())
366 }
367 if err = yaml.Unmarshal(optionsFile, &GlobalCommandOptions); err != nil {
368 Error.Fatalf("Unable to parse the command line options configuration file '%s': %s",
369 GlobalOptions.CommandOptions, err.Error())
370 }
371 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700372}
373
374func NewConnection() (*grpc.ClientConn, error) {
375 ProcessGlobalOptions()
serkant.uluderyad3daa902020-05-21 22:49:25 -0700376
377 // convert grpc.msgSize into bytes
378 n, err := parseSize(GlobalConfig.Grpc.MaxCallRecvMsgSize)
379 if err != nil {
380 Error.Fatalf("Cannot convert msgSize %s to bytes", GlobalConfig.Grpc.MaxCallRecvMsgSize)
381 }
382
383 return grpc.Dial(GlobalConfig.Server, grpc.WithInsecure(), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(n))))
Zack Williamse940c7a2019-08-21 14:25:39 -0700384}
385
Scott Baker9173ed82020-05-19 08:30:12 -0700386func ConvertJsonProtobufArray(data_in interface{}) (string, error) {
387 result := ""
388
389 slice := reflect.ValueOf(data_in)
390 if slice.Kind() != reflect.Slice {
391 return "", errors.New("Not a slice")
392 }
393
394 result = result + "["
395
396 marshaler := jsonpb.Marshaler{EmitDefaults: true}
397 for i := 0; i < slice.Len(); i++ {
398 item := slice.Index(i).Interface()
399 protoMessage, okay := item.(proto.Message)
400 if !okay {
401 return "", errors.New("Failed to convert item to a proto.Message")
402 }
403 asJson, err := marshaler.MarshalToString(protoMessage)
404 if err != nil {
405 return "", fmt.Errorf("Failed to marshal the json: %s", err)
406 }
407
408 result = result + asJson
409
410 if i < slice.Len()-1 {
411 result = result + ","
412 }
413 }
414
415 result = result + "]"
416
417 return result, nil
418}
419
Zack Williamse940c7a2019-08-21 14:25:39 -0700420func GenerateOutput(result *CommandResult) {
421 if result != nil && result.Data != nil {
422 data := result.Data
423 if result.Filter != "" {
424 f, err := filter.Parse(result.Filter)
425 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000426 Error.Fatalf("Unable to parse specified output filter '%s': %s", result.Filter, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700427 }
428 data, err = f.Process(data)
429 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000430 Error.Fatalf("Unexpected error while filtering command results: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700431 }
432 }
433 if result.OrderBy != "" {
434 s, err := order.Parse(result.OrderBy)
435 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000436 Error.Fatalf("Unable to parse specified sort specification '%s': %s", result.OrderBy, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700437 }
438 data, err = s.Process(data)
439 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000440 Error.Fatalf("Unexpected error while sorting command result: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700441 }
442 }
443 if result.OutputAs == OUTPUT_TABLE {
444 tableFormat := format.Format(result.Format)
David Bainbridge12f036f2019-10-15 22:09:04 +0000445 if err := tableFormat.Execute(os.Stdout, true, result.NameLimit, data); err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000446 Error.Fatalf("Unexpected error while attempting to format results as table : %s", err.Error())
David Bainbridge12f036f2019-10-15 22:09:04 +0000447 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700448 } else if result.OutputAs == OUTPUT_JSON {
Scott Baker9173ed82020-05-19 08:30:12 -0700449 // first try to convert it as an array of protobufs
450 asJson, err := ConvertJsonProtobufArray(data)
Zack Williamse940c7a2019-08-21 14:25:39 -0700451 if err != nil {
Scott Baker9173ed82020-05-19 08:30:12 -0700452 // if that fails, then just do a standard json conversion
453 asJsonB, err := json.Marshal(&data)
454 if err != nil {
455 Error.Fatalf("Unexpected error while processing command results to JSON: %s", err.Error())
456 }
457 asJson = string(asJsonB)
Zack Williamse940c7a2019-08-21 14:25:39 -0700458 }
459 fmt.Printf("%s", asJson)
460 } else if result.OutputAs == OUTPUT_YAML {
461 asYaml, err := yaml.Marshal(&data)
462 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000463 Error.Fatalf("Unexpected error while processing command results to YAML: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700464 }
465 fmt.Printf("%s", asYaml)
466 }
467 }
468}