blob: 43ead452dbe05fff0d483dc683ff9eb5f98c8243 [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{
75 ApiVersion: "v1",
76 Server: "localhost",
77 Tls: TlsConfigSpec{
78 UseTls: false,
79 },
80 Grpc: GrpcConfigSpec{
81 Timeout: time.Second * 10,
82 },
83 }
84
85 GlobalOptions struct {
86 Config string `short:"c" long:"config" env:"VOLTCONFIG" value-name:"FILE" default:"" description:"Location of client config file"`
87 Server string `short:"s" long:"server" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of VOLTHA"`
88 ApiVersion string `short:"a" long:"apiversion" description:"API version" value-name:"VERSION" choice:"v1" choice:"v2"`
89 Debug bool `short:"d" long:"debug" description:"Enable debug mode"`
90 UseTLS bool `long:"tls" description:"Use TLS"`
91 CACert string `long:"tlscacert" value-name:"CA_CERT_FILE" description:"Trust certs signed only by this CA"`
92 Cert string `long:"tlscert" value-name:"CERT_FILE" description:"Path to TLS vertificate file"`
93 Key string `long:"tlskey" value-name:"KEY_FILE" description:"Path to TLS key file"`
94 Verify bool `long:"tlsverify" description:"Use TLS and verify the remote"`
95 K8sConfig string `short:"8" long:"k8sconfig" env:"KUBECONFIG" value-name:"FILE" default:"" description:"Location of Kubernetes config file"`
96 }
97)
98
99type OutputOptions struct {
100 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
101 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
102 OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
103 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
104}
105
106type ListOutputOptions struct {
107 OutputOptions
108 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
109 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
110}
111
112type OutputOptionsJson struct {
113 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
114 Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
115 OutputAs string `short:"o" long:"outputas" default:"json" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
116 NameLimit int `short:"l" long:"namelimit" default:"-1" value-name:"LIMIT" description:"Limit the depth (length) in the table column name"`
117}
118
119type ListOutputOptionsJson struct {
120 OutputOptionsJson
121 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
122 OrderBy string `short:"r" long:"orderby" default:"" value-name:"ORDER" description:"Specify the sort order of the results"`
123}
124
125func toOutputType(in string) OutputType {
126 switch in {
127 case "table":
128 fallthrough
129 default:
130 return OUTPUT_TABLE
131 case "json":
132 return OUTPUT_JSON
133 case "yaml":
134 return OUTPUT_YAML
135 }
136}
137
138type CommandResult struct {
139 Format format.Format
140 Filter string
141 OrderBy string
142 OutputAs OutputType
143 NameLimit int
144 Data interface{}
145}
146
147type config struct {
148 ApiVersion string `yaml:"apiVersion"`
149 Server string `yaml:"server"`
150}
151
152func ProcessGlobalOptions() {
153 if len(GlobalOptions.Config) == 0 {
154 home, err := os.UserHomeDir()
155 if err != nil {
156 log.Printf("Unable to discover they users home directory: %s\n", err)
157 home = "~"
158 }
159 GlobalOptions.Config = filepath.Join(home, ".volt", "config")
160 }
161
162 info, err := os.Stat(GlobalOptions.Config)
163 if err == nil && !info.IsDir() {
164 configFile, err := ioutil.ReadFile(GlobalOptions.Config)
165 if err != nil {
166 log.Printf("configFile.Get err #%v ", err)
167 }
168 err = yaml.Unmarshal(configFile, &GlobalConfig)
169 if err != nil {
170 log.Fatalf("Unmarshal: %v", err)
171 }
172 }
173
174 // Override from command line
175 if GlobalOptions.Server != "" {
176 GlobalConfig.Server = GlobalOptions.Server
177 }
178 if GlobalOptions.ApiVersion != "" {
179 GlobalConfig.ApiVersion = GlobalOptions.ApiVersion
180 }
181
182 // If a k8s cert/key were not specified, then attempt to read it from
183 // any $HOME/.kube/config if it exists
184 if len(GlobalOptions.K8sConfig) == 0 {
185 home, err := os.UserHomeDir()
186 if err != nil {
187 log.Printf("Unable to discover the user's home directory: %s\n", err)
188 home = "~"
189 }
190 GlobalOptions.K8sConfig = filepath.Join(home, ".kube", "config")
191 }
192}
193
194func NewConnection() (*grpc.ClientConn, error) {
195 ProcessGlobalOptions()
196 return grpc.Dial(GlobalConfig.Server, grpc.WithInsecure())
197}
198
199func GenerateOutput(result *CommandResult) {
200 if result != nil && result.Data != nil {
201 data := result.Data
202 if result.Filter != "" {
203 f, err := filter.Parse(result.Filter)
204 if err != nil {
205 panic(err)
206 }
207 data, err = f.Process(data)
208 if err != nil {
209 panic(err)
210 }
211 }
212 if result.OrderBy != "" {
213 s, err := order.Parse(result.OrderBy)
214 if err != nil {
215 panic(err)
216 }
217 data, err = s.Process(data)
218 if err != nil {
219 panic(err)
220 }
221 }
222 if result.OutputAs == OUTPUT_TABLE {
223 tableFormat := format.Format(result.Format)
224 tableFormat.Execute(os.Stdout, true, result.NameLimit, data)
225 } else if result.OutputAs == OUTPUT_JSON {
226 asJson, err := json.Marshal(&data)
227 if err != nil {
228 panic(err)
229 }
230 fmt.Printf("%s", asJson)
231 } else if result.OutputAs == OUTPUT_YAML {
232 asYaml, err := yaml.Marshal(&data)
233 if err != nil {
234 panic(err)
235 }
236 fmt.Printf("%s", asYaml)
237 }
238 }
239}