Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MYST-188 / CLI Client #92

Merged
merged 17 commits into from
Jan 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/client_docker/ubuntu/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ RUN apt-get update \
&& apt-get install -y --fix-broken \
&& rm -rf /var/cache/apt/* /var/lib/apt/lists/* /tmp/mysterium-client.deb

ENTRYPOINT ["/usr/bin/mysterium_client"]
ENTRYPOINT ["/usr/bin/mysterium_client", "--cli"]
2 changes: 1 addition & 1 deletion bin/client_run
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/bin/bash

sudo ./build/client/mysterium_client --runtime-dir=build/client $@
sudo ./build/client/mysterium_client --runtime-dir=build/client --cli $@
19 changes: 15 additions & 4 deletions client_connection/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ func (manager *connectionManager) Connect(id identity.Identity, nodeKey string)
}

manager.vpnClient, err = manager.vpnClientFactory(*vpnSession, id)

if err := manager.vpnClient.Start(); err != nil {
manager.status = statusError(err)
return err
}

manager.status = statusConnected(vpnSession.Id)
return nil
}
Expand All @@ -82,9 +82,20 @@ func (manager *connectionManager) Status() ConnectionStatus {

func (manager *connectionManager) Disconnect() error {
manager.status = statusDisconnecting()
defer func() { manager.status = statusNotConnected() }()
manager.dialog.Close()
return manager.vpnClient.Stop()

if manager.vpnClient != nil {
if err := manager.vpnClient.Stop(); err != nil {
return err
}
}
if manager.dialog != nil {
if err := manager.dialog.Close(); err != nil {
return err
}
}

manager.status = statusNotConnected()
return nil
}

func (manager *connectionManager) Wait() error {
Expand Down
251 changes: 251 additions & 0 deletions cmd/mysterium_client/cli/command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
package cli

import (
"fmt"
"github.com/chzyer/readline"
tequilapi_client "github.com/mysterium/node/tequilapi/client"
"io"
"log"
"strings"
)

// NewCommand constructs CLI based with possibility to control quiting
func NewCommand(
historyFile string,
tequilapi *tequilapi_client.Client,
quitHandler func() error,
) *Command {
return &Command{
historyFile: historyFile,
tequilapi: tequilapi,
completer: newAutocompleter(tequilapi),
quitHandler: quitHandler,
}
}

// Command describes CLI based Mysterium UI
type Command struct {
historyFile string
tequilapi *tequilapi_client.Client
quitHandler func() error
completer *readline.PrefixCompleter
reader *readline.Instance
}

const redColor = "\033[31m%s\033[0m"
const identityDefaultPassword = ""

// Run starts CLI interface
func (c *Command) Run() (err error) {
c.reader, err = readline.NewEx(&readline.Config{
Prompt: fmt.Sprintf(redColor, "» "),
HistoryFile: c.historyFile,
AutoComplete: c.completer,
InterruptPrompt: "^C",
EOFPrompt: "exit",
})
if err != nil {
return err
}
// TODO Should overtake output of CommandRun
log.SetOutput(c.reader.Stderr())

for {
line, err := c.reader.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
c.quit()
} else {
continue
}
} else if err == io.EOF {
c.quit()
}

c.handleActions(line)
}

return nil
}

//Kill stops tequilapi service
func (c *Command) Kill() error {
c.reader.Clean()
err := c.reader.Close()
if err != nil {
return err
}

return c.quitHandler()
}

func (c *Command) handleActions(line string) {
line = strings.TrimSpace(line)
switch {
case strings.HasPrefix(line, "connect"):
c.connect(line)
break
case line == "exit" || line == "quit":
c.quit()
break

case line == "help":
c.help()
break

case line == "status":
c.status()
break

case line == "disconnect":
c.disconnect()
break

case strings.HasPrefix(line, "identities"):
c.identities(line)
break

default:
if len(line) > 0 {
c.help()
break
}
}
}

func (c *Command) connect(line string) {
connectionArgs := strings.TrimSpace(line[7:])
if len(connectionArgs) == 0 {
info("Press tab to select identity or create a new one. Connect <your-identity> <node-identity>")
return
}

identities := strings.Fields(connectionArgs)

if len(identities) != 2 {
info("Please type in the node identity. Connect <your-identity> <node-identity>")
return
}

consumerId, providerId := identities[0], identities[1]

if consumerId == "new" {
id, err := c.tequilapi.NewIdentity(identityDefaultPassword)
if err != nil {
warn(err)
return
}
consumerId = id.Address
success("New identity created:", consumerId)
}

status("CONNECTING", "from:", consumerId, "to:", providerId)

_, err := c.tequilapi.Connect(consumerId, providerId)
if err != nil {
warn(err)
return
}

success("Connected.")
}

func (c *Command) disconnect() {
err := c.tequilapi.Disconnect()
if err != nil {
warn(err)
return
}

success("Disconnected.")
}

func (c *Command) status() {
status, err := c.tequilapi.Status()
if err != nil {
warn(err)
return
}

info("Status:", status.Status)
info("SID:", status.SessionId)
}

func (c *Command) help() {
info("Mysterium CLI tequilapi commands:")
fmt.Println(c.completer.Tree(" "))
}

func (c *Command) quit() {
err := c.Kill()
if err != nil {
warn(err)
return
}
}

func (c *Command) identities(line string) {
action := strings.TrimSpace(line[10:])
if len(action) == 0 {
info("identities command:\n list\n new")
return
}

if action == "list" {
ids, err := c.tequilapi.GetIdentities()
if err != nil {
fmt.Println("Error occured:", err)
return
}

for _, id := range ids {
status("+", id.Address)
}
return
}

if action == "new" {
id, err := c.tequilapi.NewIdentity(identityDefaultPassword)
if err != nil {
warn(err)
return
}
success("New identity created:", id.Address)
}
}

func getIdentityOptionList(tequilapi *tequilapi_client.Client) func(string) []string {
return func(line string) []string {
identities := []string{"new"}
ids, err := tequilapi.GetIdentities()
if err != nil {
warn(err)
return identities
}
for _, id := range ids {
identities = append(identities, id.Address)
}

return identities
}
}

func newAutocompleter(tequilapi *tequilapi_client.Client) *readline.PrefixCompleter {
return readline.NewPrefixCompleter(
readline.PcItem(
"connect",
readline.PcItemDynamic(
getIdentityOptionList(tequilapi),
),
),
readline.PcItem(
"identities",
readline.PcItem("new"),
readline.PcItem("list"),
),
readline.PcItem("status"),
readline.PcItem("disconnect"),
readline.PcItem("help"),
readline.PcItem("quit"),
)
}
30 changes: 30 additions & 0 deletions cmd/mysterium_client/cli/io.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cli

import (
"fmt"
)

const statusColor = "\033[33m"
const warningColor = "\033[31m"
const successColor = "\033[32m"
const infoColor = "\033[93m"

func status(label string, items ...interface{}) {
fmt.Printf(statusColor+"[%s] \033[0m", label)
fmt.Println(items...)
}

func warn(items ...interface{}) {
fmt.Printf(warningColor + "[WARNING] \033[0m")
fmt.Println(items...)
}

func success(items ...interface{}) {
fmt.Printf(successColor + "[SUCCESS] \033[0m")
fmt.Println(items...)
}

func info(items ...interface{}) {
fmt.Printf(infoColor + "[INFO] \033[0m")
fmt.Println(items...)
}
38 changes: 31 additions & 7 deletions cmd/mysterium_client/mysterium_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,52 @@ package main

import (
"fmt"
"github.com/mysterium/node/cmd/mysterium_client/command_run"
"github.com/mysterium/node/cmd/mysterium_client/cli"
"github.com/mysterium/node/cmd/mysterium_client/run"
tequilapi_client "github.com/mysterium/node/tequilapi/client"
"os"
"path/filepath"
)

func main() {

options, err := command_run.ParseArguments(os.Args)
options, err := run.ParseArguments(os.Args)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

cmd := command_run.NewCommand(options)

err = cmd.Run()
if err != nil {
cmdRun := run.NewCommand(options)
if cmdRun.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

if err = cmd.Wait(); err != nil {
if options.CLI {
cmdCli := cli.NewCommand(
filepath.Join(options.DirectoryRuntime, ".cli_history"),
tequilapi_client.NewClient(options.TequilapiAddress, options.TequilapiPort),
newStopHandler(cmdRun),
)
if err := cmdCli.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

if err = cmdRun.Wait(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

func newStopHandler(cmdRun *run.CommandRun) func() error {
return func() error {
if err := cmdRun.Kill(); err != nil {
return err
}

os.Exit(0)
return nil
}
}
Loading