Example #1
0
// Run the console.
func Console(config core.Config) (err error) {
	fmt.Printf(`
Welcome to the Gate administration console!

Gate Copyright (C) 2012-2015 Cyril Adrian <*****@*****.**>
This program comes with ABSOLUTELY NO WARRANTY; for details type show w.
This is free software, and you are welcome to redistribute it
under certain conditions; type show c for details.

Type help for details on available options.
Just hit <enter> to exit.

`)

	srv, err := proxy(config)
	if err != nil {
		return
	}

	remoter := remote.NewRemoter(srv, config)
	if err != nil {
		return
	}

	mmi, err := ui.Ui(srv, config)
	if err != nil {
		return
	}

	commander, err := commands.NewCommander(remoter, srv, config, mmi)
	if err != nil {
		return
	}

	state := liner.NewLiner()
	defer state.Close()

	rl := &readline{
		commander: commander,
		server:    srv,
		state:     state,
	}

	complete := func(line string) (result []string) {
		result, err := rl.complete(line)
		if err != nil {
			fmt.Println(err)
			return
		}
		return
	}

	state.SetCompleter(complete)

	e := rl.loop(config)
	if e != io.EOF {
		err = e
	}
	return
}
Example #2
0
func execshell(line string, t *testing.T) {
	go_n1ql.SetPassthroughMode(true)
	var liner = liner.NewLiner()
	defer liner.Close()

	var b bytes.Buffer
	w := bufio.NewWriter(&b)
	command.SetWriter(w)

	errC, errS := ExecShellCmd(line, liner)
	w.Flush()
	if errC != 0 {
		if strings.HasPrefix(line, "\\Sample") {
			t.Logf("Expected Error :: %v, %s", line, command.HandleError(errC, errS))
		} else {
			t.Errorf("Error :: %v, %s", line, command.HandleError(errC, errS))
		}
	} else {
		if strings.HasPrefix(line, "\\Sample") {
			t.Errorf("Expected error for command %v. It doesnt exist.", line)
		} else {
			t.Log("Ran command ", line, " successfully.")
			t.Logf("%s", b.String())
		}

	}
	b.Reset()
}
Example #3
0
func handleInteractiveMode() {

	currentUser, err := user.Current()
	if err != nil {
		log.Printf("Unable to determine home directory, history file disabled")
	}

	var liner = liner.NewLiner()
	defer liner.Close()

	LoadHistory(liner, currentUser)

	go signalCatcher(liner)

	for {
		line, err := liner.Prompt("tuq> ")
		if err != nil {
			break
		}

		if line == "" {
			continue
		}

		UpdateHistory(liner, currentUser, line)
		err = execute_internal(line, os.Stdout)
		if err != nil {
			log.Printf("%v", err)
		}
	}

}
Example #4
0
func init() {
	fmt.Println(`
************************
** PAW-Go interpreter **
************************
`)
	fmt.Printf(":: available commands:\n%v\n::\n\n", env)

	term = liner.NewLiner()

	fname := path.Join(os.Getenv("HOME"), ".pawgo.history")
	f, err := os.Open(fname)
	if err != nil {
		f, err = os.Create(fname)
		if err != nil {
			fmt.Printf("**warning: could not access nor create history file [%s]\n", fname)
			return
		}
	}
	defer f.Close()
	_, err = term.ReadHistory(f)
	if err != nil {
		fmt.Printf("**warning: could not read history file [%s]\n", fname)
		return
	}

	term.SetCompleter(paw_completer)
}
Example #5
0
func HandleInteractiveMode(tiServer, prompt string) {

	// try to find a HOME environment variable
	homeDir := os.Getenv("HOME")
	if homeDir == "" {
		// then try USERPROFILE for Windows
		homeDir = os.Getenv("USERPROFILE")
		if homeDir == "" {
			fmt.Printf("Unable to determine home directory, history file disabled\n")
		}
	}

	var liner = liner.NewLiner()
	defer liner.Close()

	LoadHistory(liner, homeDir)

	go signalCatcher(liner)

	// state for reading a multi-line query
	queryLines := []string{}
	fullPrompt := prompt + QRY_PROMPT1
	for {
		line, err := liner.Prompt(fullPrompt)
		if err != nil {
			break
		}

		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		// Building query string mode: set prompt, gather current line
		fullPrompt = QRY_PROMPT2
		queryLines = append(queryLines, line)

		// If the current line ends with a QRY_EOL, join all query lines,
		// trim off trailing QRY_EOL characters, and submit the query string:
		if strings.HasSuffix(line, QRY_EOL) {
			queryString := strings.Join(queryLines, " ")
			for strings.HasSuffix(queryString, QRY_EOL) {
				queryString = strings.TrimSuffix(queryString, QRY_EOL)
			}
			if queryString != "" {
				UpdateHistory(liner, homeDir, queryString+QRY_EOL)
				err = execute_internal(tiServer, queryString, os.Stdout)
				if err != nil {
					s_err := handleError(err, tiServer)
					fmt.Println(fgRed, "ERROR", s_err.Code(), ":", s_err, reset)
				}
			}
			// reset state for multi-line query
			queryLines = []string{}
			fullPrompt = prompt + QRY_PROMPT1
		}
	}

}
Example #6
0
func execn1ql(line string, t *testing.T) bool {
	go_n1ql.SetPassthroughMode(true)
	var liner = liner.NewLiner()
	defer liner.Close()

	var b bytes.Buffer
	w := bufio.NewWriter(&b)
	command.SetWriter(w)

	n1ql, err := sql.Open("n1ql", Server)
	if err != nil {
		// If the test cannot connect to a server
		// don't execute the TestExecN1QLStmt method.
		testconn := false
		t.Logf("Cannot connect to %v", Server)
		return testconn
	} else {
		//Successfully logged into the server
		//For the case where server url is valid
		//sql.Open will not throw an error. Hence ping
		//the server and see if it returns an error.

		err = n1ql.Ping()

		if err != nil {
			testconn := false
			t.Logf("Cannot connect to %v", Server)
			return testconn
		}

		errC, errS := ExecN1QLStmt(line, n1ql, w)
		w.Flush()
		if errC != 0 {
			t.Errorf("Error executing statement : %v", line)
			t.Error(command.HandleError(errC, errS))
		} else {
			t.Log("Ran command ", line, " successfully.")
			t.Logf("%s", b.String())
		}
	}
	b.Reset()
	return true
}
Example #7
0
func execline(line string, t *testing.T) {
	go_n1ql.SetPassthroughMode(true)
	var liner = liner.NewLiner()
	defer liner.Close()

	var b bytes.Buffer
	w := bufio.NewWriter(&b)
	command.SetWriter(w)

	errC, errS := execute_input(line, w, true, liner)
	w.Flush()
	if errC != 0 {
		t.Errorf("Error :: %v, %s", line, command.HandleError(errC, errS))
	} else {
		t.Log("Ran command ", line, " successfully.")
		t.Logf("%s", b.String())
	}
	b.Reset()
}
Example #8
0
func setupPrompt() {
	quit := make(chan bool)

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	state := liner.NewLiner()
	go promptLoop(quit, state)

	go func() {
		<-c
		fmt.Println()
		quit <- true
	}()

	go func() {
		<-quit
		state.Close()
		os.Exit(0)
	}()
}
Example #9
0
func main() {
	term := liner.NewLiner()
	defer term.Close()

	fmt.Println("Skynet Interactive Shell")

	term.SetCompleter(tabCompleter)

	for {
		l, e := term.Prompt("> ")
		if e != nil {
			break
		}

		s := string(l)
		parts := strings.Split(s, " ")
		//fmt.Println("receive input:",s)

		validCommand := true

		switch parts[0] {
		case "exit", "quit":
			term.Close()
			syscall.Exit(0)
		case "help", "h":
			InteractiveShellHelp()

		case "services":
		case "regions":
		case "filters":
		default:
			validCommand = false
			fmt.Println("Unknown Command - type 'help' for a list of commands")
		}

		if validCommand {
			term.AppendHistory(s)
		}
	}
}
Example #10
0
File: igo.go Project: szqh97/test
func init() {
	fmt.Println(`
*********************************************
** Interactive Go interpreter (with liner) **
*********************************************

`)
	term = liner.NewLiner()

	fname := path.Join(os.Getenv("HOME"), ".go.history")
	f, err := os.Open(fname)
	if err != nil {
		fmt.Printf("**warning: could not access history file [%s]\n", fname)
		return
	}
	defer f.Close()
	_, err = term.ReadHistory(f)
	if err != nil {
		fmt.Printf("**warning: could not read history file [%s]\n", fname)
		return
	}
}
Example #11
0
func HandleInteractiveMode(tiServer, prompt string) {

	// try to find a HOME environment variable
	homeDir := os.Getenv("HOME")
	if homeDir == "" {
		// then try USERPROFILE for Windows
		homeDir = os.Getenv("USERPROFILE")
		if homeDir == "" {
			fmt.Printf("Unable to determine home directory, history file disabled\n")
		}
	}

	var liner = liner.NewLiner()
	defer liner.Close()

	LoadHistory(liner, homeDir)

	go signalCatcher(liner)

	for {
		line, err := liner.Prompt(prompt + "> ")
		if err != nil {
			break
		}

		if line == "" {
			continue
		}

		UpdateHistory(liner, homeDir, line)
		err = execute_internal(tiServer, line, os.Stdout)
		if err != nil {
			clog.Error(err)
		}
	}

}
Example #12
0
func main() {

	flag.Parse()

	esURL, err := url.Parse(*esURLString)
	if err != nil {
		log.Fatalf("Unable to parse esURL: %s error: %v", esURL, err)
	} else {
		api.Protocol = esURL.Scheme
		colonIndex := strings.Index(esURL.Host, ":")
		if colonIndex < 0 {
			api.Domain = esURL.Host
			api.Port = "9200"
		} else {
			api.Domain = esURL.Host[0:colonIndex]
			api.Port = esURL.Host[colonIndex+1:]
		}

	}

	currentUser, err := user.Current()
	if err != nil {
		log.Printf("Unable to determine home directory, history file disabled")
	}

	var liner = liner.NewLiner()
	defer liner.Close()

	LoadHistory(liner, currentUser)

	go signalCatcher(liner)

	for {
		line, err := liner.Prompt("unql-couchbase> ")
		if err != nil {
			break
		}

		if line == "" {
			continue
		}

		UpdateHistory(liner, currentUser, line)

		query, err := processNextLine(line)
		if err != nil {
			log.Printf("%v", err)
		} else {
			if *debugGrammar {
				log.Printf("Query is: %#v", query)
			}
			if query.parsedSuccessfully {
				result, err := query.Execute()
				if err != nil {
					log.Printf("Error: %v", err)
				} else {
					FormatOutput(result)
				}
			}
		}
	}

}
Example #13
0
/* This method is used to handle user interaction with the
   cli. After combining the multi line input, it is sent to
   the execute_inpu method which parses and executes the
   input command. In the event an error is returned from the
   query execution, it is printed in red. The input prompt is
   the name of the executable.
*/
func HandleInteractiveMode(prompt string) {

	// Variables used for output to file
	var err error
	outputFile := os.Stdout
	prevFile := ""
	prevreset := command.Getreset()
	prevfgRed := command.GetfgRed()

	// If an output flag is defined
	if outputFlag != "" {
		prevFile = command.FILE_OUTPUT
		outputFile, err = os.OpenFile(command.FILE_OUTPUT, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
		command.SetDispVal("", "")
		if err != nil {
			s_err := command.HandleError(errors.FILE_OPEN, err.Error())
			command.PrintError(s_err)
		}

		defer outputFile.Close()
		command.SetWriter(io.Writer(outputFile))
	}

	/* Find the HOME environment variable. If it isnt set then
	   try USERPROFILE for windows. If neither is found then
	   the cli cant find the history file to read from.
	*/
	homeDir = os.Getenv("HOME")
	if homeDir == "" {
		homeDir = os.Getenv("USERPROFILE")
		if homeDir == "" {
			_, werr := io.WriteString(command.W, "Unable to determine home directory, history file disabled\n")
			if werr != nil {
				s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
				command.PrintError(s_err)
			}
		}
	}

	/* Create a new liner */
	var liner = liner.NewLiner()
	defer liner.Close()

	/* Load history from Home directory
	 */
	err_code, err_string := LoadHistory(liner, homeDir)
	if err_code != 0 {
		s_err := command.HandleError(err_code, err_string)
		command.PrintError(s_err)
	}

	go signalCatcher(liner)

	// state for reading a multi-line query
	inputLine := []string{}
	fullPrompt := prompt + QRY_PROMPT1

	// Handle the file input and script options here so as to add
	// the commands to the history.
	if scriptFlag != "" {
		//Execute the input command
		go_n1ql.SetPassthroughMode(true)

		// If outputting to a file, then add the statement to the file as well.
		if command.FILE_RW_MODE == true {
			_, werr := io.WriteString(command.W, scriptFlag+"\n")
			if werr != nil {
				s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
				command.PrintError(s_err)
			}
		}

		err_code, err_str := execute_input(scriptFlag, command.W, false, liner)
		if err_code != 0 {
			s_err := command.HandleError(err_code, err_str)
			command.PrintError(s_err)
			liner.Close()
			os.Clearenv()
			os.Exit(1)
		}
		liner.Close()
		os.Clearenv()
		os.Exit(0)
	}

	if inputFlag != "" {
		//Read each line from the file and call execute query
		go_n1ql.SetPassthroughMode(true)
		input_command := "\\source " + inputFlag

		// If outputting to a file, then add the statement to the file as well.
		if command.FILE_RW_MODE == true {
			_, werr := io.WriteString(command.W, input_command+"\n")
			if werr != nil {
				s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
				command.PrintError(s_err)
			}
		}

		errCode, errStr := execute_input(input_command, command.W, false, liner)
		if errCode != 0 {
			s_err := command.HandleError(errCode, errStr)
			command.PrintError(s_err)
			liner.Close()
			os.Clearenv()
			os.Exit(1)
		}
		liner.Close()
		os.Clearenv()
		os.Exit(0)
	}
	// End handling the options

	for {
		line, err := liner.Prompt(fullPrompt)
		if err != nil {
			break
		}

		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		// Redirect command
		prevFile, outputFile = redirectTo(prevFile, prevreset, prevfgRed)

		if outputFile == os.Stdout {
			command.SetDispVal(prevreset, prevfgRed)
			command.SetWriter(os.Stdout)
		} else {
			if outputFile != nil {
				defer outputFile.Close()
				command.SetWriter(io.Writer(outputFile))
			}
		}
		/* Check for shell comments : -- and #. Add them to the history
		   but do not send them to be parsed.
		*/
		if strings.HasPrefix(line, "--") || strings.HasPrefix(line, "#") {
			err_code, err_string := UpdateHistory(liner, homeDir, line)
			if err_code != 0 {
				s_err := command.HandleError(err_code, err_string)
				command.PrintError(s_err)
			}

			continue
		}

		// Building query string mode: set prompt, gather current line
		fullPrompt = QRY_PROMPT2
		inputLine = append(inputLine, line)

		/* If the current line ends with a QRY_EOL, join all query lines,
		   trim off trailing QRY_EOL characters, and submit the query string.
		*/
		if strings.HasSuffix(line, QRY_EOL) {
			inputString := strings.Join(inputLine, " ")
			for strings.HasSuffix(inputString, QRY_EOL) {
				inputString = strings.TrimSuffix(inputString, QRY_EOL)
			}
			if inputString != "" {
				err_code, err_string := UpdateHistory(liner, homeDir, inputString+QRY_EOL)
				if err_code != 0 {
					s_err := command.HandleError(err_code, err_string)
					command.PrintError(s_err)
				}
				// If outputting to a file, then add the statement to the file as well.
				if command.FILE_RW_MODE == true {
					_, werr := io.WriteString(command.W, "\n"+inputString+"\n")
					if werr != nil {
						s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
						command.PrintError(s_err)
					}
				}
				err_code, err_string = execute_input(inputString, command.W, true, liner)
				/* Error handling for Shell errors and errors recieved from
				   go_n1ql.
				*/
				if err_code != 0 {
					s_err := command.HandleError(err_code, err_string)
					if err_code == errors.GON1QL_QUERY {
						//Dont print the error code for query errors.
						tmpstr := fmt.Sprintln(command.GetfgRed(), s_err, command.Getreset())
						io.WriteString(command.W, tmpstr+"\n")

					} else {
						command.PrintError(s_err)
					}

					if *errorExitFlag == true {
						if first == false {
							first = true
							_, werr := io.WriteString(command.W, "Exiting on first error encountered\n")
							if werr != nil {
								s_err = command.HandleError(errors.WRITER_OUTPUT, werr.Error())
								command.PrintError(s_err)
							}
							liner.Close()
							os.Clearenv()
							os.Exit(1)
						}
					}
				}

				/* For the \EXIT and \QUIT shell commands we need to
				   make sure that we close the liner and then exit. In
				   the event an error is returned from execute_input after
				   the \EXIT command, then handle the error and exit with
				   exit code 1 (which is for general errors).
				*/
				if EXIT == true {
					command.EXIT = false
					liner.Close()
					if err == nil {
						os.Exit(0)
					} else {
						os.Exit(1)
					}

				}

			}

			// reset state for multi-line query
			inputLine = []string{}
			fullPrompt = prompt + QRY_PROMPT1
		}
	}

}
Example #14
0
File: shell.go Project: reth-/mole
func shell(fwdChan chan<- conf.ForwardLine, cfg *conf.Config, dialer Dialer) {
	help := func() {
		infoln("Available commands:")
		infoln("  help, ?                          - show help")
		infoln("  quit, ^D                         - stop forwarding and exit")
		infoln("  test                             - test each forward for connection")
		infoln("  stat                             - show forwarding statistics")
		infoln("  debug                            - enable debugging")
		infoln("  fwd srcip:srcport dstip:dstport  - add forward")
	}

	term := liner.NewLiner()
	atExit(func() {
		term.Close()
	})

	// Receive commands

	commands := make(chan string)
	next := make(chan bool)
	go func() {
		for {
			prompt := "mole> "
			if debugEnabled {
				prompt = "(debug) mole> "
			}
			cmd, err := term.Prompt(prompt)
			if err == io.EOF {
				fmt.Println("quit")
				commands <- "quit"
				return
			}

			if cmd != "" {
				commands <- cmd
				term.AppendHistory(cmd)
				_, ok := <-next
				if !ok {
					return
				}
			}
		}
	}()

	// Catch ^C and treat as "quit" command

	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, os.Interrupt)
	go func() {
		<-sigchan
		fmt.Println("quit")
		commands <- "quit"
	}()

	// Handle commands

	for {
		cmd := <-commands

		parts := strings.SplitN(cmd, " ", -1)

		switch parts[0] {
		case "quit":
			close(next)
			return
		case "help", "?":
			help()
		case "stat":
			printStats()
		case "test":
			results := testForwards(dialer, cfg)
			for res := range results {
				infof(ansi.Bold(ansi.Cyan(res.name)))
				for _, line := range res.results {
					if line.err == nil {
						infof("%22s %s in %.02f ms", line.dst, ansi.Bold(ansi.Green("-ok-")), line.ms)
					} else {
						infof("%22s %s in %.02f ms (%s)", line.dst, ansi.Bold(ansi.Red("fail")), line.ms, line.err)
					}
				}
			}
		case "debug":
			infoln(msgDebugEnabled)
			debugEnabled = true
		case "fwd":
			if len(parts) != 3 {
				warnf(msgErrIncorrectFwd, cmd)
				break
			}

			src := strings.SplitN(parts[1], ":", 2)
			if len(src) != 2 {
				warnf(msgErrIncorrectFwdSrc, parts[1])
				break
			}

			var ipExists bool
			for _, ip := range currentAddresses() {
				if ip == src[0] {
					ipExists = true
					break
				}
			}
			if !ipExists {
				warnf(msgErrIncorrectFwdIP, src[0])
				break
			}

			dst := strings.SplitN(parts[2], ":", 2)
			if len(dst) != 2 {
				warnf(msgErrIncorrectFwdDst, parts[2])
				break
			}

			srcp, err := strconv.Atoi(src[1])
			if err != nil {
				warnln(err)
				break
			}
			if srcp < 1024 {
				warnf(msgErrIncorrectFwdPriv, srcp)
				break
			}

			dstp, err := strconv.Atoi(dst[1])
			if err != nil {
				warnln(err)
				break
			}
			fwd := conf.ForwardLine{
				SrcIP:   src[0],
				SrcPort: srcp,
				DstIP:   dst[0],
				DstPort: dstp,
			}
			okln("add", fwd)
			fwdChan <- fwd
		default:
			warnf(msgErrNoSuchCommand, parts[0])
		}

		next <- true
	}
}
Example #15
0
/* This method is used to handle user interaction with the
   cli. After combining the multi line input, it is sent to
   the execute_inpu method which parses and executes the
   input command. In the event an error is returned from the
   query execution, it is printed in red. The input prompt is
   the name of the executable.
*/
func HandleInteractiveMode(prompt string) {

	/* Find the HOME environment variable. If it isnt set then
	   try USERPROFILE for windows. If neither is found then
	   the cli cant find the history file to read from.
	*/
	homeDir := os.Getenv("HOME")
	if homeDir == "" {
		homeDir = os.Getenv("USERPROFILE")
		if homeDir == "" {
			_, werr := io.WriteString(command.W, "Unable to determine home directory, history file disabled\n")
			if werr != nil {
				s_err := command.HandleError(errors.WRITER_OUTPUT, werr.Error())
				command.PrintError(s_err)
			}
		}
	}

	/* Create a new liner */
	var liner = liner.NewLiner()
	defer liner.Close()

	/* Load history from Home directory
	   TODO : Once Histfile and Histsize are introduced then change this code
	*/
	err_code, err_string := LoadHistory(liner, homeDir)
	if err_code != 0 {
		s_err := command.HandleError(err_code, err_string)
		command.PrintError(s_err)
	}

	go signalCatcher(liner)

	// state for reading a multi-line query
	inputLine := []string{}
	fullPrompt := prompt + QRY_PROMPT1
	for {
		line, err := liner.Prompt(fullPrompt)
		if err != nil {
			break
		}

		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		/* Check for shell comments : -- and #. Add them to the history
		   but do not send them to be parsed.
		*/
		if strings.HasPrefix(line, "--") || strings.HasPrefix(line, "#") {
			err_code, err_string := UpdateHistory(liner, homeDir, line)
			if err_code != 0 {
				s_err := command.HandleError(err_code, err_string)
				command.PrintError(s_err)
			}

			continue
		}

		// Building query string mode: set prompt, gather current line
		fullPrompt = QRY_PROMPT2
		inputLine = append(inputLine, line)

		/* If the current line ends with a QRY_EOL, join all query lines,
		   trim off trailing QRY_EOL characters, and submit the query string.
		*/
		if strings.HasSuffix(line, QRY_EOL) {
			inputString := strings.Join(inputLine, " ")
			for strings.HasSuffix(inputString, QRY_EOL) {
				inputString = strings.TrimSuffix(inputString, QRY_EOL)
			}
			if inputString != "" {
				err_code, err_string := UpdateHistory(liner, homeDir, inputString+QRY_EOL)
				if err_code != 0 {
					s_err := command.HandleError(err_code, err_string)
					command.PrintError(s_err)
				}
				err_code, err_string = execute_input(inputString, os.Stdout)
				/* Error handling for Shell errors and errors recieved from
				   go_n1ql.
				*/
				if err_code != 0 {
					s_err := command.HandleError(err_code, err_string)
					if err_code == errors.GON1QL_QUERY {
						//Dont print the error code for query errors.
						tmpstr := fmt.Sprintln(fgRed, s_err, reset)
						io.WriteString(command.W, tmpstr+"\n")

					} else {
						command.PrintError(s_err)
					}

					if *errorExitFlag == true {
						if first == false {
							first = true
							_, werr := io.WriteString(command.W, "Exiting on first error encountered\n")
							if werr != nil {
								s_err = command.HandleError(errors.WRITER_OUTPUT, werr.Error())
								command.PrintError(s_err)
							}
							liner.Close()
							os.Clearenv()
							os.Exit(1)
						}
					}
				}

				/* For the \EXIT and \QUIT shell commands we need to
				   make sure that we close the liner and then exit. In
				   the event an error is returned from execute_input after
				   the \EXIT command, then handle the error and exit with
				   exit code 1 (which is for general errors).
				*/
				if EXIT == true {
					command.EXIT = false
					liner.Close()
					if err == nil {
						os.Exit(0)
					} else {
						os.Exit(1)
					}

				}

			}

			// reset state for multi-line query
			inputLine = []string{}
			fullPrompt = prompt + QRY_PROMPT1
		}
	}

}
Example #16
0
func handleInteractiveMode() {

	unqlParser := tuql.NewTuqlParser(*debugTokens, *debugGrammar, *crashHard)
	naivePlanner := naiveplanner.NewNaivePlanner()
	naiveOptimizer := naiveoptimizer.NewNaiveOptimizer()
	nullOptimizer := nulloptimizer.NewNullOptimizer()

	currentUser, err := user.Current()
	if err != nil {
		log.Printf("Unable to determine home directory, history file disabled")
	}

	var liner = liner.NewLiner()
	defer liner.Close()

	LoadHistory(liner, currentUser)

	go signalCatcher(liner)

	for {
		line, err := liner.Prompt("tuq> ")
		if err != nil {
			break
		}

		if line == "" {
			continue
		}

		UpdateHistory(liner, currentUser, line)

		query, err := unqlParser.Parse(line)
		if err != nil {
			log.Printf("%v", err)
		} else {
			if *debugGrammar {
				log.Printf("Query is: %#v", query)
			}
			if query.WasParsedSuccessfully() {
				// check to make sure the query is semantically valid
				err := query.Validate()
				if err != nil {
					log.Printf("%v", err)
				} else {
					plans := naivePlanner.Plan(*query)

					if plans != nil {
						var plan planner.Plan
						if *disableOptimizer {
							plan = nullOptimizer.Optimize(plans)
						} else {
							plan = naiveOptimizer.Optimize(plans)
						}

						if query.IsExplainOnly {
							result := plan.Explain()
							if err != nil {
								log.Printf("Error: %v", err)
							} else {
								FormatChannelOutput(result, os.Stdout)
							}
						} else {
							result := plan.Run()
							if err != nil {
								log.Printf("Error: %v", err)
							} else {
								FormatChannelOutput(result, os.Stdout)
							}
						}
					}
				}

			}
		}
	}

}
Example #17
0
func InteractiveShell() {
	term := liner.NewLiner()

	doozer := Doozer(config.DoozerConfig)

	fmt.Println("Welcome to Skynet...")

	query = &skynet.Query{
		DoozerConn: doozer,
	}

	term.SetCompleter(tabCompleter)

	for {
		l, e := term.Prompt("> ")
		if e != nil {
			break
		}

		s := string(l)
		parts := strings.Split(s, " ")
		validCommand := true

		switch parts[0] {
		case "deploy":
			if len(parts) >= 2 {
				if confirm(term, "Service will be deployed to "+strconv.Itoa(len(query.FindHosts()))+" hosts") {
					Deploy(query, parts[1], parts[2:]...)
				}
			} else {
				fmt.Println("Usage: deploy <service path> <args>")
			}
		case "exit":
			term.Close()
			syscall.Exit(0)
		case "help", "h":
			InteractiveShellHelp()
		case "services":
			ListServices(query)
		case "hosts":
			ListHosts(query)
		case "regions":
			ListRegions(query)
		case "instances":
			ListInstances(query)
		case "versions":
			ListServiceVersions(query)
		case "topology":
			PrintTopology(query)

		case "service":
			if len(parts) >= 2 {
				query.Service = parts[1]
			}

			fmt.Printf("Service: %v\n", query.Service)

		case "host":
			if len(parts) >= 2 {
				query.Host = parts[1]
			}

			fmt.Printf("Host: %v\n", query.Host)

		case "port":
			if len(parts) >= 2 {
				query.Port = parts[1]
			}

			fmt.Printf("Host: %v\n", query.Host)

		case "version":
			if len(parts) >= 2 {
				query.Version = parts[1]
			}

			fmt.Printf("Version: %v\n", query.Version)

		case "region":
			if len(parts) >= 2 {
				query.Region = parts[1]
			}

			fmt.Printf("Region: %v\n", query.Region)

		case "register":
			if confirm(term, strconv.Itoa(len(filterDaemon(query.FindInstances())))+" instances will be registered") {
				Register(query)
			}
		case "unregister":
			if confirm(term, strconv.Itoa(len(filterDaemon(query.FindInstances())))+" instances will be unregistered") {
				Unregister(query)
			}
		case "stop":
			if confirm(term, strconv.Itoa(len(filterDaemon(query.FindInstances())))+" instances will be stopped") {
				Stop(query)
			}
		case "restart":
			if confirm(term, strconv.Itoa(len(filterDaemon(query.FindInstances())))+" instances will be restarted") {
				Restart(query)
			}

		case "registered":
			if len(parts) >= 2 {
				var reg bool

				if parts[1] == "true" {
					reg = true
				} else {
					reg = false
				}

				query.Registered = &reg
			}

			registered := ""
			if query.Registered != nil {
				registered = strconv.FormatBool(*query.Registered)
			}

			fmt.Printf("Registered: %v\n", registered)

		case "reset":
			if len(parts) == 1 || parts[1] == "service" {
				query.Service = ""
			}

			if len(parts) == 1 || parts[1] == "version" {
				query.Version = ""
			}

			if len(parts) == 1 || parts[1] == "host" {
				query.Host = ""
			}

			if len(parts) == 1 || parts[1] == "port" {
				query.Port = ""
			}

			if len(parts) == 1 || parts[1] == "region" {
				query.Region = ""
			}

			if len(parts) == 1 || parts[1] == "registered" {
				query.Registered = nil
			}
		case "filters":
			registered := ""
			if query.Registered != nil {
				registered = strconv.FormatBool(*query.Registered)
			}

			fmt.Printf("Region: %v\nHost: %v\nService: %v\nVersion: %v\nRegistered: %v\n", query.Region, query.Host, query.Service, query.Version, registered)
		default:
			validCommand = false
			fmt.Println("Unknown Command - type 'help' for a list of commands")
		}

		if validCommand {
			term.AppendHistory(s)
		}
	}
}
Example #18
0
func (gs *LGGateServer) StartConsole(quit chan bool) {
    term := liner.NewLiner()
    fmt.Println("gate server console")
    defer term.Close()

    term.SetCompleter(tabCompleter)
    //reader := bufio.NewReader(os.Stdin)
    for {
        input, e := term.Prompt(gs.Name + "> ")
        if e != nil {
            break
        }
        //input, _ := reader.ReadBytes('\n')
        //cmd := string(input[:len(input)-1])
        cmd := string(input)

        cmds := strings.Split(cmd, " ")
        switch cmds[0] {
        case "/sendtoall":
            ///conn s1 :12001 0
            if len(cmds) > 1 {
                msg := strings.Join(cmds[1:], " ")

                mw := LGNewMessageWriter(gs.Datagram.GetEndian())
                mw.SetCode(2011, 0)
                mw.WriteString(msg, 0)

                dp := &LGDataPacket{
                    Type:    LGDATAPACKET_TYPE_BROADCAST,
                    Data:    mw.ToBytes(),
                    FromCid: 0,
                }

                gs.SendBroadcast(dp)
            }

        case "/setmax":
            if len(cmds) > 1 {
                max, err := strconv.Atoi(cmds[1])
                if err != nil {
                    fmt.Println("setmax is error:", err)
                    continue
                }
                gs.SetMaxConnections(max)
            } else {
                fmt.Println("please input number of max connections")
            }
        case "/restart":
            gs.Stop()
            gs.Start()
        case "/start":
            gs.Start()
        case "/stop":
            gs.Stop()
        case "/reconn":
            gs.ReConnectGrids()

        case "/exit", "/quit":
            fmt.Println("this gateserver is exit")
            quit <- true
            break
        default:
        }
    }
}
Example #19
0
func InteractiveShell() {
	term := liner.NewLiner()

	fmt.Println("Skynet Interactive Shell")

	term.SetCompleter(tabCompleter)

	for {
		l, e := term.Prompt("> ")
		if e != nil {
			break
		}

		s := string(l)
		parts := strings.Split(s, " ")
		validCommand := true

		switch parts[0] {
		case "exit", "quit":
			term.Close()
			syscall.Exit(0)
		case "help", "h":
			InteractiveShellHelp()
		case "services":
			ListServices(criteria)
		case "hosts":
			ListHosts(criteria)
		case "regions":
			ListRegions(criteria)
		case "instances":
			ListInstances(criteria)
		case "versions":
			ListVersions(criteria)
		case "build":
			Build(configFile)
		case "deploy":
			Deploy(configFile, criteria)
		case "start":
			Start(criteria, parts[1:])
		case "stop":
			Stop(criteria)
		case "restart":
			Restart(criteria)
		case "register":
			Register(criteria)
		case "unregister":
			Unregister(criteria)
		case "log":
			SetLogLevel(criteria, parts[1])
		case "daemon":
			if len(parts) >= 2 {
				switch parts[1] {
				case "log":
					if len(parts) >= 3 {
						SetDaemonLogLevel(criteria, parts[2])
					} else {
						fmt.Println("Must supply a log level")
					}
				case "stop":
					StopDaemon(criteria)
				}
			} else {
				fmt.Println("Supported subcommands for daemon are log, and stop")
			}

		case "config":
			if len(parts) >= 2 {
				configFile = parts[1]
			}

			fmt.Printf("Config: %s\n", configFile)

		case "service":
			if len(parts) >= 2 {
				criteria.AddService(serviceCriteriaFromString(parts[1]))
			}

			fmt.Printf("Services: %v\n", serviceCriteriaToString(criteria.Services))

		case "instance":
			if len(parts) >= 2 {
				criteria.AddInstance(parts[1])
			}

			fmt.Printf("Instances: %v\n", strings.Join(criteria.Instances, ", "))

		case "host":
			if len(parts) >= 2 {
				criteria.AddHost(parts[1])
			}

			fmt.Printf("Host: %v\n", strings.Join(criteria.Hosts, ", "))

		case "region":
			if len(parts) >= 2 {
				criteria.AddRegion(parts[1])
			}

			fmt.Printf("Region: %v\n", strings.Join(criteria.Regions, ", "))

		case "registered":
			if len(parts) >= 2 {
				var reg bool

				if parts[1] == "true" {
					reg = true
				} else {
					reg = false
				}

				criteria.Registered = &reg
			}

			registered := ""
			if criteria.Registered != nil {
				registered = strconv.FormatBool(*criteria.Registered)
			}

			fmt.Printf("Registered: %v\n", registered)

		case "reset":
			if len(parts) == 1 || parts[1] == "config" {
				configFile = "./build.cfg"
			}

			if len(parts) == 1 || parts[1] == "service" {
				criteria.Services = []skynet.ServiceCriteria{}
			}

			if len(parts) == 1 || parts[1] == "host" {
				criteria.Hosts = []string{}
			}

			if len(parts) == 1 || parts[1] == "region" {
				criteria.Regions = []string{}
			}

			if len(parts) == 1 || parts[1] == "registered" {
				criteria.Registered = nil
			}
		case "filters":
			registered := ""
			if criteria.Registered != nil {
				registered = strconv.FormatBool(*criteria.Registered)
			}

			fmt.Printf("Region: %v\nHost: %v\nService: %v\nRegistered: %v\nInstances: %v\n", strings.Join(criteria.Regions, ", "), strings.Join(criteria.Hosts, ", "), serviceCriteriaToString(criteria.Services), registered, strings.Join(criteria.Instances, ", "))
		case "":
		default:
			validCommand = false
			fmt.Println("Unknown Command - type 'help' for a list of commands")
		}

		if validCommand {
			term.AppendHistory(s)
		}
	}
}
Example #20
0
// clientsender(): read from stdin and send it via network
func clientsender(cid *int, client *lnet.ConnectionPool) {
	term := liner.NewLiner()
	fmt.Println("Skynet Interactive Shell")

	term.SetCompleter(tabCompleter)
	for {
		if (*cid) == 0 {
			fmt.Print("you no connect anyone server,please input conn cmd,\n")
		}
		input, e := term.Prompt("> ")
		if e != nil {
			break
		}

		//cmd := string(input[:len(input)-1])
		cmd := string(input)
		if cmd[0] == '/' {
			cmds := strings.Split(cmd, " ")
			switch cmds[0] {
			case "/conn":
				var name, addr string
				if len(cmds) > 2 {
					name = cmds[1]
					addr = cmds[2]
				} else {
					name = "c_" + strconv.Itoa(*cid)
					addr = cmds[1]
				}

				p := client.Connections.GetByName(name)
				if p != nil {
					fmt.Println(name, " is exists !")
					continue
				}

				go client.Start(name, addr)

				fmt.Print("please input your name:")
				input, _ := reader.ReadBytes('\n')
				input = input[0 : len(input)-1]

				for true {
					b := client.Connections.GetByName(name)
					if b != nil {
						change(cid, client, name)
						break
					}
					time.Sleep(2 * 1e3)
				}
				client.Connections.Get(*cid).GetTransport().SendDP(0, input)

			case "/change":
				name := cmds[1]
				change(cid, client, name)

			case "/quit\n":
				client.Connections.Get(*cid).GetTransport().SendDP(0, []byte("/quit"))

			default:
				client.Connections.Get(*cid).GetTransport().SendDP(0, input[0:len(input)-1])
			}
		} else {
			client.Connections.Get(*cid).GetTransport().SendDP(0, input[0:len(input)-1])
		}
	}
}