Skip to content

Commit

Permalink
Merge branch 'develop' into skywire-deployment
Browse files Browse the repository at this point in the history
  • Loading branch information
0pcom committed Dec 10, 2023
2 parents 5e880a6 + c4ddd24 commit b2524c0
Show file tree
Hide file tree
Showing 31 changed files with 1,058 additions and 238 deletions.
294 changes: 174 additions & 120 deletions cmd/skywire-cli/README.md

Large diffs are not rendered by default.

82 changes: 55 additions & 27 deletions cmd/skywire-cli/commands/config/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ func init() {
gHiddenFlags = append(gHiddenFlags, "envs")
genConfigCmd.Flags().BoolVar(&noFetch, "nofetch", false, "do not fetch the services from the service conf url")
gHiddenFlags = append(gHiddenFlags, "nofetch")
genConfigCmd.Flags().StringVar(&configServicePath, "confpath", "", "path of config-service offline file")
genConfigCmd.Flags().BoolVar(&noDefaults, "nodefaults", false, "do not use hardcoded defaults for production / test services")
gHiddenFlags = append(gHiddenFlags, "nodefaults")
genConfigCmd.Flags().StringVar(&ver, "version", scriptExecString("${VERSION}"), "custom version testing override\033[0m")
Expand Down Expand Up @@ -471,38 +472,64 @@ var genConfigCmd = &cobra.Command{
log := logger

if !noFetch {
// set default service conf url if none is specified
if serviceConfURL == "" {
serviceConfURL = utilenv.ServiceConfAddr
}
//use test deployment
if isTestEnv {
serviceConfURL = utilenv.TestServiceConfAddr
}
// enable errors from service conf fetch from the combination of these flags
wasStdout := isStdout
if isStdout && isHide {
isStdout = false
}
// create an http client to fetch the services
client := http.Client{
Timeout: time.Second * 15, // Timeout after 15 seconds
}
// Make the HTTP GET request
res, err := client.Get(fmt.Sprint(serviceConfURL))
if err != nil {
//silence errors for stdout
if !isStdout {
log.WithError(err).Error("Failed to fetch servers\n")
log.Warn("Falling back on hardcoded servers")
var body []byte
var err error

if configServicePath != "" {
body, err = os.ReadFile(configServicePath)
if err != nil {
if !isStdout {
log.WithError(err).Error("Failed to read config service from file\n")
log.Warn("Falling back on hardcoded servers")
}
} else {
//fill in services struct with the response
err = json.Unmarshal(body, &services)
if err != nil {
log.WithError(err).Fatal("Failed to unmarshal json response\n")
}
if !isStdout {
log.Infof("Fetched service endpoints from '%s'", serviceConfURL)
}

// reset the state of isStdout
isStdout = wasStdout
}
} else {
if res.Body != nil {
defer res.Body.Close() //nolint
// set default service conf url if none is specified
if serviceConfURL == "" {
serviceConfURL = utilenv.ServiceConfAddr
}
//use test deployment
if isTestEnv {
serviceConfURL = utilenv.TestServiceConfAddr
}
// enable errors from service conf fetch from the combination of these flags

if isStdout && isHide {
isStdout = false
}
body, err := io.ReadAll(res.Body)
// create an http client to fetch the services
client := http.Client{
Timeout: time.Second * 15, // Timeout after 15 seconds
}
// Make the HTTP GET request
res, err := client.Get(fmt.Sprint(serviceConfURL))
if err != nil {
log.WithError(err).Fatal("Failed to read response\n")
//silence errors for stdout
if !isStdout {
log.WithError(err).Error("Failed to fetch servers\n")
log.Warn("Falling back on hardcoded servers")
}
} else {
if res.Body != nil {
defer res.Body.Close() //nolint
}
body, err = io.ReadAll(res.Body)
if err != nil {
log.WithError(err).Fatal("Failed to read response\n")
}
}
//fill in services struct with the response
err = json.Unmarshal(body, &services)
Expand Down Expand Up @@ -907,6 +934,7 @@ var genConfigCmd = &cobra.Command{
Binary: visorconfig.SkysocksClientName,
AutoStart: false,
Port: routing.Port(visorconfig.SkysocksClientPort),
Args: []string{"-addr", visorconfig.SkysocksClientAddr},
},
{
Name: visorconfig.VPNServerName,
Expand Down
1 change: 1 addition & 0 deletions cmd/skywire-cli/commands/config/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ var (
disableProxyServerAutostart bool
proxyServerPass string
proxyClientPass string
configServicePath string
)

// RootCmd contains commands that interact with the config of local skywire-visor
Expand Down
138 changes: 116 additions & 22 deletions cmd/skywire-cli/commands/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package skysocksc

import (
"bytes"
"context"
"encoding/json"
"fmt"
"math/rand"
Expand All @@ -12,14 +13,17 @@ import (
"text/tabwriter"
"time"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"

"github.com/skycoin/skywire-utilities/pkg/buildinfo"
"github.com/skycoin/skywire-utilities/pkg/cmdutil"
"github.com/skycoin/skywire-utilities/pkg/skyenv"
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/routing"
"github.com/skycoin/skywire/pkg/servicedisc"
)

Expand All @@ -36,6 +40,10 @@ func init() {
version = ""
}
startCmd.Flags().StringVarP(&pk, "pk", "k", "", "server public key")
startCmd.Flags().StringVarP(&addr, "addr", "a", "", "address of proxy for use")
startCmd.Flags().StringVarP(&clientName, "name", "n", "", "name of skysocks client")
stopCmd.Flags().BoolVar(&allClients, "all", false, "stop all skysocks client")
stopCmd.Flags().StringVar(&clientName, "name", "", "specific skysocks client that want stop")
listCmd.Flags().StringVarP(&sdURL, "url", "a", "", "service discovery url default:\n"+skyenv.ServiceDiscAddr)
listCmd.Flags().BoolVarP(&directQuery, "direct", "b", false, "query service discovery directly")
listCmd.Flags().StringVarP(&pk, "pk", "k", "", "check "+serviceType+" service discovery for public key")
Expand All @@ -50,25 +58,81 @@ var startCmd = &cobra.Command{
Use: "start",
Short: "start the " + serviceType + " client",
Run: func(cmd *cobra.Command, args []string) {
//check that a valid public key is provided
err := pubkey.Set(pk)

rpcClient, err := clirpc.Client(cmd.Flags())
if err != nil {
if len(args) > 0 {
err := pubkey.Set(args[0])
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("unable to create RPC client: %w", err))
}

if clientName != "" && pk != "" && addr != "" {
// add new app with -srv and -addr args, and if app was there just change -srv and -addr args and run it
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"))
}
}

arguments := map[string]string{}
arguments["srv"] = pubkey.String()
arguments["addr"] = addr

_, err = rpcClient.App(clientName)
if err == nil {
err = rpcClient.DoCustomSetting(clientName, arguments)
if err != nil {
internal.PrintFatalError(cmd.Flags(), err)
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("Error occurs during set args to custom skysocks client"))
}
} else {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("Invalid or missing public key"))
err = rpcClient.AddApp(clientName, "skysocks-client")
if err != nil {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("Error during add new app"))
}
err = rpcClient.DoCustomSetting(clientName, arguments)
if err != nil {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("Error occurs during set args to custom skysocks client"))
}
}
internal.Catch(cmd.Flags(), rpcClient.StartApp(clientName))
internal.PrintOutput(cmd.Flags(), nil, "Starting.")
} else if clientName != "" && pk == "" && addr == "" {
internal.Catch(cmd.Flags(), rpcClient.StartApp(clientName))
internal.PrintOutput(cmd.Flags(), nil, "Starting.")
} else if pk != "" && clientName == "" && addr == "" {
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"))
}
}
internal.Catch(cmd.Flags(), rpcClient.StartSkysocksClient(pubkey.String()))
internal.PrintOutput(cmd.Flags(), nil, "Starting.")
clientName = "skysocks-client"
// change defaul skysocks-proxy app -srv arg and run it
} else {
// error
return
}
rpcClient, err := clirpc.Client(cmd.Flags())
if err != nil {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("unable to create RPC client: %w", err))
}
//TODO: implement operational timeout
internal.Catch(cmd.Flags(), rpcClient.StartSkysocksClient(pubkey.String()))
internal.PrintOutput(cmd.Flags(), nil, "Starting.")

ctx, cancel := cmdutil.SignalContext(context.Background(), &logrus.Logger{})
defer cancel()
go func() {
<-ctx.Done()
cancel()
rpcClient.StopApp(clientName) //nolint
os.Exit(1)
}()

startProcess := true
for startProcess {
time.Sleep(time.Second * 1)
Expand Down Expand Up @@ -107,8 +171,19 @@ var stopCmd = &cobra.Command{
if err != nil {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("unable to create RPC client: %w", err))
}
internal.Catch(cmd.Flags(), rpcClient.StopSkysocksClient())
internal.PrintOutput(cmd.Flags(), "OK", fmt.Sprintln("OK"))
if allClients && clientName != "" {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("cannot use both --all and --name flag in together"))
}
if !allClients && clientName == "" {
internal.PrintFatalError(cmd.Flags(), fmt.Errorf("you should use one of flags, --all or --name"))
}
if allClients {
internal.Catch(cmd.Flags(), rpcClient.StopSkysocksClients())
internal.PrintOutput(cmd.Flags(), "all skysocks client stopped", fmt.Sprintln("all skysocks clients stopped"))
return
}
internal.Catch(cmd.Flags(), rpcClient.StopApp(clientName))
internal.PrintOutput(cmd.Flags(), fmt.Sprintf("skysocks client %s stopped", clientName), fmt.Sprintf("skysocks client %s stopped\n", clientName))
},
}

