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

Cli refactor #1515

Merged
merged 20 commits into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
3 changes: 1 addition & 2 deletions cmd/skywire-cli/commands/config/auto.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
//go:build exclude

// Package cliconfig cmd/skywire-cli/commands/config/auto.go
package cliconfig
Expand Down
38 changes: 27 additions & 11 deletions cmd/skywire-cli/commands/mdisc/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (
)

var mdAddr string

// var allEntries bool
var masterLogger = logging.NewMasterLogger()
var packageLogger = masterLogger.PackageLogger("mdisc:disc")

Expand All @@ -29,7 +31,8 @@ func init() {
entryCmd,
availableServersCmd,
)
entryCmd.PersistentFlags().StringVar(&mdAddr, "addr", utilenv.DmsgDiscAddr, "address of DMSG discovery server\n")
entryCmd.PersistentFlags().StringVarP(&mdAddr, "addr", "a", "", "DMSG discovery server address\n"+utilenv.DmsgDiscAddr)
// entryCmd.PersistentFlags().BoolVarP(&allEntries, "entries", "e", "", "get all entries")
availableServersCmd.PersistentFlags().StringVar(&mdAddr, "addr", utilenv.DmsgDiscAddr, "address of DMSG discovery server\n")
var helpflag bool
RootCmd.Flags().BoolVarP(&helpflag, "help", "h", false, "help for "+RootCmd.Use)
Expand All @@ -45,17 +48,30 @@ var RootCmd = &cobra.Command{
var entryCmd = &cobra.Command{
Use: "entry <visor-public-key>",
Short: "Fetch an entry",
Args: cobra.MinimumNArgs(1),
// Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
pk := internal.ParsePK(cmd.Flags(), "visor-public-key", args[0])

masterLogger.SetLevel(logrus.InfoLevel)

entry, err := disc.NewHTTP(mdAddr, &http.Client{}, packageLogger).Entry(ctx, pk)
internal.Catch(cmd.Flags(), err)
internal.PrintOutput(cmd.Flags(), entry, fmt.Sprintln(entry))
//print help on no args
if len(args) == 0 {
cmd.Help() //nolint
} else {
if mdAddr == "" {
mdAddr = utilenv.DmsgDiscAddr
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
pk := internal.ParsePK(cmd.Flags(), "visor-public-key", args[0])

masterLogger.SetLevel(logrus.InfoLevel)

//TODO: fetch all entries
// if allEntries {
// entries, err := disc.NewHTTP(mdAddr, &http.Client{}, packageLogger).AvailableServers(ctx)
// }

entry, err := disc.NewHTTP(mdAddr, &http.Client{}, packageLogger).Entry(ctx, pk)
internal.Catch(cmd.Flags(), err)
internal.PrintOutput(cmd.Flags(), entry, fmt.Sprintln(entry))
}
},
}

Expand Down
225 changes: 225 additions & 0 deletions cmd/skywire-cli/commands/proxy/proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
// Package skysocksc cmd/skywire-cli/commands/skysocksc/skysocks.go
package skysocksc

import (
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"text/tabwriter"
"time"

"github.com/spf13/cobra"

"github.com/skycoin/skywire-utilities/pkg/buildinfo"
clirpc "github.com/skycoin/skywire/cmd/skywire-cli/commands/rpc"
"github.com/skycoin/skywire/cmd/skywire-cli/internal"
"github.com/skycoin/skywire/pkg/app/appserver"
"github.com/skycoin/skywire/pkg/servicedisc"
)

func init() {
RootCmd.PersistentFlags().StringVar(&clirpc.Addr, "rpc", "localhost:3435", "RPC server address")
RootCmd.AddCommand(
proxyStartCmd,
proxyStopCmd,
proxyStatusCmd,
proxyListCmd,
)
version := buildinfo.Version()
if version == "unknown" {
version = ""
}
proxyStartCmd.Flags().StringVarP(&pk, "pk", "k", "", "server public key")
proxyListCmd.Flags().StringVarP(&pk, "pk", "k", "", "check proxy service discovery for public key")
proxyListCmd.Flags().IntVarP(&count, "num", "n", 0, "number of results to return")
proxyListCmd.Flags().BoolVarP(&isUnFiltered, "unfilter", "u", false, "provide unfiltered results")
proxyListCmd.Flags().StringVarP(&ver, "ver", "v", version, "filter results by version")
proxyListCmd.Flags().StringVarP(&country, "country", "c", "", "filter results by country")
proxyListCmd.Flags().BoolVarP(&isStats, "stats", "s", false, "return only a count of the results")
}

var proxyStartCmd = &cobra.Command{
Use: "start",
Short: "start the proxy client",
// Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
//check that a valid public key is provided
err := pubkey.Set(pk)
if err != nil {
if len(args) > 0 {
err := pubkey.Set(args[0])
if err != nil {
internal.PrintFatalError(cmd.Flags(), err)
}
} else {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("Invalid or missing public key"))
}
}
//connect to RPC
rpcClient, err := clirpc.Client(cmd.Flags())
if err != nil {
os.Exit(1)
}
//TODO: implement operational timeout
internal.Catch(cmd.Flags(), rpcClient.StartSkysocksClient(pubkey.String()))
internal.PrintOutput(cmd.Flags(), nil, "Starting.")
startProcess := true
for startProcess {
time.Sleep(time.Second * 1)
internal.PrintOutput(cmd.Flags(), nil, ".")
states, err := rpcClient.Apps()
internal.Catch(cmd.Flags(), err)

type output struct {
AppError string `json:"app_error,omitempty"`
}

for _, state := range states {
if state.Name == "skysocks-client" {
if state.Status == appserver.AppStatusRunning {
startProcess = false
internal.PrintOutput(cmd.Flags(), nil, fmt.Sprintln("\nRunning!"))
}
if state.Status == appserver.AppStatusErrored {
startProcess = false
out := output{
AppError: state.DetailedStatus,
}
internal.PrintOutput(cmd.Flags(), out, fmt.Sprintln("\nError! > "+state.DetailedStatus))
}
}
}
}
},
}

