blob: 9330b0c4af8fead9beba2278b70b032d82a1948f [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"
20 "fmt"
Scott Baker2b0ad652019-08-21 14:57:07 -070021 "github.com/opencord/voltctl/pkg/filter"
22 "github.com/opencord/voltctl/pkg/format"
23 "github.com/opencord/voltctl/pkg/order"
Zack Williamse940c7a2019-08-21 14:25:39 -070024 "google.golang.org/grpc"
25 "gopkg.in/yaml.v2"
26 "io/ioutil"
27 "log"
divyadesai19009132020-03-04 12:58:08 +000028 "net"
Zack Williamse940c7a2019-08-21 14:25:39 -070029 "os"
30 "path/filepath"
divyadesai19009132020-03-04 12:58:08 +000031 "strconv"
Zack Williamse940c7a2019-08-21 14:25:39 -070032 "strings"
33 "time"
34)
35
36type OutputType uint8
37
38const (
39 OUTPUT_TABLE OutputType = iota
40 OUTPUT_JSON
41 OUTPUT_YAML
divyadesai19009132020-03-04 12:58:08 +000042
43 defaultApiHost = "localhost"
44 defaultApiPort = 55555
45
46 defaultKafkaHost = "localhost"
47 defaultKafkaPort = 9092
48
49 supportedKvStoreType = "etcd"
50 defaultKvHost = "localhost"
51 defaultKvPort = 2379
52 defaultKvTimeout = time.Second * 5
53
54 defaultGrpcTimeout = time.Minute * 5
Zack Williamse940c7a2019-08-21 14:25:39 -070055)
56
57type GrpcConfigSpec struct {
58 Timeout time.Duration `yaml:"timeout"`
59}
60
divyadesai19009132020-03-04 12:58:08 +000061type KvStoreConfigSpec struct {
62 Timeout time.Duration `yaml:"timeout"`
63}
64
Zack Williamse940c7a2019-08-21 14:25:39 -070065type TlsConfigSpec struct {
66 UseTls bool `yaml:"useTls"`
67 CACert string `yaml:"caCert"`
68 Cert string `yaml:"cert"`
69 Key string `yaml:"key"`
70 Verify string `yaml:"verify"`
71}
72
73type GlobalConfigSpec struct {
divyadesai19009132020-03-04 12:58:08 +000074 ApiVersion string `yaml:"apiVersion"`
75 Server string `yaml:"server"`
76 Kafka string `yaml:"kafka"`
77 KvStore string `yaml:"kvstore"`
78 Tls TlsConfigSpec `yaml:"tls"`
79 Grpc GrpcConfigSpec `yaml:"grpc"`
80 KvStoreConfig KvStoreConfigSpec `yaml:"kvstoreconfig"`
81 K8sConfig string `yaml:"-"`
Zack Williamse940c7a2019-08-21 14:25:39 -070082}
83
84var (
85 ParamNames = map[string]map[string]string{
86 "v1": {
87 "ID": "voltha.ID",
88 },
89 "v2": {
90 "ID": "common.ID",
91 },
kesavand12cd8eb2020-01-20 22:25:22 -050092 "v3": {
Dinesh Belwalkarc9aa6d82020-03-04 15:22:17 -080093 "ID": "common.ID",
94 "port": "voltha.Port",
95 "ValueSpecifier": "common.ValueSpecifier",
kesavand12cd8eb2020-01-20 22:25:22 -050096 },
Zack Williamse940c7a2019-08-21 14:25:39 -070097 }
98
99 CharReplacer = strings.NewReplacer("\\t", "\t", "\\n", "\n")
100
101 GlobalConfig = GlobalConfigSpec{
kesavand12cd8eb2020-01-20 22:25:22 -0500102 ApiVersion: "v3",
David Bainbridge0f758d42019-10-26 05:17:48 +0000103 Server: "localhost:55555",
Scott Bakered4efab2020-01-13 19:12:25 -0800104 Kafka: "",
divyadesai19009132020-03-04 12:58:08 +0000105 KvStore: "localhost:2379",
Zack Williamse940c7a2019-08-21 14:25:39 -0700106 Tls: TlsConfigSpec{
107 UseTls: false,
108 },
109 Grpc: GrpcConfigSpec{
divyadesai19009132020-03-04 12:58:08 +0000110 Timeout: defaultGrpcTimeout,
111 },
112 KvStoreConfig: KvStoreConfigSpec{
113 Timeout: defaultKvTimeout,
Zack Williamse940c7a2019-08-21 14:25:39 -0700114 },
115 }
116
David Bainbridgea6722342019-10-24 23:55:53 +0000117 GlobalCommandOptions = make(map[string]map[string]string)
118
Zack Williamse940c7a2019-08-21 14:25:39 -0700119 GlobalOptions struct {
divyadesai19009132020-03-04 12:58:08 +0000120 Config string `short:"c" long:"config" env:"VOLTCONFIG" value-name:"FILE" default:"" description:"Location of client config file"`
121 Server string `short:"s" long:"server" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of VOLTHA"`
122 Kafka string `short:"k" long:"kafka" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of Kafka"`
123 KvStore string `short:"e" long:"kvstore" env:"KVSTORE" value-name:"SERVER:PORT" description:"IP/Host and port of KV store (etcd)"`
124
David Bainbridgec4029aa2019-09-26 18:56:39 +0000125 // Do not set the default for the API version here, else it will override the value read in the config
David K. Bainbridge2b627612020-02-18 14:50:13 -0800126 // nolint: staticcheck
kesavand12cd8eb2020-01-20 22:25:22 -0500127 ApiVersion string `short:"a" long:"apiversion" description:"API version" value-name:"VERSION" choice:"v1" choice:"v2" choice:"v3"`
David Bainbridgea6722342019-10-24 23:55:53 +0000128 Debug bool `short:"d" long:"debug" description:"Enable debug mode"`
David K. Bainbridge402f8482020-02-26 17:14:46 -0800129 Timeout string `short:"t" long:"timeout" description:"API call timeout duration" value-name:"DURATION" default:""`
David Bainbridgea6722342019-10-24 23:55:53 +0000130 UseTLS bool `long:"tls" description:"Use TLS"`
131 CACert string `long:"tlscacert" value-name:"CA_CERT_FILE" description:"Trust certs signed only by this CA"`
132 Cert string `long:"tlscert" value-name:"CERT_FILE" description:"Path to TLS vertificate file"`
133 Key string `long:"tlskey" value-name:"KEY_FILE" description:"Path to TLS key file"`
134 Verify bool `long:"tlsverify" description:"Use TLS and verify the remote"`
135 K8sConfig string `short:"8" long:"k8sconfig" env:"KUBECONFIG" value-name:"FILE" default:"" description:"Location of Kubernetes config file"`
divyadesai19009132020-03-04 12:58:08 +0000136 KvStoreTimeout string `long:"kvstoretimeout" env:"KVSTORE_TIMEOUT" value-name:"DURATION" default:"" description:"timeout for calls to KV store"`
David Bainbridgea6722342019-10-24 23:55:53 +0000137 CommandOptions string `short:"o" long:"command-options" env:"VOLTCTL_COMMAND_OPTIONS" value-name:"FILE" default:"" description:"Location of command options default configuration file"`
Zack Williamse940c7a2019-08-21 14:25:39 -0700138 }
David Bainbridgea6722342019-10-24 23:55:53 +0000139
140 Debug = log.New(os.Stdout, "DEBUG: ", 0)
141 Info = log.New(os.Stdout, "INFO: ", 0)
142 Warn = log.New(os.Stderr, "WARN: ", 0)
143 Error = log.New(os.Stderr, "ERROR: ", 0)
Zack Williamse940c7a2019-08-21 14:25:39 -0700144)
145
146type OutputOptions struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800147 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
148 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
149 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700150 OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
151 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
152}
153
154type ListOutputOptions struct {
155 OutputOptions
156 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
157 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
158}
159
160type OutputOptionsJson struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800161 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
162 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
163 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700164 OutputAs string `short:"o" long:"outputas" default:"json" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
165 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
166}
167
168type ListOutputOptionsJson struct {
169 OutputOptionsJson
170 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
171 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
172}
173
174func toOutputType(in string) OutputType {
175 switch in {
176 case "table":
177 fallthrough
178 default:
179 return OUTPUT_TABLE
180 case "json":
181 return OUTPUT_JSON
182 case "yaml":
183 return OUTPUT_YAML
184 }
185}
186
divyadesai19009132020-03-04 12:58:08 +0000187func splitEndpoint(ep, defaultHost string, defaultPort int) (string, int, error) {
188 port := defaultPort
189 host, sPort, err := net.SplitHostPort(ep)
190 if err != nil {
191 if addrErr, ok := err.(*net.AddrError); ok {
192 if addrErr.Err != "missing port in address" {
193 return "", 0, err
194 }
195 host = ep
196 } else {
197 return "", 0, err
198 }
199 } else if len(strings.TrimSpace(sPort)) > 0 {
200 val, err := strconv.Atoi(sPort)
201 if err != nil {
202 return "", 0, err
203 }
204 port = val
205 }
206 if len(strings.TrimSpace(host)) == 0 {
207 host = defaultHost
208 }
209 return strings.Trim(host, "]["), port, nil
210}
211
Zack Williamse940c7a2019-08-21 14:25:39 -0700212type CommandResult struct {
213 Format format.Format
214 Filter string
215 OrderBy string
216 OutputAs OutputType
217 NameLimit int
218 Data interface{}
219}
220
David Bainbridgea6722342019-10-24 23:55:53 +0000221func GetCommandOptionWithDefault(name, option, defaultValue string) string {
222 if cmd, ok := GlobalCommandOptions[name]; ok {
223 if val, ok := cmd[option]; ok {
224 return CharReplacer.Replace(val)
225 }
226 }
227 return defaultValue
228}
229
Zack Williamse940c7a2019-08-21 14:25:39 -0700230func ProcessGlobalOptions() {
231 if len(GlobalOptions.Config) == 0 {
232 home, err := os.UserHomeDir()
233 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000234 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700235 home = "~"
236 }
237 GlobalOptions.Config = filepath.Join(home, ".volt", "config")
238 }
239
David Bainbridgea6722342019-10-24 23:55:53 +0000240 if info, err := os.Stat(GlobalOptions.Config); err == nil && !info.IsDir() {
Zack Williamse940c7a2019-08-21 14:25:39 -0700241 configFile, err := ioutil.ReadFile(GlobalOptions.Config)
242 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000243 Error.Fatalf("Unable to read the configuration file '%s': %s",
244 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700245 }
David Bainbridgea6722342019-10-24 23:55:53 +0000246 if err = yaml.Unmarshal(configFile, &GlobalConfig); err != nil {
247 Error.Fatalf("Unable to parse the configuration file '%s': %s",
248 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700249 }
250 }
251
252 // Override from command line
253 if GlobalOptions.Server != "" {
254 GlobalConfig.Server = GlobalOptions.Server
255 }
divyadesai19009132020-03-04 12:58:08 +0000256 host, port, err := splitEndpoint(GlobalConfig.Server, defaultApiHost, defaultApiPort)
257 if err != nil {
258 Error.Fatalf("voltha API endport incorrectly specified '%s':%s",
259 GlobalConfig.Server, err)
260 }
261 GlobalConfig.Server = net.JoinHostPort(host, strconv.Itoa(port))
262
Scott Bakered4efab2020-01-13 19:12:25 -0800263 if GlobalOptions.Kafka != "" {
264 GlobalConfig.Kafka = GlobalOptions.Kafka
265 }
divyadesai19009132020-03-04 12:58:08 +0000266 host, port, err = splitEndpoint(GlobalConfig.Kafka, defaultKafkaHost, defaultKafkaPort)
267 if err != nil {
268 Error.Fatalf("Kafka endport incorrectly specified '%s':%s",
269 GlobalConfig.Kafka, err)
270 }
271 GlobalConfig.Kafka = net.JoinHostPort(host, strconv.Itoa(port))
272
273 if GlobalOptions.KvStore != "" {
274 GlobalConfig.KvStore = GlobalOptions.KvStore
275 }
276 host, port, err = splitEndpoint(GlobalConfig.KvStore, defaultKvHost, defaultKvPort)
277 if err != nil {
278 Error.Fatalf("KV store endport incorrectly specified '%s':%s",
279 GlobalConfig.KvStore, err)
280 }
281 GlobalConfig.KvStore = net.JoinHostPort(host, strconv.Itoa(port))
282
Zack Williamse940c7a2019-08-21 14:25:39 -0700283 if GlobalOptions.ApiVersion != "" {
284 GlobalConfig.ApiVersion = GlobalOptions.ApiVersion
285 }
286
divyadesai19009132020-03-04 12:58:08 +0000287 if GlobalOptions.KvStoreTimeout != "" {
288 timeout, err := time.ParseDuration(GlobalOptions.KvStoreTimeout)
289 if err != nil {
290 Error.Fatalf("Unable to parse specified KV strore timeout duration '%s': %s",
291 GlobalOptions.KvStoreTimeout, err.Error())
292 }
293 GlobalConfig.KvStoreConfig.Timeout = timeout
294 }
295
David K. Bainbridge402f8482020-02-26 17:14:46 -0800296 if GlobalOptions.Timeout != "" {
297 timeout, err := time.ParseDuration(GlobalOptions.Timeout)
298 if err != nil {
299 Error.Fatalf("Unable to parse specified timeout duration '%s': %s",
300 GlobalOptions.Timeout, err.Error())
301 }
302 GlobalConfig.Grpc.Timeout = timeout
303 }
304
Zack Williamse940c7a2019-08-21 14:25:39 -0700305 // If a k8s cert/key were not specified, then attempt to read it from
306 // any $HOME/.kube/config if it exists
307 if len(GlobalOptions.K8sConfig) == 0 {
308 home, err := os.UserHomeDir()
309 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000310 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700311 home = "~"
312 }
313 GlobalOptions.K8sConfig = filepath.Join(home, ".kube", "config")
314 }
David Bainbridgea6722342019-10-24 23:55:53 +0000315
316 if len(GlobalOptions.CommandOptions) == 0 {
317 home, err := os.UserHomeDir()
318 if err != nil {
319 Warn.Printf("Unable to discover the user's home directory: %s", err)
320 home = "~"
321 }
322 GlobalOptions.CommandOptions = filepath.Join(home, ".volt", "command_options")
323 }
324
325 if info, err := os.Stat(GlobalOptions.CommandOptions); err == nil && !info.IsDir() {
326 optionsFile, err := ioutil.ReadFile(GlobalOptions.CommandOptions)
327 if err != nil {
328 Error.Fatalf("Unable to read command options configuration file '%s' : %s",
329 GlobalOptions.CommandOptions, err.Error())
330 }
331 if err = yaml.Unmarshal(optionsFile, &GlobalCommandOptions); err != nil {
332 Error.Fatalf("Unable to parse the command line options configuration file '%s': %s",
333 GlobalOptions.CommandOptions, err.Error())
334 }
335 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700336}
337
338func NewConnection() (*grpc.ClientConn, error) {
339 ProcessGlobalOptions()
340 return grpc.Dial(GlobalConfig.Server, grpc.WithInsecure())
341}
342
343func GenerateOutput(result *CommandResult) {
344 if result != nil && result.Data != nil {
345 data := result.Data
346 if result.Filter != "" {
347 f, err := filter.Parse(result.Filter)
348 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000349 Error.Fatalf("Unable to parse specified output filter '%s': %s", result.Filter, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700350 }
351 data, err = f.Process(data)
352 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000353 Error.Fatalf("Unexpected error while filtering command results: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700354 }
355 }
356 if result.OrderBy != "" {
357 s, err := order.Parse(result.OrderBy)
358 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000359 Error.Fatalf("Unable to parse specified sort specification '%s': %s", result.OrderBy, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700360 }
361 data, err = s.Process(data)
362 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000363 Error.Fatalf("Unexpected error while sorting command result: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700364 }
365 }
366 if result.OutputAs == OUTPUT_TABLE {
367 tableFormat := format.Format(result.Format)
David Bainbridge12f036f2019-10-15 22:09:04 +0000368 if err := tableFormat.Execute(os.Stdout, true, result.NameLimit, data); err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000369 Error.Fatalf("Unexpected error while attempting to format results as table : %s", err.Error())
David Bainbridge12f036f2019-10-15 22:09:04 +0000370 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700371 } else if result.OutputAs == OUTPUT_JSON {
372 asJson, err := json.Marshal(&data)
373 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000374 Error.Fatalf("Unexpected error while processing command results to JSON: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700375 }
376 fmt.Printf("%s", asJson)
377 } else if result.OutputAs == OUTPUT_YAML {
378 asYaml, err := yaml.Marshal(&data)
379 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000380 Error.Fatalf("Unexpected error while processing command results to YAML: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700381 }
382 fmt.Printf("%s", asYaml)
383 }
384 }
385}