Expand All @@ -128,26 +203,45 @@ var statusCmd = &cobra.Command{
w := tabwriter.NewWriter(&b, 0, 0, 5, ' ', tabwriter.TabIndent)
internal.Catch(cmd.Flags(), err)
type appState struct {
Status string `json:"status"`
Name string `json:"name"`
Status string `json:"status"`
AutoStart bool `json:"autostart"`
Args []string `json:"args"`
AppPort routing.Port `json:"app_port"`
}
var jsonAppStatus appState
var jsonAppStatus []appState
fmt.Fprintf(w, "---- All Proxy List -----------------------------------------------------\n\n")
for _, state := range states {
if state.Name == stateName {

if state.AppConfig.Binary == binaryName {
status := "stopped"
if state.Status == appserver.AppStatusRunning {
status = "running"
}
if state.Status == appserver.AppStatusErrored {
status = "errored"
}
jsonAppStatus = appState{
Status: status,
jsonAppStatus = append(jsonAppStatus, appState{
Name: state.Name,
Status: status,
AutoStart: state.AutoStart,
Args: state.Args,
AppPort: state.Port,
})
var tmpAddr string
var tmpSrv string
for idx, arg := range state.Args {
if arg == "-srv" {
tmpSrv = state.Args[idx+1]
}
if arg == "-addr" {
tmpAddr = "127.0.0.1" + state.Args[idx+1]
}
}
_, err = fmt.Fprintf(w, "%s\n", status)
_, err = fmt.Fprintf(w, "Name: %s\nStatus: %s\nServer: %s\nAddress: %s\nAppPort: %d\nAutoStart: %t\n\n", state.Name, status, tmpSrv, tmpAddr, state.Port, state.AutoStart)
internal.Catch(cmd.Flags(), err)
}
}
fmt.Fprintf(w, "-------------------------------------------------------------------------\n")
internal.Catch(cmd.Flags(), w.Flush())
internal.PrintOutput(cmd.Flags(), jsonAppStatus, b.String())
},
Expand Down
4 changes: 4 additions & 0 deletions cmd/skywire-cli/commands/proxy/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
)

var (
binaryName = "skysocks-client"
stateName = "skysocks-client"
serviceType = servicedisc.ServiceTypeProxy
servicePort = ":44"
Expand All @@ -22,6 +23,9 @@ var (
sdURL string
directQuery bool
servers []servicedisc.Service
allClients bool
clientName string
addr string
)

// RootCmd contains commands that interact with the skywire-visor
Expand Down
Loading

0 comments on commit b2524c0

Please sign in to comment.