var proxyStopCmd = &cobra.Command{
Use: "stop",
Short: "stop the proxy client",
Run: func(cmd *cobra.Command, args []string) {
rpcClient, err := clirpc.Client(cmd.Flags())
if err != nil {
os.Exit(1)
}
internal.Catch(cmd.Flags(), rpcClient.StopSkysocksClient())
internal.PrintOutput(cmd.Flags(), "OK", fmt.Sprintln("OK"))
},
}

var proxyStatusCmd = &cobra.Command{
Use: "status",
Short: "proxy client(s) status",
Run: func(cmd *cobra.Command, args []string) {
//TODO: check status of multiple clients
rpcClient, err := clirpc.Client(cmd.Flags())
if err != nil {
os.Exit(1)
}
states, err := rpcClient.Apps()
internal.Catch(cmd.Flags(), err)

var b bytes.Buffer
w := tabwriter.NewWriter(&b, 0, 0, 5, ' ', tabwriter.TabIndent)
internal.Catch(cmd.Flags(), err)
type appState struct {
Status string `json:"status"`
}
var jsonAppStatus appState
for _, state := range states {
if state.Name == "skysocks-client" {

status := "stopped"
if state.Status == appserver.AppStatusRunning {
status = "running"
}
if state.Status == appserver.AppStatusErrored {
status = "errored"
}
jsonAppStatus = appState{
Status: status,
}
_, err = fmt.Fprintf(w, "%s\n", status)
internal.Catch(cmd.Flags(), err)
}
}
internal.Catch(cmd.Flags(), w.Flush())
internal.PrintOutput(cmd.Flags(), jsonAppStatus, b.String())
},
}

