forked from IBM-Cloud/redli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redli.go
448 lines (377 loc) · 11.2 KB
/
redli.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// ------------------------------------------------------------------------------
// Copyright IBM Corp. 2018
//
// 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 (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"regexp"
"sort"
"strconv"
"strings"
"github.com/gomodule/redigo/redis"
"github.com/mattn/go-isatty"
"github.com/mattn/go-shellwords"
"github.com/peterh/liner"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
debug = kingpin.Flag("debug", "Enable debug mode.").Bool()
longprompt = kingpin.Flag("long", "Enable long prompt with host/port").Bool()
redisurl = kingpin.Flag("uri", "URI to connect to").Short('u').URL()
redishost = kingpin.Flag("host", "Host to connect to").Short('h').Default("127.0.0.1").String()
redisport = kingpin.Flag("port", "Port to connect to").Short('p').Default("6379").Int()
redisuser = kingpin.Flag("redisuser", "Username to use when connecting. Supported since Redis 6.").Short('r').Default("").String()
redisauth = kingpin.Flag("auth", "Password to use when connecting").Short('a').String()
redisdb = kingpin.Flag("ndb", "Redis database to access").Short('n').Default("0").Int()
redistls = kingpin.Flag("tls", "Enable TLS/SSL").Default("false").Bool()
servername = kingpin.Flag("servername", "ServerName is used to verify the hostname on the returned certificates unless skipverify is set.").Short('s').String()
skipverify = kingpin.Flag("skipverify", "Don't validate certificates").Default("false").Bool()
rediscertfile = kingpin.Flag("certfile", "Self-signed certificate file for validation").Envar("REDIS_CERTFILE").File()
rediscertb64 = kingpin.Flag("certb64", "Self-signed certificate string as base64 for validation").Envar("REDIS_CERTB64").String()
forceraw = kingpin.Flag("raw", "Produce raw output").Bool()
eval = kingpin.Flag("eval", "Evaluate a Lua script file, follow with keys a , and args").File()
commandargs = kingpin.Arg("commands", "Redis commands and values").Strings()
)
var (
rawrediscommands = Commands{}
conn redis.Conn
raw = false
)
func main() {
kingpin.Version(version)
kingpin.Parse()
if *forceraw {
raw = true
} else {
if !isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()) {
raw = true
}
}
cert := []byte{}
if *rediscertfile != nil {
mycert, err := ioutil.ReadAll(*rediscertfile)
if err != nil {
log.Fatal(err)
}
cert = mycert
} else if rediscertb64 != nil {
mycert, err := base64.StdEncoding.DecodeString((*rediscertb64))
if err != nil {
log.Fatal("What", err)
}
cert = mycert
}
connectionurl := ""
if *redisurl == nil {
// With no URI, build a URI from other flags
if *redistls {
connectionurl = "rediss://"
} else {
connectionurl = "redis://"
}
if redisauth != nil {
connectionurl = connectionurl + url.QueryEscape(*redisuser) + ":" + url.QueryEscape(*redisauth) + "@"
}
connectionurl = connectionurl + *redishost + ":" + strconv.Itoa(*redisport) + "/" + strconv.Itoa(*redisdb)
} else {
connectionurl = (*redisurl).String()
}
config := &tls.Config{InsecureSkipVerify: *skipverify}
// If we have a certificate, then assume TLS
if len(cert) > 0 {
config.RootCAs = x509.NewCertPool()
config.ClientAuth = tls.RequireAndVerifyClientCert
ok := config.RootCAs.AppendCertsFromPEM(cert)
if !ok {
log.Fatal("Couldn't load cert data")
}
}
if servername != nil && *servername != "" {
config.ServerName = *servername
}
conn, err := redis.DialURL(connectionurl, redis.DialTLSConfig(config))
if err != nil && err.Error() == "ERR wrong number of arguments for 'auth' command" {
// Fallback to support usernames with Redis versions without ACL support
// Since at this point we constructed a valid URL that has to be escaped properly
// this regex should work...
re := regexp.MustCompile(`^(rediss?://)(.*)(:.*@.*)`)
connectionurl = re.ReplaceAllString(connectionurl, `$1$3`)
conn, err = redis.DialURL(connectionurl, redis.DialTLSConfig(config))
}
if err != nil {
log.Fatal("Dial ", err)
}
defer conn.Close()
// We may not need to carry on setting up the interactive front end so...
if *eval != nil {
command := *commandargs
scriptsrc, err := ioutil.ReadAll(*eval)
if err != nil {
log.Fatal(err)
}
var iargs []interface{}
keycnt := 0
// If there are other arguments, process them
if len(command) > 0 {
var args = make([]interface{}, len(command[:]))
gotcomma := false
for i, d := range command {
if !gotcomma {
if d == "," {
gotcomma = true
} else {
args[i] = d
keycnt = keycnt + 1
}
} else {
args[i-1] = d
}
}
iargs = append(iargs, args...)
}
script := redis.NewScript(keycnt, string(scriptsrc[:]))
result, err := script.Do(conn, iargs...)
if err != nil {
log.Fatal(err)
}
printRedisResult(result, false)
os.Exit(0)
}
if *commandargs != nil {
command := *commandargs
catchMonitorCmd(conn, command[0])
var args = make([]interface{}, len(command[1:]))
for i, d := range command[1:] {
args[i] = d
}
result, err := conn.Do(command[0], args...)
if err != nil {
log.Fatal(err)
}
forceraw := false
if strings.ToLower(command[0]) == "info" {
forceraw = true
}
printRedisResult(result, forceraw)
os.Exit(0)
}
json.Unmarshal([]byte(redisCommandsJSON), &rawrediscommands)
rediscommands := make(map[string]Command, len(rawrediscommands))
commandstrings := make([]string, len(rawrediscommands))
i := 0
for k, v := range rawrediscommands {
command := strings.ToLower(k)
commandstrings[i] = command
i = i + 1
rediscommands[command] = v
}
sort.Strings(commandstrings)
liner := liner.NewLiner()
defer liner.Close()
liner.SetCtrlCAborts(true)
liner.SetCompleter(func(line string) (c []string) {
lowerline := strings.ToLower(line)
for _, n := range commandstrings {
if strings.HasPrefix(n, lowerline) {
c = append(c, n)
}
}
if len(c) == 0 {
if strings.HasPrefix(lowerline, "help ") {
helpphrase := strings.TrimPrefix(lowerline, "help ")
for _, n := range commandstrings {
if strings.HasPrefix(n, helpphrase) {
c = append(c, "help "+n)
}
}
}
}
return
})
for {
forceraw := false
line, err := liner.Prompt(getPrompt())
if err != nil {
break
}
if len(line) == 0 {
continue // Ignore no input
}
parts, err := shellwords.Parse(line)
if len(parts) == 0 {
continue // Ignore no input
}
liner.AppendHistory(line)
if parts[0] == "help" {
if len(parts) == 1 {
fmt.Println("Enter help <command> to show information about a command")
continue
}
lookup := parts[1]
if len(parts) == 3 {
lookup = parts[1] + " " + parts[2]
}
commanddata, ok := rediscommands[lookup]
if ok {
fmt.Printf("Command: %s\n", strings.ToUpper(lookup))
fmt.Printf("Summary: %s\n", commanddata.Summary)
if commanddata.Complexity != "" {
fmt.Printf("Complexity: %s\n", commanddata.Complexity)
}
if commanddata.Arguments != nil {
fmt.Println("Args:")
for _, a := range commanddata.Arguments {
fmt.Printf(" %s (%s)\n", a.Name, a.Type)
}
}
continue
}
}
if parts[0] == "exit" {
break
}
if strings.ToLower(parts[0]) == "info" {
forceraw = true
}
var args = make([]interface{}, len(parts[1:]))
for i, d := range parts[1:] {
args[i] = d
}
catchMonitorCmd(conn, parts[0])
result, err := conn.Do(parts[0], args...)
printRedisResult(result, forceraw)
}
}
// catchMonitorCmd to go into a "stream" mode to stream back
// every command processed by Redis server.
func catchMonitorCmd(conn redis.Conn, command string) {
if strings.ToLower(command) == "monitor" {
conn.Do("monitor")
for {
line, _ := redis.String(conn.Receive())
fmt.Printf("%s\n", line)
}
}
}
func printRedisResult(result interface{}, forceraw bool) {
printRedisResultIndenting(result, "", forceraw)
}
func printRedisResultIndenting(result interface{}, prefix string, forceraw bool) {
switch v := result.(type) {
case []interface{}:
if raw || forceraw {
for _, j := range v {
switch vt := j.(type) {
case []interface{}:
printRedisResultIndenting(vt, "", forceraw)
default:
fmt.Printf("%s\n", toRedisValueString(vt, forceraw))
}
}
} else {
spacer := strings.Repeat(" ", len(prefix))
for i, j := range v {
switch vt := j.(type) {
case []interface{}:
newprefix := fmt.Sprintf("%s %d)", prefix, i+1)
printRedisResultIndenting(vt, newprefix, forceraw)
default:
if i == 0 {
fmt.Printf("%s %d) %s\n", prefix, i+1, toRedisValueString(j, forceraw))
} else {
fmt.Printf("%s %d) %s\n", spacer, i+1, toRedisValueString(j, forceraw))
}
}
}
}
default:
fmt.Printf("%s\n", toRedisValueString(result, forceraw))
}
}
func toRedisValueString(value interface{}, forceraw bool) string {
switch v := value.(type) {
case redis.Error:
if raw || forceraw {
return fmt.Sprintf("%s", v.Error())
}
return fmt.Sprintf("(error) %s", v.Error())
case int64:
if raw || forceraw {
return fmt.Sprintf("%d", v)
}
return fmt.Sprintf("(integer) %d", v)
case string:
return fmt.Sprintf("%s", v)
case []byte:
if raw || forceraw {
return fmt.Sprintf("%s", string(v))
}
return fmt.Sprintf("\"%s\"", string(v))
case nil:
return "nil"
}
return ""
}
func redisParseInfo(reply string) map[string]string {
lines := strings.Split(reply, "\r\n")
values := map[string]string{}
for _, line := range lines {
if len(line) > 0 && line[0] != '#' {
parts := strings.Split(line, ":")
if len(parts) == 2 {
values[parts[0]] = parts[1]
}
}
}
return values
}
func getPrompt() string {
if *longprompt {
if *redisurl != nil {
return fmt.Sprintf("%s:%s> ", (*redisurl).Hostname(), (*redisurl).Port())
}
return fmt.Sprintf("%s:%d> ", *redishost, *redisport)
}
return "> "
}
func printAsJSON(toprint interface{}) {
jsonstr, _ := json.MarshalIndent(toprint, "", " ")
fmt.Println(string(jsonstr))
}
//Commands is a holder for Redis Command structures
type Commands map[string]Command
//Command is a holder for Redis Command data includint arguments
type Command struct {
Summary string `json:"summary"`
Complexity string `json:"complexity"`
Arguments []Argument `json:"arguments"`
Since string `json:"since"`
Group string `json:"group"`
}
//Argument is a holder for Redis Command Argument data
type Argument struct {
Name string `json:"name"`
Type string `json:"type"`
Enum string `json:"enum,omitempty"`
Optional bool `json:"optional"`
}