/
shell.go
401 lines (331 loc) · 10.6 KB
/
shell.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright (c) 2015-2016 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
package main
import (
"encoding/json"
"flag"
"fmt"
"golang.org/x/crypto/ssh/terminal"
"io"
"os"
"path/filepath"
"github.com/couchbase/query/errors"
"github.com/couchbaselabs/go_cbq/command"
go_n1ql "github.com/couchbaselabs/go_n1ql"
)
/*
Command line options provided.
*/
/*
Option : -engine or -e
Args : <url to the query service or to the cluster>
Default value : http://localhost:8091/
Point to the cluser/query endpoint to connect to.
*/
var ServerFlag string
func init() {
const (
defaultserver = "http://localhost:8091/"
usage = "URL to the query service/cluster. \n\t\t Default : http://localhost:8091\n\n Usage: cbq \n\t\t Connects to local couchbase instance. Same as: cbq -engine=http://localhost:8091\n\t cbq -engine=http://172.23.107.18:8093 \n\t\t Connects to query node at 172.23.107.18 Port 8093 \n\t cbq -engine=https://my.secure.node.com:8093 \n\t\t Connects to query node at my.secure.node.com:8093 using secure https protocol."
)
flag.StringVar(&ServerFlag, "engine", defaultserver, usage)
flag.StringVar(&ServerFlag, "e", defaultserver, "Shorthand for -engine")
}
/*
Option : -no-engine or -ne
Default value : false
Enable/Disable startup connection to a query service/cluster endpoint.
*/
var NoQueryService bool
func init() {
const (
defaultval = false
usage = "Start shell without connecting to a query service/cluster endpoint. \n\t\t Default : false \n\t\t Possible Values : true/false"
)
flag.BoolVar(&NoQueryService, "no-engine", defaultval, usage)
flag.BoolVar(&NoQueryService, "ne", defaultval, " Shorthand for -no-engine")
}
/*
Option : -quiet
Default value : false
Enable/Disable startup connection message for the shell
*/
var quietFlag bool
func init() {
const (
defaultval = false
usage = "Enable/Disable startup connection message for the shell \n\t\t Default : false \n\t\t Possible Values : true/false"
)
flag.BoolVar(&quietFlag, "quiet", defaultval, usage)
flag.BoolVar(&quietFlag, "q", defaultval, " Shorthand for -quiet")
}
/*
Option : -timeout or -t
Args : <timeout value>
Default value : "0ms"
Query timeout parameter.
*/
var timeoutFlag string
func init() {
const (
defaultval = ""
usage = "Query timeout parameter. Units are mandatory. For Example : \"10ms\". \n\t\t Valid Units : ns (nanoseconds), us (microseconds), ms (milliseconds), s (seconds), m (minutes), h (hours) "
)
flag.StringVar(&timeoutFlag, "timeout", defaultval, usage)
flag.StringVar(&timeoutFlag, "t", defaultval, " Shorthand for -timeout")
}
/*
Option : -user or -u
Args : Login username
Login credentials for users. The shell will prompt for the password.
*/
var userFlag string
func init() {
const (
defaultval = ""
usage = "Username \n\t For Example : -u=Administrator"
)
flag.StringVar(&userFlag, "user", defaultval, usage)
flag.StringVar(&userFlag, "u", defaultval, " Shorthand for -user")
}
/*
Option : -credentials or -c
Args : A list of credentials, in the form of user/password objects.
Login credentials for users as well as SASL Buckets.
*/
var credsFlag string
func init() {
const (
defaultval = ""
usage = "A list of credentials, in the form user:password. \n\t For Example : Administrator:password, beer-sample:asdasd"
)
flag.StringVar(&credsFlag, "credentials", defaultval, usage)
flag.StringVar(&credsFlag, "c", defaultval, " Shorthand for -credentials")
}
/*
Option : -version or -v
Shell Version
*/
var versionFlag bool
func init() {
const (
usage = "Shell Version \n\t Usage: -version"
)
flag.BoolVar(&versionFlag, "version", false, usage)
flag.BoolVar(&versionFlag, "v", false, "Shorthand for -version")
}
/*
Option : -script or -s
Args : <query>
Single command mode
*/
var scriptFlag string
func init() {
const (
defaultval = ""
usage = "Single command mode. Execute input command and exit shell. \n\t For Example : -script=\"select * from system:keyspaces\""
)
flag.StringVar(&scriptFlag, "script", defaultval, usage)
flag.StringVar(&scriptFlag, "s", defaultval, " Shorthand for -script")
}
/*
Option : -pretty
Default value : false
Pretty print output
*/
var prettyFlag = flag.Bool("pretty", true, "Pretty print the output.")
/*
Option : -exit-on-error
Default value : false
Exit shell after first error encountered.
*/
var errorExitFlag = flag.Bool("exit-on-error", false, "Exit shell after first error encountered.")
/*
Option : -file or -f
Args : <filename>
Input file to run queries from. Exit after the queries are run.
*/
var inputFlag string
func init() {
const (
defaultval = ""
usage = "File to load commands from. \n\t For Example : -file=temp.txt"
)
flag.StringVar(&inputFlag, "file", defaultval, usage)
flag.StringVar(&inputFlag, "f", defaultval, " Shorthand for -file")
}
/*
Option : -ouput or -o
Args : <filename>
Output file to send results of queries to.
*/
var outputFlag string
func init() {
const (
defaultval = ""
usage = "File to output commands and their results. \n\t For Example : -output=temp.txt"
)
flag.StringVar(&outputFlag, "output", defaultval, usage)
flag.StringVar(&outputFlag, "o", defaultval, " Shorthand for -output")
}
/*
Option : -log-file or -l
Args : <filename>
Log commands for session.
*/
var logFlag string
func init() {
const (
defaultval = ""
usage = "File to log commands into. \n\t For Example : -log-file=temp.txt"
)
flag.StringVar(&logFlag, "log-file", defaultval, usage)
flag.StringVar(&logFlag, "l", defaultval, " Shorthand for -log-file")
}
/* Define credentials as user/pass and convert into
JSON object credentials
*/
var (
SERVICE_URL string
DISCONNECT bool
EXIT bool
)
func main() {
flag.Parse()
command.W = os.Stdout
/* Handle options and what they should do */
// TODO : Readd ...
//Taken out so as to connect to both cluster and query service
//using go_n1ql.
/*
if strings.HasPrefix(ServerFlag, "http://") == false {
ServerFlag = "http://" + ServerFlag
}
urlRegex := "^(https?://)[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"
match, _ := regexp.MatchString(urlRegex, ServerFlag)
if match == false {
//TODO Isha : Add error code. Throw invalid url error
fmt.Println("Invalid url please check" + ServerFlag)
}
//-engine
if strings.HasSuffix(ServerFlag, "/") == false {
ServerFlag = ServerFlag + "/"
}
*/
/* -quiet : Display Message only if flag not specified
*/
if !quietFlag && NoQueryService == false {
s := fmt.Sprintln("Connect to " + ServerFlag + ". Type Ctrl-D to exit.\n")
_, werr := io.WriteString(command.W, s)
if werr != nil {
s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
command.PrintError(s_err)
}
}
/* -version : Display the version of the shell and then exit.
*/
if versionFlag == true {
dummy := []string{}
cmd := command.Version{}
cmd.ExecCommand(dummy)
os.Exit(0)
}
/* -user : Accept Admin credentials. Prompt for password and set
the n1ql_creds. Append to creds so that user can also define
bucket credentials using -credentials if they need to.
*/
var creds command.Credentials
if userFlag != "" {
s := fmt.Sprintln("Enter Password: ")
_, werr := io.WriteString(command.W, s)
if werr != nil {
s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
command.PrintError(s_err)
}
password, err := terminal.ReadPassword(0)
if err == nil {
if string(password) == "" {
s_err := command.HandleError(errors.INVALID_PASSWORD, "")
command.PrintError(s_err)
os.Exit(1)
} else {
creds = append(creds, command.Credential{"user": userFlag, "pass": string(password)})
}
} else {
s_err := command.HandleError(errors.INVALID_PASSWORD, err.Error())
command.PrintError(s_err)
os.Exit(1)
}
}
/* -credentials : Accept credentials to pass to the n1ql endpoint.
Ensure that the user inputs credentials in the form a:b.
It is important to apend these credentials to those given by
-user.
*/
if userFlag == "" && credsFlag == "" {
// No credentials exist. This can still be used to connect to
// un-authenticated servers.
// Dont output the statement if we are running in single command
// mode.
if scriptFlag == "" {
_, werr := io.WriteString(command.W, "No Input Credentials. In order to connect to a server with authentication, please provide credentials.\n")
if werr != nil {
s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
command.PrintError(s_err)
}
}
} else if credsFlag != "" {
creds_ret, err_code, err_string := command.ToCreds(credsFlag)
if err_code != 0 {
s_err := command.HandleError(err_code, err_string)
command.PrintError(s_err)
}
for _, v := range creds_ret {
creds = append(creds, v)
}
}
//Append empty credentials. This is used for cases where one of the buckets
//is a SASL bucket, and we need to access the other unprotected buckets.
//CBauth works this way.
//if credsFlag == "" && userFlag != "" {
creds = append(creds, command.Credential{"user": "", "pass": ""})
//}
/* Add the credentials set by -user and -credentials to the
go_n1ql creds parameter.
*/
if creds != nil {
ac, err := json.Marshal(creds)
if err != nil {
//Error while Marshalling
s_err := command.HandleError(errors.JSON_MARSHAL, err.Error())
command.PrintError(s_err)
os.Exit(1)
}
go_n1ql.SetQueryParams("creds", string(ac))
}
if scriptFlag != "" {
go_n1ql.SetPassthroughMode(true)
err_code, err_str := execute_input(scriptFlag, os.Stdout)
if err_code != 0 {
s_err := command.HandleError(err_code, err_str)
command.PrintError(s_err)
os.Exit(1)
}
os.Exit(0)
}
if timeoutFlag != "0ms" {
go_n1ql.SetQueryParams("timeout", timeoutFlag)
}
if inputFlag != "" {
//Read each line from the file and call execute query
}
go_n1ql.SetPassthroughMode(true)
//fmt.Println("Input arguments, ", os.Args)
HandleInteractiveMode(filepath.Base(os.Args[0]))
}