var proxyListCmd = &cobra.Command{
Use: "list",
Short: "List servers",
Long: "List proxy servers from service discovery\n http://sd.skycoin.com/api/services?type=proxy\n http://sd.skycoin.com/api/services?type=vpn&country=US",
Run: func(cmd *cobra.Command, args []string) {
if pk != "" {
err := pubkey.Set(pk)
if err != nil {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("Invalid or missing public key"))
}
}
rpcClient, err := clirpc.Client(cmd.Flags())
if err != nil {
internal.PrintFatalRPCError(cmd.Flags(), err)
}
if isUnFiltered {
ver = ""
country = ""
}
servers, err := rpcClient.ProxyServers(ver, country)
if err != nil {
internal.PrintFatalRPCError(cmd.Flags(), err)
}
if len(servers) == 0 {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("No Servers found"))
}
if isStats {
internal.PrintOutput(cmd.Flags(), fmt.Sprintf("%d Servers\n", len(servers)), fmt.Sprintf("%d Servers\n", len(servers)))
} else {
var msg string
var results []string
limit := len(servers)
if count > 0 && count < limit {
limit = count
}
if pk != "" {
for _, server := range servers {
if strings.Replace(server.Addr.String(), ":44", "", 1) == pk {
results = append(results, server.Addr.String())
}
}
} else {
for _, server := range servers {
results = append(results, server.Addr.String())
}
}
rand.Shuffle(len(results), func(i, j int) {
results[i], results[j] = results[j], results[i]
})
for i := 0; i < limit && i < len(results); i++ {
msg += strings.Replace(results[i], ":44", "", 1)
if server := findServerByPK(servers, results[i]); server != nil && server.Geo != nil {
if server.Geo.Country != "" {
msg += fmt.Sprintf(" | %s\n", server.Geo.Country)
} else {
msg += "\n"
}
} else {
msg += "\n"
}
}
internal.PrintOutput(cmd.Flags(), servers, msg)
}
},
}

func findServerByPK(servers []servicedisc.Service, addr string) *servicedisc.Service {
for _, server := range servers {
if server.Addr.String() == addr {
return &server
}
}
return nil
}
24 changes: 24 additions & 0 deletions cmd/skywire-cli/commands/proxy/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Package skysocksc root.go
package skysocksc

import (
"github.com/spf13/cobra"

"github.com/skycoin/skywire-utilities/pkg/cipher"
)

var (
isUnFiltered bool
ver string
country string
isStats bool
pubkey cipher.PubKey
pk string
count int
)

// RootCmd contains commands that interact with the skywire-visor
var RootCmd = &cobra.Command{
Use: "proxy",
Short: "Skysocks client",
}
4 changes: 3 additions & 1 deletion cmd/skywire-cli/commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ import (
clidmsgpty "github.com/skycoin/skywire/cmd/skywire-cli/commands/dmsgpty"
clilog "github.com/skycoin/skywire/cmd/skywire-cli/commands/log"
climdisc "github.com/skycoin/skywire/cmd/skywire-cli/commands/mdisc"
cliskysocksc "github.com/skycoin/skywire/cmd/skywire-cli/commands/proxy"
clireward "github.com/skycoin/skywire/cmd/skywire-cli/commands/reward"
clirtfind "github.com/skycoin/skywire/cmd/skywire-cli/commands/rtfind"
cliskyfwd "github.com/skycoin/skywire/cmd/skywire-cli/commands/skyfwd"
cliskyrev "github.com/skycoin/skywire/cmd/skywire-cli/commands/skyrev"
cliskysocksc "github.com/skycoin/skywire/cmd/skywire-cli/commands/skysocksc"
clisurvey "github.com/skycoin/skywire/cmd/skywire-cli/commands/survey"
cliut "github.com/skycoin/skywire/cmd/skywire-cli/commands/ut"
clivisor "github.com/skycoin/skywire/cmd/skywire-cli/commands/visor"
clivpn "github.com/skycoin/skywire/cmd/skywire-cli/commands/vpn"
"github.com/skycoin/skywire/cmd/skywire-cli/internal"
Expand Down Expand Up @@ -181,6 +182,7 @@ func init() {
clidmsgpty.RootCmd,
clivisor.RootCmd,
clivpn.RootCmd,
cliut.RootCmd,
cliskyfwd.RootCmd,
cliskyrev.RootCmd,
clireward.RootCmd,
Expand Down
Loading