Skip to content

Commit

Permalink
Updated start server command
Browse files Browse the repository at this point in the history
  • Loading branch information
bsrinivas8687 committed Aug 12, 2021
1 parent ec7f0a3 commit e850c44
Show file tree
Hide file tree
Showing 10 changed files with 168 additions and 66 deletions.
111 changes: 69 additions & 42 deletions cmd/start.go
Original file line number Diff line number Diff line change
@@ -1,87 +1,114 @@
package cmd

import (
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"

"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/std"
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/sentinel-official/hub"
hubparams "github.com/sentinel-official/hub/params"
"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/sentinel-official/cli-client/context"
"github.com/sentinel-official/cli-client/middlewares"
keysrest "github.com/sentinel-official/cli-client/rest/keys"
servicerest "github.com/sentinel-official/cli-client/rest/service"
"github.com/sentinel-official/cli-client/types"
configtypes "github.com/sentinel-official/cli-client/types/config"
randutils "github.com/sentinel-official/cli-client/utils/rand"
restmiddlewares "github.com/sentinel-official/cli-client/rest/middlewares"
restmodules "github.com/sentinel-official/cli-client/rest/modules"
clitypes "github.com/sentinel-official/cli-client/types"
)

func StartCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "start",
Short: "Start REST API server",
RunE: func(cmd *cobra.Command, args []string) error {
var (
home = viper.GetString(flags.FlagHome)
configPath = filepath.Join(home, types.ConfigFilename)
buildPath = filepath.Join(home, types.BuildFolderName)
)
Short: "Start the management server",
Args: cobra.NoArgs,
PreRunE: func(cmd *cobra.Command, _ []string) error {
home, err := cmd.Flags().GetString(clitypes.FlagHome)
if err != nil {
return err
}

v := viper.New()
v.SetConfigFile(configPath)
if err := os.MkdirAll(home, os.ModePerm); err != nil {
return err
}

config, err := configtypes.ReadInConfig(v)
tty, err := cmd.Flags().GetBool(clitypes.FlagTTY)
if err != nil {
return err
}
if err := config.Validate(); err != nil {

if !tty {
os.Stderr, os.Stdin, os.Stdout = nil, nil, nil
}

return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
home, err := cmd.Flags().GetString(clitypes.FlagHome)
if err != nil {
return err
}

config.Token = randutils.RandomStringHex(types.TokenLength)
if err := config.SaveToPath(configPath); err != nil {
listen, err := cmd.Flags().GetString(clitypes.FlagListen)
if err != nil {
return err
}

encoding := hubparams.MakeEncodingConfig()
std.RegisterInterfaces(encoding.InterfaceRegistry)
hub.ModuleBasics.RegisterInterfaces(encoding.InterfaceRegistry)
withKeyring, err := cmd.Flags().GetBool(clitypes.FlagWithKeyring)
if err != nil {
return err
}

var (
ctx = context.NewContext().
WithConfig(config).
WithEncoding(&encoding)
withService, err := cmd.Flags().GetBool(clitypes.FlagWithService)
if err != nil {
return err
}

var (
ctx = context.NewServiceContext().
WithHome(home)
muxRouter = mux.NewRouter()
prefixRouter = muxRouter.PathPrefix(types.APIPathPrefix).Subrouter()
prefixRouter = muxRouter.
PathPrefix(clitypes.APIPathPrefix).
Subrouter()
)

muxRouter.Use(middlewares.Log)
muxRouter.PathPrefix("/").
Handler(http.FileServer(http.Dir(buildPath)))
muxRouter.Use(restmiddlewares.Log)
prefixRouter.Use(restmiddlewares.AddHeaders)

prefixRouter.Use(middlewares.AddHeaders)
keysrest.RegisterRoutes(prefixRouter, ctx)
servicerest.RegisterRoutes(prefixRouter, ctx)
if withKeyring {
restmodules.RegisterKeyring(prefixRouter, &ctx)
}
if withService {
restmodules.RegisterService(prefixRouter, &ctx)
}

if err := ioutil.WriteFile(
filepath.Join(home, "url.txt"),
[]byte("http"+"://"+listen+clitypes.APIPathPrefix),
os.ModePerm,
); err != nil {
return err
}

router := cors.New(
cors.Options{
AllowedOrigins: strings.Split(config.CORS.AllowedOrigins, ","),
AllowedMethods: []string{http.MethodDelete, http.MethodGet, http.MethodPost},
AllowedOrigins: []string{"*"},
AllowedMethods: []string{http.MethodPost},
AllowedHeaders: []string{"Content-Type"},
},
).Handler(muxRouter)

return http.ListenAndServe(config.ListenOn, router)
log.Printf("Listening on %s", listen)
return http.ListenAndServe(listen, router)
},
}

cmd.Flags().Bool(clitypes.FlagWithKeyring, false, "include the endpoints of keyring module")
cmd.Flags().Bool(clitypes.FlagWithService, false, "include the endpoints of service module")
cmd.Flags().Bool(clitypes.FlagTTY, false, "enable the standard error, input and output")
cmd.Flags().String(clitypes.FlagListen, clitypes.Listen, "listen address of the server")
cmd.Flags().String(clitypes.FlagHome, clitypes.Home, "home directory of the server")

return cmd
}
4 changes: 4 additions & 0 deletions services/wireguard/types/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ func NewPrivateKey() (*Key, error) {
return key, nil
}

func (k *Key) Bytes() []byte {
return k[:]
}

func (k *Key) String() string {
return base64.StdEncoding.EncodeToString(k[:])
}
Expand Down
13 changes: 6 additions & 7 deletions services/wireguard/wireguard.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"strings"

"github.com/alessio/shellescape"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/viper"

"github.com/sentinel-official/cli-client/services/wireguard/types"
clienttypes "github.com/sentinel-official/cli-client/types"
Expand All @@ -23,6 +21,7 @@ var (
type WireGuard struct {
cfg *types.Config
info []byte
home string
}

func NewWireGuard() *WireGuard {
Expand All @@ -31,8 +30,8 @@ func NewWireGuard() *WireGuard {

func (w *WireGuard) WithConfig(v *types.Config) *WireGuard { w.cfg = v; return w }
func (w *WireGuard) WithInfo(v []byte) *WireGuard { w.info = v; return w }
func (w *WireGuard) WithHome(v string) *WireGuard { w.home = v; return w }

func (w *WireGuard) Home() string { return viper.GetString(flags.FlagHome) }
func (w *WireGuard) Info() []byte { return w.info }

func (w *WireGuard) IsUp() bool {
Expand All @@ -54,12 +53,12 @@ func (w *WireGuard) IsUp() bool {
}

func (w *WireGuard) PreUp() error {
return w.cfg.WriteToFile(w.Home())
return w.cfg.WriteToFile(w.home)
}

func (w *WireGuard) Up() error {
var (
path = filepath.Join(w.Home(), fmt.Sprintf("%s.conf", w.cfg.Name))
path = filepath.Join(w.home, fmt.Sprintf("%s.conf", w.cfg.Name))
cmd = exec.Command("wg-quick", strings.Split(
fmt.Sprintf("up %s", shellescape.Quote(path)), " ")...)
)
Expand All @@ -74,7 +73,7 @@ func (w *WireGuard) PreDown() error { return nil }

func (w *WireGuard) Down() error {
var (
path = filepath.Join(w.Home(), fmt.Sprintf("%s.conf", w.cfg.Name))
path = filepath.Join(w.home, fmt.Sprintf("%s.conf", w.cfg.Name))
cmd = exec.Command("wg-quick", strings.Split(
fmt.Sprintf("down %s", shellescape.Quote(path)), " ")...)
)
Expand All @@ -85,7 +84,7 @@ func (w *WireGuard) Down() error {
}

func (w *WireGuard) PostDown() error {
path := filepath.Join(w.Home(), fmt.Sprintf("%s.conf", w.cfg.Name))
path := filepath.Join(w.home, fmt.Sprintf("%s.conf", w.cfg.Name))
if _, err := os.Stat(path); err == nil {
return os.Remove(path)
}
Expand Down
9 changes: 5 additions & 4 deletions types/bandwidth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (

hubtypes "github.com/sentinel-official/hub/types"

netutil "github.com/sentinel-official/cli-client/utils/net"
netutils "github.com/sentinel-official/cli-client/utils/net"
)

type Bandwidth struct {
Expand All @@ -14,9 +14,10 @@ type Bandwidth struct {
}

func (b Bandwidth) String() string {
return fmt.Sprintf("%s+%s",
netutil.ToReadable(b.Upload, 2),
netutil.ToReadable(b.Download, 2),
return fmt.Sprintf(
"%s+%s",
netutils.ToReadable(b.Upload, 2),
netutils.ToReadable(b.Download, 2),
)
}

Expand Down
6 changes: 3 additions & 3 deletions types/keyring/key.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package keyring

import (
"encoding/hex"
"encoding/base64"

"github.com/cosmos/cosmos-sdk/crypto/keyring"
)
Expand All @@ -15,8 +15,8 @@ type Key struct {
func NewKeyFromRaw(v keyring.Info) Key {
return Key{
Name: v.GetName(),
PubKey: hex.EncodeToString(v.GetPubKey().Bytes()),
Address: hex.EncodeToString(v.GetAddress().Bytes()),
PubKey: base64.StdEncoding.EncodeToString(v.GetPubKey().Bytes()),
Address: base64.StdEncoding.EncodeToString(v.GetAddress().Bytes()),
}
}

Expand Down
10 changes: 4 additions & 6 deletions types/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ import (
)

const (
APIPathPrefix = "/api/v1"
BuildFolderName = "build"
ConfigFilename = "config.toml"
StatusFilename = "status.json"
TokenLength = 32
APIPathPrefix = "/api/v1"
StatusFilename = "status.json"
Listen = "127.0.0.1:11112"
)

var (
DefaultHomeDirectory = func() string {
Home = func() string {
home, err := os.UserHomeDir()
if err != nil {
panic(err)
Expand Down
4 changes: 0 additions & 4 deletions types/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,16 @@ type Service interface {
}

type Status struct {
From string `json:"from"`
ID uint64 `json:"id"`
IFace string `json:"iface"`
To string `json:"to"`
}

func NewStatus() *Status {
return &Status{}
}

func (s *Status) WithFrom(v string) *Status { s.From = v; return s }
func (s *Status) WithID(v uint64) *Status { s.ID = v; return s }
func (s *Status) WithIFace(v string) *Status { s.IFace = v; return s }
func (s *Status) WithTo(v string) *Status { s.To = v; return s }

func (s *Status) LoadFromPath(path string) error {
if _, err := os.Stat(path); err != nil {
Expand Down
24 changes: 24 additions & 0 deletions utils/file/read.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package file

import (
"bufio"
"os"
)

func ReadLine(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}

var (
reader = bufio.NewReader(file)
)

buf, _, err := reader.ReadLine()
if err != nil {
return "", err
}

return string(buf), nil
}
19 changes: 19 additions & 0 deletions utils/keyring/input.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package keyring

import (
"bufio"

"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
)

func ReadPassword(backend string, r *bufio.Reader) (s string, err error) {
if backend == keyring.BackendFile {
s, err = input.GetPassword("Enter keyring passphrase: ", r)
if err != nil {
return "", err
}
}

return s, nil
}
34 changes: 34 additions & 0 deletions utils/process/pid.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package process

import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"

"github.com/natefinch/atomic"
)

func ReadPID(path string) (int, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return 0, err
}

id, err := strconv.Atoi(string(bytes))
if err != nil {
return 0, err
}

return id, nil
}

func WritePID(path string) error {
return atomic.WriteFile(
path,
strings.NewReader(
fmt.Sprintf("%d", os.Getpid()),
),
)
}

0 comments on commit e850c44

Please sign in to comment.