blob: 7972b8f46c7ea5c887a0756d348611bd08b497af [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"`
57 Tls TlsConfigSpec `yaml:"tls"`
58 Grpc GrpcConfigSpec `yaml:"grpc"`
59 K8sConfig string `yaml:"-"`
60}
61
62var (
63 ParamNames = map[string]map[string]string{
64 "v1": {
65 "ID": "voltha.ID",
66 },
67 "v2": {
68 "ID": "common.ID",
69 },
70 }
71
72 CharReplacer = strings.NewReplacer("\\t", "\t", "\\n", "\n")
73
74 GlobalConfig = GlobalConfigSpec{
David Bainbridgec4029aa2019-09-26 18:56:39 +000075 ApiVersion: "v2",
David Bainbridge0f758d42019-10-26 05:17:48 +000076 Server: "localhost:55555",
Zack Williamse940c7a2019-08-21 14:25:39 -070077 Tls: TlsConfigSpec{
78 UseTls: false,
79 },
80 Grpc: GrpcConfigSpec{
81 Timeout: time.Second * 10,
82 },
83 }
84
David Bainbridgea6722342019-10-24 23:55:53 +000085 GlobalCommandOptions = make(map[string]map[string]string)
86
Zack Williamse940c7a2019-08-21 14:25:39 -070087 GlobalOptions struct {
David Bainbridgec4029aa2019-09-26 18:56:39 +000088 Config string `short:"c" long:"config" env:"VOLTCONFIG" value-name:"FILE" default:"" description:"Location of client config file"`
89 Server string `short:"s" long:"server" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of VOLTHA"`
90 // Do not set the default for the API version here, else it will override the value read in the config
David Bainbridgea6722342019-10-24 23:55:53 +000091 ApiVersion string `short:"a" long:"apiversion" description:"API version" value-name:"VERSION" choice:"v1" choice:"v2"`
92 Debug bool `short:"d" long:"debug" description:"Enable debug mode"`
93 UseTLS bool `long:"tls" description:"Use TLS"`
94 CACert string `long:"tlscacert" value-name:"CA_CERT_FILE" description:"Trust certs signed only by this CA"`
95 Cert string `long:"tlscert" value-name:"CERT_FILE" description:"Path to TLS vertificate file"`
96 Key string `long:"tlskey" value-name:"KEY_FILE" description:"Path to TLS key file"`
97 Verify bool `long:"tlsverify" description:"Use TLS and verify the remote"`
98 K8sConfig string `short:"8" long:"k8sconfig" env:"KUBECONFIG" value-name:"FILE" default:"" description:"Location of Kubernetes config file"`
99 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 -0700100 }
David Bainbridgea6722342019-10-24 23:55:53 +0000101
102 Debug = log.New(os.Stdout, "DEBUG: ", 0)
103 Info = log.New(os.Stdout, "INFO: ", 0)
104 Warn = log.New(os.Stderr, "WARN: ", 0)
105 Error = log.New(os.Stderr, "ERROR: ", 0)
Zack Williamse940c7a2019-08-21 14:25:39 -0700106)
107
108type OutputOptions struct {
109 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
110 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
111 OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
112 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
113}
114
115type ListOutputOptions struct {
116 OutputOptions
117 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
118 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
119}
120
121type OutputOptionsJson struct {
122 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
123 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
124 OutputAs string `short:"o" long:"outputas" default:"json" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
125 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
126}
127
128type ListOutputOptionsJson struct {
129 OutputOptionsJson
130 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
131 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
132}
133
134func toOutputType(in string) OutputType {
135 switch in {
136 case "table":
137 fallthrough
138 default:
139 return OUTPUT_TABLE
140 case "json":
141 return OUTPUT_JSON
142 case "yaml":
143 return OUTPUT_YAML
144 }
145}
146
147type CommandResult struct {
148 Format format.Format
149 Filter string
150 OrderBy string
151 OutputAs OutputType
152 NameLimit int
153 Data interface{}
154}
155
David Bainbridgea6722342019-10-24 23:55:53 +0000156func GetCommandOptionWithDefault(name, option, defaultValue string) string {
157 if cmd, ok := GlobalCommandOptions[name]; ok {
158 if val, ok := cmd[option]; ok {
159 return CharReplacer.Replace(val)
160 }
161 }
162 return defaultValue
163}
164
Zack Williamse940c7a2019-08-21 14:25:39 -0700165func ProcessGlobalOptions() {
166 if len(GlobalOptions.Config) == 0 {
167 home, err := os.UserHomeDir()
168 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000169 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700170 home = "~"
171 }
172 GlobalOptions.Config = filepath.Join(home, ".volt", "config")
173 }
174
David Bainbridgea6722342019-10-24 23:55:53 +0000175 if info, err := os.Stat(GlobalOptions.Config); err == nil && !info.IsDir() {
Zack Williamse940c7a2019-08-21 14:25:39 -0700176 configFile, err := ioutil.ReadFile(GlobalOptions.Config)
177 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000178 Error.Fatalf("Unable to read the configuration file '%s': %s",
179 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700180 }
David Bainbridgea6722342019-10-24 23:55:53 +0000181 if err = yaml.Unmarshal(configFile, &GlobalConfig); err != nil {
182 Error.Fatalf("Unable to parse the configuration file '%s': %s",
183 GlobalOptions.Config, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700184 }
185 }
186
187 // Override from command line
188 if GlobalOptions.Server != "" {
189 GlobalConfig.Server = GlobalOptions.Server
190 }
191 if GlobalOptions.ApiVersion != "" {
192 GlobalConfig.ApiVersion = GlobalOptions.ApiVersion
193 }
194
195 // If a k8s cert/key were not specified, then attempt to read it from
196 // any $HOME/.kube/config if it exists
197 if len(GlobalOptions.K8sConfig) == 0 {
198 home, err := os.UserHomeDir()
199 if err != nil {
David Bainbridgea6722342019-10-24 23:55:53 +0000200 Warn.Printf("Unable to discover the user's home directory: %s", err)
Zack Williamse940c7a2019-08-21 14:25:39 -0700201 home = "~"
202 }
203 GlobalOptions.K8sConfig = filepath.Join(home, ".kube", "config")
204 }
David Bainbridgea6722342019-10-24 23:55:53 +0000205
206 if len(GlobalOptions.CommandOptions) == 0 {
207 home, err := os.UserHomeDir()
208 if err != nil {
209 Warn.Printf("Unable to discover the user's home directory: %s", err)
210 home = "~"
211 }
212 GlobalOptions.CommandOptions = filepath.Join(home, ".volt", "command_options")
213 }
214
215 if info, err := os.Stat(GlobalOptions.CommandOptions); err == nil && !info.IsDir() {
216 optionsFile, err := ioutil.ReadFile(GlobalOptions.CommandOptions)
217 if err != nil {
218 Error.Fatalf("Unable to read command options configuration file '%s' : %s",
219 GlobalOptions.CommandOptions, err.Error())
220 }
221 if err = yaml.Unmarshal(optionsFile, &GlobalCommandOptions); err != nil {
222 Error.Fatalf("Unable to parse the command line options configuration file '%s': %s",
223 GlobalOptions.CommandOptions, err.Error())
224 }
225 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700226}
227
228func NewConnection() (*grpc.ClientConn, error) {
229 ProcessGlobalOptions()
230 return grpc.Dial(GlobalConfig.Server, grpc.WithInsecure())
231}
232
233func GenerateOutput(result *CommandResult) {
234 if result != nil && result.Data != nil {
235 data := result.Data
236 if result.Filter != "" {
237 f, err := filter.Parse(result.Filter)
238 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000239 Error.Fatalf("Unable to parse specified output filter '%s': %s", result.Filter, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700240 }
241 data, err = f.Process(data)
242 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000243 Error.Fatalf("Unexpected error while filtering command results: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700244 }
245 }
246 if result.OrderBy != "" {
247 s, err := order.Parse(result.OrderBy)
248 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000249 Error.Fatalf("Unable to parse specified sort specification '%s': %s", result.OrderBy, err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700250 }
251 data, err = s.Process(data)
252 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000253 Error.Fatalf("Unexpected error while sorting command result: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700254 }
255 }
256 if result.OutputAs == OUTPUT_TABLE {
257 tableFormat := format.Format(result.Format)
David Bainbridge12f036f2019-10-15 22:09:04 +0000258 if err := tableFormat.Execute(os.Stdout, true, result.NameLimit, data); err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000259 Error.Fatalf("Unexpected error while attempting to format results as table : %s", err.Error())
David Bainbridge12f036f2019-10-15 22:09:04 +0000260 }
Zack Williamse940c7a2019-08-21 14:25:39 -0700261 } else if result.OutputAs == OUTPUT_JSON {
262 asJson, err := json.Marshal(&data)
263 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000264 Error.Fatalf("Unexpected error while processing command results to JSON: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700265 }
266 fmt.Printf("%s", asJson)
267 } else if result.OutputAs == OUTPUT_YAML {
268 asYaml, err := yaml.Marshal(&data)
269 if err != nil {
David Bainbridge0f758d42019-10-26 05:17:48 +0000270 Error.Fatalf("Unexpected error while processing command results to YAML: %s", err.Error())
Zack Williamse940c7a2019-08-21 14:25:39 -0700271 }
272 fmt.Printf("%s", asYaml)
273 }
274 }
275}