blob: d839907a471c3e3e079dfbd6f6291e8c6a13d8d7 [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"
28 "os"
29 "path/filepath"
30 "strings"
31 "time"
32)
33
34type OutputType uint8
35
36const (
37 OUTPUT_TABLE OutputType = iota
38 OUTPUT_JSON
39 OUTPUT_YAML
40)
41
42type GrpcConfigSpec struct {
43 Timeout time.Duration `yaml:"timeout"`
44}
45
46type TlsConfigSpec struct {
47 UseTls bool `yaml:"useTls"`
48 CACert string `yaml:"caCert"`
49 Cert string `yaml:"cert"`
50 Key string `yaml:"key"`
51 Verify string `yaml:"verify"`
52}
53
54type GlobalConfigSpec struct {
55 ApiVersion string `yaml:"apiVersion"`
56 Server string `yaml:"server"`
Scott Bakered4efab2020-01-13 19:12:25 -080057 Kafka string `yaml:"kafka"`
Zack Williamse940c7a2019-08-21 14:25:39 -070058 Tls TlsConfigSpec `yaml:"tls"`
59 Grpc GrpcConfigSpec `yaml:"grpc"`
60 K8sConfig string `yaml:"-"`
61}
62
63var (
64 ParamNames = map[string]map[string]string{
65 "v1": {
66 "ID": "voltha.ID",
67 },
68 "v2": {
69 "ID": "common.ID",
70 },
kesavand12cd8eb2020-01-20 22:25:22 -050071 "v3": {
72 "ID": "common.ID",
73 "port": "voltha.Port",
74 },
Zack Williamse940c7a2019-08-21 14:25:39 -070075 }
76
77 CharReplacer = strings.NewReplacer("\\t", "\t", "\\n", "\n")
78
79 GlobalConfig = GlobalConfigSpec{
kesavand12cd8eb2020-01-20 22:25:22 -050080 ApiVersion: "v3",
David Bainbridge0f758d42019-10-26 05:17:48 +000081 Server: "localhost:55555",
Scott Bakered4efab2020-01-13 19:12:25 -080082 Kafka: "",
Zack Williamse940c7a2019-08-21 14:25:39 -070083 Tls: TlsConfigSpec{
84 UseTls: false,
85 },
86 Grpc: GrpcConfigSpec{
87 Timeout: time.Second * 10,
88 },
89 }
90
David Bainbridgea6722342019-10-24 23:55:53 +000091 GlobalCommandOptions = make(map[string]map[string]string)
92
Zack Williamse940c7a2019-08-21 14:25:39 -070093 GlobalOptions struct {
David Bainbridgec4029aa2019-09-26 18:56:39 +000094 Config string `short:"c" long:"config" env:"VOLTCONFIG" value-name:"FILE" default:"" description:"Location of client config file"`
95 Server string `short:"s" long:"server" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of VOLTHA"`
Scott Bakered4efab2020-01-13 19:12:25 -080096 Kafka string `short:"k" long:"kafka" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of Kafka"`
David Bainbridgec4029aa2019-09-26 18:56:39 +000097 // 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 -080098 // nolint: staticcheck
kesavand12cd8eb2020-01-20 22:25:22 -050099 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 +0000100 Debug bool `short:"d" long:"debug" description:"Enable debug mode"`
101 UseTLS bool `long:"tls" description:"Use TLS"`
102 CACert string `long:"tlscacert" value-name:"CA_CERT_FILE" description:"Trust certs signed only by this CA"`
103 Cert string `long:"tlscert" value-name:"CERT_FILE" description:"Path to TLS vertificate file"`
104 Key string `long:"tlskey" value-name:"KEY_FILE" description:"Path to TLS key file"`
105 Verify bool `long:"tlsverify" description:"Use TLS and verify the remote"`
106 K8sConfig string `short:"8" long:"k8sconfig" env:"KUBECONFIG" value-name:"FILE" default:"" description:"Location of Kubernetes config file"`
107 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 -0700108 }
David Bainbridgea6722342019-10-24 23:55:53 +0000109
110 Debug = log.New(os.Stdout, "DEBUG: ", 0)
111 Info = log.New(os.Stdout, "INFO: ", 0)
112 Warn = log.New(os.Stderr, "WARN: ", 0)
113 Error = log.New(os.Stderr, "ERROR: ", 0)
Zack Williamse940c7a2019-08-21 14:25:39 -0700114)
115
116type OutputOptions struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800117 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
118 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
119 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700120 OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
121 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
122}
123
124type ListOutputOptions struct {
125 OutputOptions
126 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
127 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
128}
129
130type OutputOptionsJson struct {
David K. Bainbridge2b627612020-02-18 14:50:13 -0800131 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
132 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
133 // nolint: staticcheck
Zack Williamse940c7a2019-08-21 14:25:39 -0700134 OutputAs string `short:"o" long:"outputas" default:"json" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
135 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
136}
137
138type ListOutputOptionsJson struct {
139 OutputOptionsJson
140 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
141 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
142}
143
144func toOutputType(in string) OutputType {
145 switch in {
146 case "table":
147 fallthrough
148 default:
149 return OUTPUT_TABLE
150 case "json":
151 return OUTPUT_JSON
152 case "yaml":
153 return OUTPUT_YAML
154 }
155}
156
157type CommandResult struct {
158 Format format.Format
159 Filter string
160 OrderBy string
161 OutputAs OutputType
162 NameLimit int
163 Data interface{}
164}
165
David Bainbridgea6722342019-10-24 23:55:53 +0000166func GetCommandOptionWithDefault(name, option, defaultValue string) string {
167 if cmd, ok := GlobalCommandOptions[name]; ok {
168 if val, ok := cmd[option]; ok {
169 return CharReplacer.Replace(val)
170 }
171 }
172 return defaultValue
173}
174
Zack Williamse940c7a2019-08-21 14:25:39 -0700175func ProcessGlobalOptions() {
176 if len(GlobalOptions.Config) == 0 {
177 home, err := os.UserHomeDir()
178 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000179 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700180 home = "~"
181 }
182 GlobalOptions.Config = filepath.Join(home, ".volt", "config")
183 }
184
David Bainbridgea6722342019-10-24 23:55:53 +0000185 if info, err := os.Stat(GlobalOptions.Config); err == nil && !info.IsDir() {
Zack Williamse940c7a2019-08-21 14:25:39 -0700186 configFile, err := ioutil.ReadFile(GlobalOptions.Config)
187 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000188 Error.Fatalf("Unable to read the configuration file '%s': %s",
189 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700190 }
David Bainbridgea6722342019-10-24 23:55:53 +0000191 if err = yaml.Unmarshal(configFile, &GlobalConfig); err != nil {
192 Error.Fatalf("Unable to parse the configuration file '%s': %s",
193 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700194 }
195 }
196
197 // Override from command line
198 if GlobalOptions.Server != "" {
199 GlobalConfig.Server = GlobalOptions.Server
200 }
Scott Bakered4efab2020-01-13 19:12:25 -0800201 if GlobalOptions.Kafka != "" {
202 GlobalConfig.Kafka = GlobalOptions.Kafka
203 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700204 if GlobalOptions.ApiVersion != "" {
205 GlobalConfig.ApiVersion = GlobalOptions.ApiVersion
206 }
207
208 // If a k8s cert/key were not specified, then attempt to read it from
209 // any $HOME/.kube/config if it exists
210 if len(GlobalOptions.K8sConfig) == 0 {
211 home, err := os.UserHomeDir()
212 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000213 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700214 home = "~"
215 }
216 GlobalOptions.K8sConfig = filepath.Join(home, ".kube", "config")
217 }
David Bainbridgea6722342019-10-24 23:55:53 +0000218
219 if len(GlobalOptions.CommandOptions) == 0 {
220 home, err := os.UserHomeDir()
221 if err != nil {
222 Warn.Printf("Unable to discover the user's home directory: %s", err)
223 home = "~"
224 }
225 GlobalOptions.CommandOptions = filepath.Join(home, ".volt", "command_options")
226 }
227
228 if info, err := os.Stat(GlobalOptions.CommandOptions); err == nil && !info.IsDir() {
229 optionsFile, err := ioutil.ReadFile(GlobalOptions.CommandOptions)
230 if err != nil {
231 Error.Fatalf("Unable to read command options configuration file '%s' : %s",
232 GlobalOptions.CommandOptions, err.Error())
233 }
234 if err = yaml.Unmarshal(optionsFile, &GlobalCommandOptions); err != nil {
235 Error.Fatalf("Unable to parse the command line options configuration file '%s': %s",
236 GlobalOptions.CommandOptions, err.Error())
237 }
238 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700239}
240
241func NewConnection() (*grpc.ClientConn, error) {
242 ProcessGlobalOptions()
243 return grpc.Dial(GlobalConfig.Server, grpc.WithInsecure())
244}
245
246func GenerateOutput(result *CommandResult) {
247 if result != nil && result.Data != nil {
248 data := result.Data
249 if result.Filter != "" {
250 f, err := filter.Parse(result.Filter)
251 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000252 Error.Fatalf("Unable to parse specified output filter '%s': %s", result.Filter, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700253 }
254 data, err = f.Process(data)
255 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000256 Error.Fatalf("Unexpected error while filtering command results: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700257 }
258 }
259 if result.OrderBy != "" {
260 s, err := order.Parse(result.OrderBy)
261 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000262 Error.Fatalf("Unable to parse specified sort specification '%s': %s", result.OrderBy, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700263 }
264 data, err = s.Process(data)
265 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000266 Error.Fatalf("Unexpected error while sorting command result: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700267 }
268 }
269 if result.OutputAs == OUTPUT_TABLE {
270 tableFormat := format.Format(result.Format)
David Bainbridge12f036f2019-10-15 22:09:04 +0000271 if err := tableFormat.Execute(os.Stdout, true, result.NameLimit, data); err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000272 Error.Fatalf("Unexpected error while attempting to format results as table : %s", err.Error())
David Bainbridge12f036f2019-10-15 22:09:04 +0000273 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700274 } else if result.OutputAs == OUTPUT_JSON {
275 asJson, err := json.Marshal(&data)
276 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000277 Error.Fatalf("Unexpected error while processing command results to JSON: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700278 }
279 fmt.Printf("%s", asJson)
280 } else if result.OutputAs == OUTPUT_YAML {
281 asYaml, err := yaml.Marshal(&data)
282 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000283 Error.Fatalf("Unexpected error while processing command results to YAML: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700284 }
285 fmt.Printf("%s", asYaml)
286 }
287 }
288}