コード例 #1
0
ファイル: main.go プロジェクト: ashanbrown/influxdb
func main() {
	c := CommandLine{}

	fs := flag.NewFlagSet("InfluxDB shell version "+version, flag.ExitOnError)
	fs.StringVar(&c.Host, "host", client.DefaultHost, "Influxdb host to connect to.")
	fs.IntVar(&c.Port, "port", client.DefaultPort, "Influxdb port to connect to.")
	fs.StringVar(&c.Username, "username", c.Username, "Username to connect to the server.")
	fs.StringVar(&c.Password, "password", c.Password, `Password to connect to the server.  Leaving blank will prompt for password (--password="").`)
	fs.StringVar(&c.Database, "database", c.Database, "Database to connect to the server.")
	fs.BoolVar(&c.Ssl, "ssl", false, "Use https for connecting to cluster.")
	fs.StringVar(&c.Format, "format", defaultFormat, "Format specifies the format of the server responses:  json, csv, or column.")
	fs.StringVar(&c.Precision, "precision", defaultPrecision, "Precision specifies the format of the timestamp:  rfc3339,h,m,s,ms,u or ns.")
	fs.StringVar(&c.WriteConsistency, "consistency", "any", "Set write consistency level: any, one, quorum, or all.")
	fs.BoolVar(&c.Pretty, "pretty", false, "Turns on pretty print for the json format.")
	fs.StringVar(&c.Execute, "execute", c.Execute, "Execute command and quit.")
	fs.BoolVar(&c.ShowVersion, "version", false, "Displays the InfluxDB version.")
	fs.BoolVar(&c.Import, "import", false, "Import a previous database.")
	fs.IntVar(&c.PPS, "pps", defaultPPS, "How many points per second the import will allow.  By default it is zero and will not throttle importing.")
	fs.StringVar(&c.Path, "path", "", "path to the file to import")
	fs.BoolVar(&c.Compressed, "compressed", false, "set to true if the import file is compressed")

	// Define our own custom usage to print
	fs.Usage = func() {
		fmt.Println(`Usage of influx:
  -version
       Display the version and exit.
  -host 'host name'
       Host to connect to.
  -port 'port #'
       Port to connect to.
  -database 'database name'
       Database to connect to the server.
  -password 'password'
      Password to connect to the server.  Leaving blank will prompt for password (--password '').
  -username 'username'
       Username to connect to the server.
  -ssl
        Use https for requests.
  -execute 'command'
       Execute command and quit.
  -format 'json|csv|column'
       Format specifies the format of the server responses:  json, csv, or column.
  -precision 'rfc3339|h|m|s|ms|u|ns'
       Precision specifies the format of the timestamp:  rfc3339, h, m, s, ms, u or ns.
  -consistency 'any|one|quorum|all'
       Set write consistency level: any, one, quorum, or all
  -pretty
       Turns on pretty print for the json format.
  -import
       Import a previous database export from file
  -pps
       How many points per second the import will allow.  By default it is zero and will not throttle importing.
  -path
       Path to file to import
  -compressed
       Set to true if the import file is compressed

Examples:

    # Use influx in a non-interactive mode to query the database "metrics" and pretty print json:
    $ influx -database 'metrics' -execute 'select * from cpu' -format 'json' -pretty

    # Connect to a specific database on startup and set database context:
    $ influx -database 'metrics' -host 'localhost' -port '8086'
`)
	}
	fs.Parse(os.Args[1:])

	if c.ShowVersion {
		showVersion()
		os.Exit(0)
	}

	var promptForPassword bool
	// determine if they set the password flag but provided no value
	for _, v := range os.Args {
		v = strings.ToLower(v)
		if (strings.HasPrefix(v, "-password") || strings.HasPrefix(v, "--password")) && c.Password == "" {
			promptForPassword = true
			break
		}
	}

	c.Line = liner.NewLiner()
	defer c.Line.Close()

	if promptForPassword {
		p, e := c.Line.PasswordPrompt("password: "******"Unable to parse password.")
		} else {
			c.Password = p
		}
	}

	if err := c.connect(""); err != nil {
		fmt.Fprintf(os.Stderr,
			"Failed to connect to %s\nPlease check your connection settings and ensure 'influxd' is running.\n",
			c.Client.Addr())
		return
	}

	if c.Execute == "" && !c.Import {
		token, err := c.DatabaseToken()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to check token: %s\n", err.Error())
			return
		}
		if token == "" {
			fmt.Printf(noTokenMsg)
		}
		fmt.Printf("Connected to %s version %s\n", c.Client.Addr(), c.Version)
	}

	if c.Execute != "" {
		// Modify precision before executing query
		c.SetPrecision(c.Precision)
		if err := c.ExecuteQuery(c.Execute); err != nil {
			c.Line.Close()
			os.Exit(1)
		}
		c.Line.Close()
		os.Exit(0)
	}

	if c.Import {
		path := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
		u, e := client.ParseConnectionString(path, c.Ssl)
		if e != nil {
			fmt.Println(e)
			return
		}

		config := v8.NewConfig()
		config.Username = c.Username
		config.Password = c.Password
		config.Precision = "ns"
		config.WriteConsistency = "any"
		config.Path = c.Path
		config.Version = version
		config.URL = u
		config.Compressed = c.Compressed
		config.PPS = c.PPS
		config.Precision = c.Precision

		i := v8.NewImporter(config)
		if err := i.Import(); err != nil {
			fmt.Printf("ERROR: %s\n", err)
			c.Line.Close()
			os.Exit(1)
		}
		c.Line.Close()
		os.Exit(0)
	}

	showVersion()

	var historyFile string
	usr, err := user.Current()
	// Only load history if we can get the user
	if err == nil {
		historyFile = filepath.Join(usr.HomeDir, ".influx_history")

		if f, err := os.Open(historyFile); err == nil {
			c.Line.ReadHistory(f)
			f.Close()
		}
	}

	for {
		l, e := c.Line.Prompt("> ")
		if e != nil {
			break
		}
		if c.ParseCommand(l) {
			// write out the history
			if len(historyFile) > 0 {
				c.Line.AppendHistory(l)
				if f, err := os.Create(historyFile); err == nil {
					c.Line.WriteHistory(f)
					f.Close()
				}
			}
		} else {
			break // exit main loop
		}
	}
}
コード例 #2
0
ファイル: cli.go プロジェクト: olivierHa/influxdb
// Run executes the CLI
func (c *CommandLine) Run() error {
	// register OS signals for graceful termination
	if !c.IgnoreSignals {
		signal.Notify(c.osSignals, os.Kill, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
	}

	var promptForPassword bool
	// determine if they set the password flag but provided no value
	for _, v := range os.Args {
		v = strings.ToLower(v)
		if (strings.HasPrefix(v, "-password") || strings.HasPrefix(v, "--password")) && c.Password == "" {
			promptForPassword = true
			break
		}
	}

	c.Line = liner.NewLiner()
	defer c.Line.Close()

	c.Line.SetMultiLineMode(true)

	if promptForPassword {
		p, e := c.Line.PasswordPrompt("password: "******"Unable to parse password.")
		} else {
			c.Password = p
		}
	}

	if err := c.Connect(""); err != nil {
		return fmt.Errorf(
			"Failed to connect to %s\nPlease check your connection settings and ensure 'influxd' is running.",
			c.Client.Addr())
	}

	// Modify precision.
	c.SetPrecision(c.Precision)

	if c.Execute == "" && !c.Import {
		token, err := c.DatabaseToken()
		if err != nil {
			return fmt.Errorf("Failed to check token: %s", err.Error())
		}
		if token == "" {
			fmt.Printf(noTokenMsg)
		}
		fmt.Printf("Connected to %s version %s\n", c.Client.Addr(), c.ServerVersion)
	}

	if c.Execute != "" {
		// Make the non-interactive mode send everything through the CLI's parser
		// the same way the interactive mode works
		lines := strings.Split(c.Execute, "\n")
		for _, line := range lines {
			c.ParseCommand(line)
		}

		c.Line.Close()
		return nil
	}

	if c.Import {
		path := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
		u, e := client.ParseConnectionString(path, c.Ssl)
		if e != nil {
			return e
		}

		config := v8.NewConfig()
		config.Username = c.Username
		config.Password = c.Password
		config.Precision = "ns"
		config.WriteConsistency = "any"
		config.Path = c.Path
		config.Version = c.ClientVersion
		config.URL = u
		config.Compressed = c.Compressed
		config.PPS = c.PPS
		config.Precision = c.Precision

		i := v8.NewImporter(config)
		if err := i.Import(); err != nil {
			err = fmt.Errorf("ERROR: %s\n", err)
			c.Line.Close()
			return err
		}
		c.Line.Close()
		return nil
	}

	c.Version()

	usr, err := user.Current()
	// Only load/write history if we can get the user
	if err == nil {
		c.historyFilePath = filepath.Join(usr.HomeDir, ".influx_history")
		if historyFile, err := os.Open(c.historyFilePath); err == nil {
			c.Line.ReadHistory(historyFile)
			historyFile.Close()
		}
	}

	// read from prompt until exit is run
	for {
		select {
		case <-c.osSignals:
			close(c.Quit)
		case <-c.Quit:
			c.exit()
			return nil
		default:
			l, e := c.Line.Prompt("> ")
			if e == io.EOF {
				// Instead of die, register that someone exited the program gracefully
				l = "exit"
			} else if e != nil {
				break
			}
			if c.ParseCommand(l) {
				c.Line.AppendHistory(l)
				c.saveHistory()
			}
		}
	}
}
コード例 #3
0
ファイル: cli.go プロジェクト: rzagabe/telegraf
func (c *CommandLine) Run() {
	var promptForPassword bool
	// determine if they set the password flag but provided no value
	for _, v := range os.Args {
		v = strings.ToLower(v)
		if (strings.HasPrefix(v, "-password") || strings.HasPrefix(v, "--password")) && c.Password == "" {
			promptForPassword = true
			break
		}
	}

	c.Line = liner.NewLiner()
	defer c.Line.Close()

	if promptForPassword {
		p, e := c.Line.PasswordPrompt("password: "******"Unable to parse password.")
		} else {
			c.Password = p
		}
	}

	if err := c.Connect(""); err != nil {
		fmt.Fprintf(os.Stderr,
			"Failed to connect to %s\nPlease check your connection settings and ensure 'influxd' is running.\n",
			c.Client.Addr())
		return
	}

	if c.Execute == "" && !c.Import {
		token, err := c.DatabaseToken()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to check token: %s\n", err.Error())
			return
		}
		if token == "" {
			fmt.Printf(noTokenMsg)
		}
		fmt.Printf("Connected to %s version %s\n", c.Client.Addr(), c.ServerVersion)
	}

	if c.Execute != "" {
		// Modify precision before executing query
		c.SetPrecision(c.Precision)
		if err := c.ExecuteQuery(c.Execute); err != nil {
			c.Line.Close()
			os.Exit(1)
		}
		c.Line.Close()
		os.Exit(0)
	}

	if c.Import {
		path := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
		u, e := client.ParseConnectionString(path, c.Ssl)
		if e != nil {
			fmt.Println(e)
			return
		}

		config := v8.NewConfig()
		config.Username = c.Username
		config.Password = c.Password
		config.Precision = "ns"
		config.WriteConsistency = "any"
		config.Path = c.Path
		config.Version = c.ClientVersion
		config.URL = u
		config.Compressed = c.Compressed
		config.PPS = c.PPS
		config.Precision = c.Precision

		i := v8.NewImporter(config)
		if err := i.Import(); err != nil {
			fmt.Printf("ERROR: %s\n", err)
			c.Line.Close()
			os.Exit(1)
		}
		c.Line.Close()
		os.Exit(0)
	}

	c.Version()

	var historyFile string
	usr, err := user.Current()
	// Only load history if we can get the user
	if err == nil {
		historyFile = filepath.Join(usr.HomeDir, ".influx_history")

		if f, err := os.Open(historyFile); err == nil {
			c.Line.ReadHistory(f)
			f.Close()
		}
	}

	for {
		l, e := c.Line.Prompt("> ")
		if e != nil {
			break
		}
		if c.ParseCommand(l) {
			// write out the history
			if len(historyFile) > 0 {
				c.Line.AppendHistory(l)
				if f, err := os.Create(historyFile); err == nil {
					c.Line.WriteHistory(f)
					f.Close()
				}
			}
		} else {
			break // exit main loop
		}
	}
}
コード例 #4
0
ファイル: cli.go プロジェクト: Wind0r/influxdb
// Run executes the CLI
func (c *CommandLine) Run() {
	// register OS signals for graceful termination
	signal.Notify(c.osSignals, os.Kill, os.Interrupt, syscall.SIGTERM)

	var promptForPassword bool
	// determine if they set the password flag but provided no value
	for _, v := range os.Args {
		v = strings.ToLower(v)
		if (strings.HasPrefix(v, "-password") || strings.HasPrefix(v, "--password")) && c.Password == "" {
			promptForPassword = true
			break
		}
	}

	c.Line = liner.NewLiner()
	defer c.Line.Close()

	c.Line.SetMultiLineMode(true)

	if promptForPassword {
		p, e := c.Line.PasswordPrompt("password: "******"Unable to parse password.")
		} else {
			c.Password = p
		}
	}

	if err := c.Connect(""); err != nil {
		fmt.Fprintf(os.Stderr,
			"Failed to connect to %s\nPlease check your connection settings and ensure 'influxd' is running.\n",
			c.Client.Addr())
		return
	}

	if c.Execute == "" && !c.Import {
		token, err := c.DatabaseToken()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to check token: %s\n", err.Error())
			return
		}
		if token == "" {
			fmt.Printf(noTokenMsg)
		}
		fmt.Printf("Connected to %s version %s\n", c.Client.Addr(), c.ServerVersion)
	}

	if c.Execute != "" {
		// Modify precision before executing query
		c.SetPrecision(c.Precision)
		if err := c.ExecuteQuery(c.Execute); err != nil {
			c.Line.Close()
			os.Exit(1)
		}
		c.Line.Close()
		os.Exit(0)
	}

	if c.Import {
		path := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
		u, e := client.ParseConnectionString(path, c.Ssl)
		if e != nil {
			fmt.Println(e)
			return
		}

		config := v8.NewConfig()
		config.Username = c.Username
		config.Password = c.Password
		config.Precision = "ns"
		config.WriteConsistency = "any"
		config.Path = c.Path
		config.Version = c.ClientVersion
		config.URL = u
		config.Compressed = c.Compressed
		config.PPS = c.PPS
		config.Precision = c.Precision

		i := v8.NewImporter(config)
		if err := i.Import(); err != nil {
			fmt.Printf("ERROR: %s\n", err)
			c.Line.Close()
			os.Exit(1)
		}
		c.Line.Close()
		os.Exit(0)
	}

	c.Version()

	var historyFilePath string
	usr, err := user.Current()
	// Only load/write history if we can get the user
	if err == nil {
		historyFilePath = filepath.Join(usr.HomeDir, ".influx_history")
		if c.historyFile, err = os.OpenFile(historyFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0640); err == nil {
			defer c.historyFile.Close()
			c.Line.ReadHistory(c.historyFile)
		}
	}

	// read from prompt until exit is run
	for {
		select {
		case <-c.osSignals:
			close(c.Quit)
		case <-c.Quit:
			c.exit()
		default:
			l, e := c.Line.Prompt("> ")
			if e != nil {
				break
			}
			if c.ParseCommand(l) {
				c.Line.AppendHistory(l)
				_, err := c.Line.WriteHistory(c.historyFile)
				if err != nil {
					fmt.Printf("There was an error writing history file: %s\n", err)
				}
			}
		}
	}
}