Debian Codegraph @

cmd/influx/cli/cli.go

raw
1 // Package cli contains the logic of the influx command line client.
2 package cli // import "github.com/influxdata/influxdb/cmd/influx/cli"
3
4 import (
5 "bytes"
6 "context"
7 "encoding/csv"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "io/ioutil"
13 "net"
14 "net/http"
15 "os"
16 "os/signal"
17 "path/filepath"
18 "reflect"
19 "runtime"
20 "sort"
21 "strconv"
22 "strings"
23 "syscall"
24 "text/tabwriter"
25
26 "golang.org/x/crypto/ssh/terminal"
27
28 "github.com/influxdata/influxdb/client"
29 "github.com/influxdata/influxdb/importer/v8"
30 "github.com/influxdata/influxdb/models"
31 "github.com/influxdata/influxql"
32 "github.com/peterh/liner"
33 )
34
35 // ErrBlankCommand is returned when a parsed command is empty.
36 var ErrBlankCommand = errors.New("empty input")
37
38 // CommandLine holds CLI configuration and state.
39 type CommandLine struct {
40 Line *liner.State
41 Host string
42 Port int
43 Database string
44 Ssl bool
45 RetentionPolicy string
46 ClientVersion string
47 ServerVersion string
48 Pretty bool // controls pretty print for json
49 Format string // controls the output format. Valid values are json, csv, or column
50 Execute string
51 ShowVersion bool
52 Import bool
53 Chunked bool
54 ChunkSize int
55 NodeID int
56 Quit chan struct{}
57 IgnoreSignals bool // Ignore signals normally caught by this process (used primarily for testing)
58 ForceTTY bool // Force the CLI to act as if it were connected to a TTY
59 osSignals chan os.Signal
60 historyFilePath string
61
62 Client *client.Client
63 ClientConfig client.Config // Client config options.
64 ImporterConfig v8.Config // Importer configuration options.
65 }
66
67 // New returns an instance of CommandLine with the specified client version.
68 func New(version string) *CommandLine {
69 return &CommandLine{
70 ClientVersion: version,
71 Quit: make(chan struct{}, 1),
72 osSignals: make(chan os.Signal, 1),
73 Chunked: true,
74 }
75 }
76
77 // Run executes the CLI.
78 func (c *CommandLine) Run() error {
79 hasTTY := c.ForceTTY || terminal.IsTerminal(int(os.Stdin.Fd()))
80
81 var promptForPassword bool
82 // determine if they set the password flag but provided no value
83 for _, v := range os.Args {
84 v = strings.ToLower(v)
85 if (strings.HasPrefix(v, "-password") || strings.HasPrefix(v, "--password")) && c.ClientConfig.Password == "" {
86 promptForPassword = true
87 break
88 }
89 }
90
91 // Check if we will be able to prompt for the password later.
92 if promptForPassword && !hasTTY {
93 return errors.New("unable to prompt for a password with no TTY")
94 }
95
96 // Read environment variables for username/password.
97 if c.ClientConfig.Username == "" {
98 c.ClientConfig.Username = os.Getenv("INFLUX_USERNAME")
99 }
100 // If we are going to be prompted for a password, always use the entered password.
101 if promptForPassword {
102 // Open the liner (temporarily) and prompt for the password.
103 p, e := func() (string, error) {
104 l := liner.NewLiner()
105 defer l.Close()
106 return l.PasswordPrompt("password: ")
107 }()
108 if e != nil {
109 return errors.New("Unable to parse password")
110 }
111 c.ClientConfig.Password = p
112 } else if c.ClientConfig.Password == "" {
113 c.ClientConfig.Password = os.Getenv("INFLUX_PASSWORD")
114 }
115
116 if err := c.Connect(""); err != nil {
117 msg := "Please check your connection settings and ensure 'influxd' is running."
118 if !c.Ssl && strings.Contains(err.Error(), "malformed HTTP response") {
119 // Attempt to connect with SSL and disable secure SSL for this test.
120 c.Ssl = true
121 unsafeSsl := c.ClientConfig.UnsafeSsl
122 c.ClientConfig.UnsafeSsl = true
123 if err := c.Connect(""); err == nil {
124 msg = "Please use the -ssl flag to connect using SSL."
125 }
126 c.Ssl = false
127 c.ClientConfig.UnsafeSsl = unsafeSsl
128 } else if c.Ssl && !c.ClientConfig.UnsafeSsl && strings.Contains(err.Error(), "certificate is valid for") {
129 // Attempt to connect with an insecure connection just to see if it works.
130 c.ClientConfig.UnsafeSsl = true
131 if err := c.Connect(""); err == nil {
132 msg = "You may use -unsafeSsl to connect anyway, but the SSL connection will not be secure."
133 }
134 c.ClientConfig.UnsafeSsl = false
135 }
136 return fmt.Errorf("Failed to connect to %s: %s\n%s", c.Client.Addr(), err.Error(), msg)
137 }
138
139 // Modify precision.
140 c.SetPrecision(c.ClientConfig.Precision)
141
142 if c.Execute != "" {
143 // Make the non-interactive mode send everything through the CLI's parser
144 // the same way the interactive mode works
145 lines := strings.Split(c.Execute, "\n")
146 for _, line := range lines {
147 if err := c.ParseCommand(line); err != nil {
148 return err
149 }
150 }
151 return nil
152 }
153
154 if c.Import {
155 addr := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
156 u, e := client.ParseConnectionString(addr, c.Ssl)
157 if e != nil {
158 return e
159 }
160
161 // Copy the latest importer config and inject the latest client config
162 // into it.
163 config := c.ImporterConfig
164 config.Config = c.ClientConfig
165 config.URL = u
166
167 i := v8.NewImporter(config)
168 if err := i.Import(); err != nil {
169 err = fmt.Errorf("ERROR: %s", err)
170 return err
171 }
172 return nil
173 }
174
175 if !hasTTY {
176 cmd, err := ioutil.ReadAll(os.Stdin)
177 if err != nil {
178 return err
179 }
180 return c.ExecuteQuery(string(cmd))
181 }
182
183 if !c.IgnoreSignals {
184 // register OS signals for graceful termination
185 signal.Notify(c.osSignals, syscall.SIGINT, syscall.SIGTERM)
186 }
187
188 c.Line = liner.NewLiner()
189 defer c.Line.Close()
190
191 c.Line.SetMultiLineMode(true)
192
193 if len(c.ServerVersion) == 0 {
194 fmt.Printf("WARN: Connected to %s, but found no server version.\n", c.Client.Addr())
195 fmt.Printf("Are you sure an InfluxDB server is listening at the given address?\n")
196 } else {
197 fmt.Printf("Connected to %s version %s\n", c.Client.Addr(), c.ServerVersion)
198 }
199
200 c.Version()
201
202 // Only load/write history if HOME environment variable is set.
203 var historyDir string
204 if runtime.GOOS == "windows" {
205 if userDir := os.Getenv("USERPROFILE"); userDir != "" {
206 historyDir = userDir
207 }
208 }
209
210 if homeDir := os.Getenv("HOME"); homeDir != "" {
211 historyDir = homeDir
212 }
213
214 // Attempt to load the history file.
215 if historyDir != "" {
216 c.historyFilePath = filepath.Join(historyDir, ".influx_history")
217 if historyFile, err := os.Open(c.historyFilePath); err == nil {
218 c.Line.ReadHistory(historyFile)
219 historyFile.Close()
220 }
221 }
222
223 // read from prompt until exit is run
224 return c.mainLoop()
225 }
226
227 // mainLoop runs the main prompt loop for the CLI.
228 func (c *CommandLine) mainLoop() error {
229 for {
230 select {
231 case <-c.osSignals:
232 c.exit()
233 return nil
234 case <-c.Quit:
235 c.exit()
236 return nil
237 default:
238 l, e := c.Line.Prompt("> ")
239 if e == io.EOF {
240 // Instead of die, register that someone exited the program gracefully
241 l = "exit"
242 } else if e != nil {
243 c.exit()
244 return e
245 }
246 if err := c.ParseCommand(l); err != ErrBlankCommand && !strings.HasPrefix(strings.TrimSpace(l), "auth") {
247 l = influxql.Sanitize(l)
248 c.Line.AppendHistory(l)
249 c.saveHistory()
250 }
251 }
252 }
253 }
254
255 // ParseCommand parses an instruction and calls the related method
256 // or executes the command as a query against InfluxDB.
257 func (c *CommandLine) ParseCommand(cmd string) error {
258 lcmd := strings.TrimSpace(strings.ToLower(cmd))
259 tokens := strings.Fields(lcmd)
260
261 if len(tokens) > 0 {
262 switch tokens[0] {
263 case "exit", "quit":
264 close(c.Quit)
265 case "gopher":
266 c.gopher()
267 case "connect":
268 return c.Connect(cmd)
269 case "auth":
270 c.SetAuth(cmd)
271 case "help":
272 c.help()
273 case "history":
274 c.history()
275 case "format":
276 c.SetFormat(cmd)
277 case "precision":
278 c.SetPrecision(cmd)
279 case "consistency":
280 c.SetWriteConsistency(cmd)
281 case "settings":
282 c.Settings()
283 case "chunked":
284 c.Chunked = !c.Chunked
285 if c.Chunked {
286 fmt.Println("chunked responses enabled")
287 } else {
288 fmt.Println("chunked reponses disabled")
289 }
290 case "chunk":
291 c.SetChunkSize(cmd)
292 case "pretty":
293 c.Pretty = !c.Pretty
294 if c.Pretty {
295 fmt.Println("Pretty print enabled")
296 } else {
297 fmt.Println("Pretty print disabled")
298 }
299 case "use":
300 c.use(cmd)
301 case "node":
302 c.node(cmd)
303 case "insert":
304 return c.Insert(cmd)
305 case "clear":
306 c.clear(cmd)
307 default:
308 return c.ExecuteQuery(cmd)
309 }
310
311 return nil
312 }
313 return ErrBlankCommand
314 }
315
316 // Connect connects to a server.
317 func (c *CommandLine) Connect(cmd string) error {
318 // normalize cmd
319 cmd = strings.ToLower(cmd)
320
321 // Remove the "connect" keyword if it exists
322 addr := strings.TrimSpace(strings.Replace(cmd, "connect", "", -1))
323 if addr == "" {
324 // If they didn't provide a connection string, use the current settings
325 addr = net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
326 }
327
328 URL, err := client.ParseConnectionString(addr, c.Ssl)
329 if err != nil {
330 return err
331 }
332
333 // Create copy of the current client config and create a new client.
334 ClientConfig := c.ClientConfig
335 ClientConfig.UserAgent = "InfluxDBShell/" + c.ClientVersion
336 ClientConfig.URL = URL
337 ClientConfig.Proxy = http.ProxyFromEnvironment
338
339 client, err := client.NewClient(ClientConfig)
340 if err != nil {
341 return fmt.Errorf("Could not create client %s", err)
342 }
343 c.Client = client
344
345 _, v, err := c.Client.Ping()
346 if err != nil {
347 return err
348 }
349 c.ServerVersion = v
350
351 // Update the command with the current connection information
352 if host, port, err := net.SplitHostPort(ClientConfig.URL.Host); err == nil {
353 c.Host = host
354 if i, err := strconv.Atoi(port); err == nil {
355 c.Port = i
356 }
357 }
358
359 return nil
360 }
361
362 // SetAuth sets client authentication credentials.
363 func (c *CommandLine) SetAuth(cmd string) {
364 // If they pass in the entire command, we should parse it
365 // auth <username> <password>
366 args := strings.Fields(cmd)
367 if len(args) == 3 {
368 args = args[1:]
369 } else {
370 args = []string{}
371 }
372
373 if len(args) == 2 {
374 c.ClientConfig.Username = args[0]
375 c.ClientConfig.Password = args[1]
376 } else {
377 u, e := c.Line.Prompt("username: ")
378 if e != nil {
379 fmt.Printf("Unable to process input: %s", e)
380 return
381 }
382 c.ClientConfig.Username = strings.TrimSpace(u)
383 p, e := c.Line.PasswordPrompt("password: ")
384 if e != nil {
385 fmt.Printf("Unable to process input: %s", e)
386 return
387 }
388 c.ClientConfig.Password = p
389 }
390
391 // Update the client as well
392 c.Client.SetAuth(c.ClientConfig.Username, c.ClientConfig.Password)
393 }
394
395 func (c *CommandLine) clear(cmd string) {
396 args := strings.Split(strings.TrimSuffix(strings.TrimSpace(cmd), ";"), " ")
397 v := strings.ToLower(strings.Join(args[1:], " "))
398 switch v {
399 case "database", "db":
400 c.Database = ""
401 fmt.Println("database context cleared")
402 return
403 case "retention policy", "rp":
404 c.RetentionPolicy = ""
405 fmt.Println("retention policy context cleared")
406 return
407 default:
408 if len(args) > 1 {
409 fmt.Printf("invalid command %q.\n", v)
410 }
411 fmt.Println(`Possible commands for 'clear' are:
412 # Clear the database context
413 clear database
414 clear db
415
416 # Clear the retention policy context
417 clear retention policy
418 clear rp
419 `)
420 }
421 }
422
423 func (c *CommandLine) use(cmd string) {
424 args := strings.SplitAfterN(strings.TrimSuffix(strings.TrimSpace(cmd), ";"), " ", 2)
425 if len(args) != 2 {
426 fmt.Printf("Could not parse database name from %q.\n", cmd)
427 return
428 }
429
430 stmt := args[1]
431 db, rp, err := parseDatabaseAndRetentionPolicy([]byte(stmt))
432 if err != nil {
433 fmt.Printf("Unable to parse database or retention policy from %s", stmt)
434 return
435 }
436
437 if !c.databaseExists(db) {
438 fmt.Println("DB does not exist!")
439 return
440 }
441
442 c.Database = db
443 fmt.Printf("Using database %s\n", db)
444
445 if rp != "" {
446 if !c.retentionPolicyExists(db, rp) {
447 return
448 }
449 c.RetentionPolicy = rp
450 fmt.Printf("Using retention policy %s\n", rp)
451 }
452 }
453
454 func (c *CommandLine) databaseExists(db string) bool {
455 // Validate if specified database exists
456 response, err := c.Client.Query(client.Query{Command: "SHOW DATABASES"})
457 if err != nil {
458 fmt.Printf("ERR: %s\n", err)
459 return false
460 } else if err := response.Error(); err != nil {
461 if c.ClientConfig.Username == "" {
462 fmt.Printf("ERR: %s\n", err)
463 return false
464 }
465 // TODO(jsternberg): Fix SHOW DATABASES to be user-aware #6397.
466 // If we are unable to run SHOW DATABASES, display a warning and use the
467 // database anyway in case the person doesn't have permission to run the
468 // command, but does have permission to use the database.
469 fmt.Printf("WARN: %s\n", err)
470 } else {
471 // Verify the provided database exists
472 if databaseExists := func() bool {
473 for _, result := range response.Results {
474 for _, row := range result.Series {
475 if row.Name == "databases" {
476 for _, values := range row.Values {
477 for _, database := range values {
478 if database == db {
479 return true
480 }
481 }
482 }
483 }
484 }
485 }
486 return false
487 }(); !databaseExists {
488 fmt.Printf("ERR: Database %s doesn't exist. Run SHOW DATABASES for a list of existing databases.\n", db)
489 return false
490 }
491 }
492 return true
493 }
494
495 func (c *CommandLine) retentionPolicyExists(db, rp string) bool {
496 // Validate if specified database exists
497 response, err := c.Client.Query(client.Query{Command: fmt.Sprintf("SHOW RETENTION POLICIES ON %q", db)})
498 if err != nil {
499 fmt.Printf("ERR: %s\n", err)
500 return false
501 } else if err := response.Error(); err != nil {
502 if c.ClientConfig.Username == "" {
503 fmt.Printf("ERR: %s\n", err)
504 return false
505 }
506 fmt.Printf("WARN: %s\n", err)
507 } else {
508 // Verify the provided database exists
509 if retentionPolicyExists := func() bool {
510 for _, result := range response.Results {
511 for _, row := range result.Series {
512 for _, values := range row.Values {
513 for i, v := range values {
514 if i != 0 {
515 continue
516 }
517 if v == rp {
518 return true
519 }
520 }
521 }
522 }
523 }
524 return false
525 }(); !retentionPolicyExists {
526 fmt.Printf("ERR: RETENTION POLICY %s doesn't exist. Run SHOW RETENTION POLICIES ON %q for a list of existing retention polices.\n", rp, db)
527 return false
528 }
529 }
530 return true
531 }
532
533 func (c *CommandLine) node(cmd string) {
534 args := strings.Split(strings.TrimSuffix(strings.TrimSpace(cmd), ";"), " ")
535 if len(args) != 2 {
536 fmt.Println("Improper number of arguments for 'node' command, requires exactly one.")
537 return
538 }
539
540 if args[1] == "clear" {
541 c.NodeID = 0
542 return
543 }
544
545 id, err := strconv.Atoi(args[1])
546 if err != nil {
547 fmt.Printf("Unable to parse node id from %s. Must be an integer or 'clear'.\n", args[1])
548 return
549 }
550 c.NodeID = id
551 }
552
553 // SetChunkSize sets the chunk size
554 // 0 sets it back to the default
555 func (c *CommandLine) SetChunkSize(cmd string) {
556 // normalize cmd
557 cmd = strings.ToLower(cmd)
558 cmd = strings.Join(strings.Fields(cmd), " ")
559
560 // Remove the "chunk size" keyword if it exists
561 cmd = strings.TrimPrefix(cmd, "chunk size ")
562
563 // Remove the "chunk" keyword if it exists
564 // allows them to use `chunk 50` as a shortcut
565 cmd = strings.TrimPrefix(cmd, "chunk ")
566
567 if n, err := strconv.ParseInt(cmd, 10, 64); err == nil {
568 c.ChunkSize = int(n)
569 if c.ChunkSize <= 0 {
570 c.ChunkSize = 0
571 }
572 fmt.Printf("chunk size set to %d\n", c.ChunkSize)
573 } else {
574 fmt.Printf("unable to parse chunk size from %q\n", cmd)
575 }
576 }
577
578 // SetPrecision sets client precision.
579 func (c *CommandLine) SetPrecision(cmd string) {
580 // normalize cmd
581 cmd = strings.ToLower(cmd)
582
583 // Remove the "precision" keyword if it exists
584 cmd = strings.TrimSpace(strings.Replace(cmd, "precision", "", -1))
585
586 switch cmd {
587 case "h", "m", "s", "ms", "u", "ns":
588 c.ClientConfig.Precision = cmd
589 c.Client.SetPrecision(c.ClientConfig.Precision)
590 case "rfc3339":
591 c.ClientConfig.Precision = ""
592 c.Client.SetPrecision(c.ClientConfig.Precision)
593 default:
594 fmt.Printf("Unknown precision %q. Please use rfc3339, h, m, s, ms, u or ns.\n", cmd)
595 }
596 }
597
598 // SetFormat sets output format.
599 func (c *CommandLine) SetFormat(cmd string) {
600 // normalize cmd
601 cmd = strings.ToLower(cmd)
602 // Remove the "format" keyword if it exists
603 cmd = strings.TrimSpace(strings.Replace(cmd, "format", "", -1))
604
605 switch cmd {
606 case "json", "csv", "column":
607 c.Format = cmd
608 default:
609 fmt.Printf("Unknown format %q. Please use json, csv, or column.\n", cmd)
610 }
611 }
612
613 // SetWriteConsistency sets write consistency level.
614 func (c *CommandLine) SetWriteConsistency(cmd string) {
615 // normalize cmd
616 cmd = strings.ToLower(cmd)
617 // Remove the "consistency" keyword if it exists
618 cmd = strings.TrimSpace(strings.Replace(cmd, "consistency", "", -1))
619
620 _, err := models.ParseConsistencyLevel(cmd)
621 if err != nil {
622 fmt.Printf("Unknown consistency level %q. Please use any, one, quorum, or all.\n", cmd)
623 return
624 }
625 c.ClientConfig.WriteConsistency = cmd
626 }
627
628 // isWhitespace returns true if the rune is a space, tab, or newline.
629 func isWhitespace(ch rune) bool { return ch == ' ' || ch == '\t' || ch == '\n' }
630
631 // isLetter returns true if the rune is a letter.
632 func isLetter(ch rune) bool { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') }
633
634 // isDigit returns true if the rune is a digit.
635 func isDigit(ch rune) bool { return (ch >= '0' && ch <= '9') }
636
637 // isIdentFirstChar returns true if the rune can be used as the first char in an unquoted identifer.
638 func isIdentFirstChar(ch rune) bool { return isLetter(ch) || ch == '_' }
639
640 // isIdentChar returns true if the rune can be used in an unquoted identifier.
641 func isNotIdentChar(ch rune) bool { return !(isLetter(ch) || isDigit(ch) || ch == '_') }
642
643 func parseUnquotedIdentifier(stmt string) (string, string) {
644 if fields := strings.FieldsFunc(stmt, isNotIdentChar); len(fields) > 0 {
645 return fields[0], strings.TrimPrefix(stmt, fields[0])
646 }
647 return "", stmt
648 }
649
650 func parseDoubleQuotedIdentifier(stmt string) (string, string) {
651 escapeNext := false
652 fields := strings.FieldsFunc(stmt, func(ch rune) bool {
653 if ch == '\\' {
654 escapeNext = true
655 } else if ch == '"' {
656 if !escapeNext {
657 return true
658 }
659 escapeNext = false
660 }
661 return false
662 })
663 if len(fields) > 0 {
664 return fields[0], strings.TrimPrefix(stmt, "\""+fields[0]+"\"")
665 }
666 return "", stmt
667 }
668
669 func parseNextIdentifier(stmt string) (ident, remainder string) {
670 if len(stmt) > 0 {
671 switch {
672 case isWhitespace(rune(stmt[0])):
673 return parseNextIdentifier(stmt[1:])
674 case isIdentFirstChar(rune(stmt[0])):
675 return parseUnquotedIdentifier(stmt)
676 case stmt[0] == '"':
677 return parseDoubleQuotedIdentifier(stmt)
678 }
679 }
680 return "", stmt
681 }
682
683 func (c *CommandLine) parseInto(stmt string) *client.BatchPoints {
684 ident, stmt := parseNextIdentifier(stmt)
685 db, rp := c.Database, c.RetentionPolicy
686 if strings.HasPrefix(stmt, ".") {
687 db = ident
688 ident, stmt = parseNextIdentifier(stmt[1:])
689 }
690 if strings.HasPrefix(stmt, " ") {
691 rp = ident
692 stmt = stmt[1:]
693 }
694
695 return &client.BatchPoints{
696 Points: []client.Point{
697 client.Point{Raw: stmt},
698 },
699 Database: db,
700 RetentionPolicy: rp,
701 Precision: c.ClientConfig.Precision,
702 WriteConsistency: c.ClientConfig.WriteConsistency,
703 }
704 }
705
706 func (c *CommandLine) parseInsert(stmt string) (*client.BatchPoints, error) {
707 i, point := parseNextIdentifier(stmt)
708 if !strings.EqualFold(i, "insert") {
709 return nil, fmt.Errorf("found %s, expected INSERT", i)
710 }
711 if i, r := parseNextIdentifier(point); strings.EqualFold(i, "into") {
712 bp := c.parseInto(r)
713 return bp, nil
714 }
715 return &client.BatchPoints{
716 Points: []client.Point{
717 client.Point{Raw: point},
718 },
719 Database: c.Database,
720 RetentionPolicy: c.RetentionPolicy,
721 Precision: c.ClientConfig.Precision,
722 WriteConsistency: c.ClientConfig.WriteConsistency,
723 }, nil
724 }
725
726 // Insert runs an INSERT statement.
727 func (c *CommandLine) Insert(stmt string) error {
728 bp, err := c.parseInsert(stmt)
729 if err != nil {
730 fmt.Printf("ERR: %s\n", err)
731 return nil
732 }
733 if _, err := c.Client.Write(*bp); err != nil {
734 fmt.Printf("ERR: %s\n", err)
735 if c.Database == "" {
736 fmt.Println("Note: error may be due to not setting a database or retention policy.")
737 fmt.Println(`Please set a database with the command "use <database>" or`)
738 fmt.Println("INSERT INTO <database>.<retention-policy> <point>")
739 }
740 }
741 return nil
742 }
743
744 // query creates a query struct to be used with the client.
745 func (c *CommandLine) query(query string) client.Query {
746 return client.Query{
747 Command: query,
748 Database: c.Database,
749 RetentionPolicy: c.RetentionPolicy,
750 Chunked: c.Chunked,
751 ChunkSize: c.ChunkSize,
752 NodeID: c.NodeID,
753 }
754 }
755
756 // ExecuteQuery runs any query statement.
757 func (c *CommandLine) ExecuteQuery(query string) error {
758 // If we have a retention policy, we need to rewrite the statement sources
759 if c.RetentionPolicy != "" {
760 pq, err := influxql.NewParser(strings.NewReader(query)).ParseQuery()
761 if err != nil {
762 fmt.Printf("ERR: %s\n", err)
763 return err
764 }
765 for _, stmt := range pq.Statements {
766 if selectStatement, ok := stmt.(*influxql.SelectStatement); ok {
767 influxql.WalkFunc(selectStatement.Sources, func(n influxql.Node) {
768 if t, ok := n.(*influxql.Measurement); ok {
769 if t.Database == "" && c.Database != "" {
770 t.Database = c.Database
771 }
772 if t.RetentionPolicy == "" && c.RetentionPolicy != "" {
773 t.RetentionPolicy = c.RetentionPolicy
774 }
775 }
776 })
777 }
778 }
779 query = pq.String()
780 }
781
782 ctx := context.Background()
783 if !c.IgnoreSignals {
784 done := make(chan struct{})
785 defer close(done)
786
787 var cancel func()
788 ctx, cancel = context.WithCancel(ctx)
789 go func() {
790 select {
791 case <-done:
792 case <-c.osSignals:
793 cancel()
794 }
795 }()
796 }
797
798 response, err := c.Client.QueryContext(ctx, c.query(query))
799 if err != nil {
800 if err.Error() == "" {
801 err = ctx.Err()
802 if err == context.Canceled {
803 err = errors.New("aborted by user")
804 }
805 }
806 fmt.Printf("ERR: %s\n", err)
807 return err
808 }
809 c.FormatResponse(response, os.Stdout)
810 if err := response.Error(); err != nil {
811 fmt.Printf("ERR: %s\n", response.Error())
812 if c.Database == "" {
813 fmt.Println("Warning: It is possible this error is due to not setting a database.")
814 fmt.Println(`Please set a database with the command "use <database>".`)
815 }
816 return err
817 }
818 return nil
819 }
820
821 // FormatResponse formats output to the previously chosen format.
822 func (c *CommandLine) FormatResponse(response *client.Response, w io.Writer) {
823 switch c.Format {
824 case "json":
825 c.writeJSON(response, w)
826 case "csv":
827 c.writeCSV(response, w)
828 case "column":
829 c.writeColumns(response, w)
830 default:
831 fmt.Fprintf(w, "Unknown output format %q.\n", c.Format)
832 }
833 }
834
835 func (c *CommandLine) writeJSON(response *client.Response, w io.Writer) {
836 var data []byte
837 var err error
838 if c.Pretty {
839 data, err = json.MarshalIndent(response, "", " ")
840 } else {
841 data, err = json.Marshal(response)
842 }
843 if err != nil {
844 fmt.Fprintf(w, "Unable to parse json: %s\n", err)
845 return
846 }
847 fmt.Fprintln(w, string(data))
848 }
849
850 func tagsEqual(prev, current map[string]string) bool {
851 return reflect.DeepEqual(prev, current)
852 }
853
854 func columnsEqual(prev, current []string) bool {
855 return reflect.DeepEqual(prev, current)
856 }
857
858 func headersEqual(prev, current models.Row) bool {
859 if prev.Name != current.Name {
860 return false
861 }
862 return tagsEqual(prev.Tags, current.Tags) && columnsEqual(prev.Columns, current.Columns)
863 }
864
865 func (c *CommandLine) writeCSV(response *client.Response, w io.Writer) {
866 csvw := csv.NewWriter(w)
867 var previousHeaders models.Row
868 for _, result := range response.Results {
869 suppressHeaders := len(result.Series) > 0 && headersEqual(previousHeaders, result.Series[0])
870 if !suppressHeaders && len(result.Series) > 0 {
871 previousHeaders = models.Row{
872 Name: result.Series[0].Name,
873 Tags: result.Series[0].Tags,
874 Columns: result.Series[0].Columns,
875 }
876 }
877
878 // Create a tabbed writer for each result as they won't always line up
879 rows := c.formatResults(result, "\t", suppressHeaders)
880 for _, r := range rows {
881 csvw.Write(strings.Split(r, "\t"))
882 }
883 }
884 csvw.Flush()
885 }
886
887 func (c *CommandLine) writeColumns(response *client.Response, w io.Writer) {
888 // Create a tabbed writer for each result as they won't always line up
889 writer := new(tabwriter.Writer)
890 writer.Init(w, 0, 8, 1, ' ', 0)
891
892 var previousHeaders models.Row
893 for i, result := range response.Results {
894 // Print out all messages first
895 for _, m := range result.Messages {
896 fmt.Fprintf(w, "%s: %s.\n", m.Level, m.Text)
897 }
898 // Check to see if the headers are the same as the previous row. If so, suppress them in the output
899 suppressHeaders := len(result.Series) > 0 && headersEqual(previousHeaders, result.Series[0])
900 if !suppressHeaders && len(result.Series) > 0 {
901 previousHeaders = models.Row{
902 Name: result.Series[0].Name,
903 Tags: result.Series[0].Tags,
904 Columns: result.Series[0].Columns,
905 }
906 }
907
908 // If we are suppressing headers, don't output the extra line return. If we
909 // aren't suppressing headers, then we put out line returns between results
910 // (not before the first result, and not after the last result).
911 if !suppressHeaders && i > 0 {
912 fmt.Fprintln(writer, "")
913 }
914
915 rows := c.formatResults(result, "\t", suppressHeaders)
916 for _, r := range rows {
917 fmt.Fprintln(writer, r)
918 }
919
920 }
921 writer.Flush()
922 }
923
924 // formatResults will behave differently if you are formatting for columns or csv
925 func (c *CommandLine) formatResults(result client.Result, separator string, suppressHeaders bool) []string {
926 rows := []string{}
927 // Create a tabbed writer for each result as they won't always line up
928 for i, row := range result.Series {
929 // gather tags
930 tags := []string{}
931 for k, v := range row.Tags {
932 tags = append(tags, fmt.Sprintf("%s=%s", k, v))
933 sort.Strings(tags)
934 }
935
936 columnNames := []string{}
937
938 // Only put name/tags in a column if format is csv
939 if c.Format == "csv" {
940 if len(tags) > 0 {
941 columnNames = append([]string{"tags"}, columnNames...)
942 }
943
944 if row.Name != "" {
945 columnNames = append([]string{"name"}, columnNames...)
946 }
947 }
948
949 columnNames = append(columnNames, row.Columns...)
950
951 // Output a line separator if we have more than one set or results and format is column
952 if i > 0 && c.Format == "column" && !suppressHeaders {
953 rows = append(rows, "")
954 }
955
956 // If we are column format, we break out the name/tag to separate lines
957 if c.Format == "column" && !suppressHeaders {
958 if row.Name != "" {
959 n := fmt.Sprintf("name: %s", row.Name)
960 rows = append(rows, n)
961 }
962 if len(tags) > 0 {
963 t := fmt.Sprintf("tags: %s", (strings.Join(tags, ", ")))
964 rows = append(rows, t)
965 }
966 }
967
968 if !suppressHeaders {
969 rows = append(rows, strings.Join(columnNames, separator))
970 }
971
972 // if format is column, write dashes under each column
973 if c.Format == "column" && !suppressHeaders {
974 lines := []string{}
975 for _, columnName := range columnNames {
976 lines = append(lines, strings.Repeat("-", len(columnName)))
977 }
978 rows = append(rows, strings.Join(lines, separator))
979 }
980
981 for _, v := range row.Values {
982 var values []string
983 if c.Format == "csv" {
984 if row.Name != "" {
985 values = append(values, row.Name)
986 }
987 if len(tags) > 0 {
988 values = append(values, strings.Join(tags, ","))
989 }
990 }
991
992 for _, vv := range v {
993 values = append(values, interfaceToString(vv))
994 }
995 rows = append(rows, strings.Join(values, separator))
996 }
997 }
998 return rows
999 }
1000
1001 func interfaceToString(v interface{}) string {
1002 switch t := v.(type) {
1003 case nil:
1004 return ""
1005 case bool:
1006 return fmt.Sprintf("%v", v)
1007 case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr:
1008 return fmt.Sprintf("%d", t)
1009 case float32, float64:
1010 return fmt.Sprintf("%v", t)
1011 default:
1012 return fmt.Sprintf("%v", t)
1013 }
1014 }
1015
1016 // Settings prints current settings.
1017 func (c *CommandLine) Settings() {
1018 w := new(tabwriter.Writer)
1019 w.Init(os.Stdout, 0, 1, 1, ' ', 0)
1020 fmt.Fprintln(w, "Setting\tValue")
1021 fmt.Fprintln(w, "--------\t--------")
1022 if c.Port > 0 {
1023 fmt.Fprintf(w, "Host\t%s:%d\n", c.Host, c.Port)
1024 } else {
1025 fmt.Fprintf(w, "Host\t%s\n", c.Host)
1026 }
1027 fmt.Fprintf(w, "Username\t%s\n", c.ClientConfig.Username)
1028 fmt.Fprintf(w, "Database\t%s\n", c.Database)
1029 fmt.Fprintf(w, "RetentionPolicy\t%s\n", c.RetentionPolicy)
1030 fmt.Fprintf(w, "Pretty\t%v\n", c.Pretty)
1031 fmt.Fprintf(w, "Format\t%s\n", c.Format)
1032 fmt.Fprintf(w, "Write Consistency\t%s\n", c.ClientConfig.WriteConsistency)
1033 fmt.Fprintf(w, "Chunked\t%v\n", c.Chunked)
1034 fmt.Fprintf(w, "Chunk Size\t%d\n", c.ChunkSize)
1035 fmt.Fprintln(w)
1036 w.Flush()
1037 }
1038
1039 func (c *CommandLine) help() {
1040 fmt.Println(`Usage:
1041 connect <host:port> connects to another node specified by host:port
1042 auth prompts for username and password
1043 pretty toggles pretty print for the json format
1044 chunked turns on chunked responses from server
1045 chunk size <size> sets the size of the chunked responses. Set to 0 to reset to the default chunked size
1046 use <db_name> sets current database
1047 format <format> specifies the format of the server responses: json, csv, or column
1048 precision <format> specifies the format of the timestamp: rfc3339, h, m, s, ms, u or ns
1049 consistency <level> sets write consistency level: any, one, quorum, or all
1050 history displays command history
1051 settings outputs the current settings for the shell
1052 clear clears settings such as database or retention policy. run 'clear' for help
1053 exit/quit/ctrl+d quits the influx shell
1054
1055 show databases show database names
1056 show series show series information
1057 show measurements show measurement information
1058 show tag keys show tag key information
1059 show field keys show field key information
1060
1061 A full list of influxql commands can be found at:
1062 https://docs.influxdata.com/influxdb/latest/query_language/spec/`)
1063 }
1064
1065 func (c *CommandLine) history() {
1066 var buf bytes.Buffer
1067 c.Line.WriteHistory(&buf)
1068 fmt.Print(buf.String())
1069 }
1070
1071 func (c *CommandLine) saveHistory() {
1072 if c.historyFilePath == "" {
1073 return
1074 }
1075 if historyFile, err := os.Create(c.historyFilePath); err != nil {
1076 fmt.Printf("There was an error writing history file: %s\n", err)
1077 } else {
1078 c.Line.WriteHistory(historyFile)
1079 historyFile.Close()
1080 }
1081 }
1082
1083 func (c *CommandLine) gopher() {
1084 fmt.Println(`
1085 .-::-::://:-::- .:/++/'
1086 '://:-''/oo+//++o+/.://o- ./+:
1087 .:-. '++- .o/ '+yydhy' o-
1088 .:/. .h: :osoys .smMN- :/
1089 -/:.' s- /MMMymh. '/y/ s'
1090 -+s:'''' d -mMMms// '-/o:
1091 -/++/++/////:. o: '... s- :s.
1092 :+-+s-' ':/' 's- /+ 'o:
1093 '+-'o: /ydhsh. '//. '-o- o-
1094 .y. o: .MMMdm+y ':+++:::/+:.' s:
1095 .-h/ y- 'sdmds'h -+ydds:::-.' 'h.
1096 .//-.d' o: '.' 'dsNMMMNh:.:++' :y
1097 +y. 'd 's. .s:mddds: ++ o/
1098 'N- odd 'o/. './o-s-' .---+++' o-
1099 'N' yNd .://:/:::::. -s -+/s/./s' 'o/'
1100 so' .h '''' ////s: '+. .s +y'
1101 os/-.y' 's' 'y::+ +d'
1102 '.:o/ -+:-:.' so.---.'
1103 o' 'd-.''/s'
1104 .s' :y.''.y
1105 -s mo:::'
1106 :: yh
1107 // '''' /M'
1108 o+ .s///:/. 'N:
1109 :+ /: -s' ho
1110 's- -/s/:+/.+h' +h
1111 ys' ':' '-. -d
1112 oh .h
1113 /o .s
1114 s. .h
1115 -y .d
1116 m/ -h
1117 +d /o
1118 'N- y:
1119 h: m.
1120 s- -d
1121 o- s+
1122 +- 'm'
1123 s/ oo--.
1124 y- /s ':+'
1125 s' 'od--' .d:
1126 -+ ':o: ':+-/+
1127 y- .:+- '
1128 //o- '.:+/.
1129 .-:+/' ''-/+/.
1130 ./:' ''.:o+/-'
1131 .+o:/:/+-' ''.-+ooo/-'
1132 o: -h///++////-.
1133 /: .o/
1134 //+ 'y
1135 ./sooy.`)
1136 }
1137
1138 // Version prints the CLI version.
1139 func (c *CommandLine) Version() {
1140 fmt.Println("InfluxDB shell version:", c.ClientVersion)
1141 }
1142
1143 func (c *CommandLine) exit() {
1144 // write to history file
1145 c.saveHistory()
1146 // release line resources
1147 c.Line.Close()
1148 c.Line = nil
1149 }