Skip to content

Commit

Permalink
Merge pull request #537 from nkryuchkov/bug/fix-linter
Browse files Browse the repository at this point in the history
Fix linter errors
  • Loading branch information
志宇 authored Sep 4, 2019
2 parents b0cfe67 + 7fd7ae3 commit 4fb40ea
Show file tree
Hide file tree
Showing 14 changed files with 133 additions and 57 deletions.
11 changes: 10 additions & 1 deletion internal/utclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ import (
"net/http"

"github.com/skycoin/dmsg/cipher"
"github.com/skycoin/skycoin/src/util/logging"

"github.com/skycoin/skywire/internal/httpauth"
)

var log = logging.MustGetLogger("utclient")

// Error is the object returned to the client when there's an error.
type Error struct {
Error string `json:"error"`
Expand Down Expand Up @@ -61,10 +64,16 @@ func (c *httpClient) Get(ctx context.Context, path string) (*http.Response, erro
// UpdateNodeUptime updates node uptime.
func (c *httpClient) UpdateNodeUptime(ctx context.Context) error {
resp, err := c.Get(ctx, "/update")
if resp != nil {
defer func() {
if err := resp.Body.Close(); err != nil {
log.WithError(err).Warn("Failed to close response body")
}
}()
}
if err != nil {
return err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status: %d, error: %v", resp.StatusCode, extractError(resp.Body))
Expand Down
8 changes: 6 additions & 2 deletions internal/utclient/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ func TestClientAuth(t *testing.T) {
headerCh <- r.Header

case fmt.Sprintf("/security/nonces/%s", testPubKey):
fmt.Fprintf(w, `{"edge": "%s", "next_nonce": 1}`, testPubKey)
if _, err := fmt.Fprintf(w, `{"edge": "%s", "next_nonce": 1}`, testPubKey); err != nil {
t.Errorf("Failed to write nonce response: %s", err)
}

default:
t.Errorf("Don't know how to handle URL = '%s'", url)
Expand Down Expand Up @@ -75,7 +77,9 @@ func authHandler(next http.Handler) http.Handler {
m := http.NewServeMux()
m.Handle("/security/nonces/", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(&httpauth.NextNonceResponse{Edge: testPubKey, NextNonce: 1}) // nolint: errcheck
if err := json.NewEncoder(w).Encode(&httpauth.NextNonceResponse{Edge: testPubKey, NextNonce: 1}); err != nil {
log.WithError(err).Error("Failed to encode nonce response")
}
},
))
m.Handle("/", next)
Expand Down
19 changes: 15 additions & 4 deletions pkg/router/route_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@ import (
"github.com/skycoin/skywire/pkg/snet"
)

// RMConfig represents route manager configuration.
type RMConfig struct {
SetupPKs []cipher.PubKey // Trusted setup PKs.
GarbageCollectDuration time.Duration
OnConfirmLoop func(loop routing.Loop, rule routing.Rule) (err error)
OnLoopClosed func(loop routing.Loop) error
}

// SetupIsTrusted checks if setup node is trusted.
func (sc RMConfig) SetupIsTrusted(sPK cipher.PubKey) bool {
for _, pk := range sc.SetupPKs {
if sPK == pk {
Expand All @@ -33,6 +35,7 @@ func (sc RMConfig) SetupIsTrusted(sPK cipher.PubKey) bool {
return false
}

// routeManager represents route manager.
type routeManager struct {
Logger *logging.Logger
conf RMConfig
Expand All @@ -42,8 +45,8 @@ type routeManager struct {
done chan struct{}
}

// NewRouteManager creates a new route manager.
func NewRouteManager(n *snet.Network, rt routing.Table, config RMConfig) (*routeManager, error) {
// newRouteManager creates a new route manager.
func newRouteManager(n *snet.Network, rt routing.Table, config RMConfig) (*routeManager, error) {
sl, err := n.Listen(snet.DmsgType, snet.AwaitSetupPort)
if err != nil {
return nil, err
Expand All @@ -58,11 +61,13 @@ func NewRouteManager(n *snet.Network, rt routing.Table, config RMConfig) (*route
}, nil
}

// Close closes route manager.
func (rm *routeManager) Close() error {
close(rm.done)
return rm.sl.Close()
}

// Serve initiates serving connections by route manager.
func (rm *routeManager) Serve() {
// Routing table garbage collect loop.
go rm.rtGarbageCollectLoop()
Expand Down Expand Up @@ -97,7 +102,11 @@ func (rm *routeManager) serveConn() error {
}

func (rm *routeManager) handleSetupConn(conn net.Conn) error {
defer func() { _ = conn.Close() }() //nolint:errcheck
defer func() {
if err := conn.Close(); err != nil {
log.WithError(err).Warn("Failed to close connection")
}
}()

proto := setup.NewSetupProtocol(conn)
t, body, err := proto.ReadPacket()
Expand Down Expand Up @@ -148,7 +157,7 @@ func (rm *routeManager) rtGarbageCollectLoop() {
}
}

func (rm *routeManager) dialSetupConn(ctx context.Context) (*snet.Conn, error) {
func (rm *routeManager) dialSetupConn(_ context.Context) (*snet.Conn, error) {
for _, sPK := range rm.conf.SetupPKs {
conn, err := rm.n.Dial(snet.DmsgType, sPK, snet.SetupPort)
if err != nil {
Expand All @@ -160,6 +169,7 @@ func (rm *routeManager) dialSetupConn(ctx context.Context) (*snet.Conn, error) {
return nil, errors.New("failed to dial to a setup node")
}

// GetRule gets routing rule.
func (rm *routeManager) GetRule(routeID routing.RouteID) (routing.Rule, error) {
rule, err := rm.rt.Rule(routeID)
if err != nil {
Expand All @@ -183,6 +193,7 @@ func (rm *routeManager) GetRule(routeID routing.RouteID) (routing.Rule, error) {
return rule, nil
}

// RemoveLoopRule removes loop rule.
func (rm *routeManager) RemoveLoopRule(loop routing.Loop) error {
var appRouteID routing.RouteID
var appRule routing.Rule
Expand Down
2 changes: 1 addition & 1 deletion pkg/router/route_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestNewRouteManager(t *testing.T) {

rt := routing.InMemoryRoutingTable()

rm, err := NewRouteManager(env.Nets[0], rt, RMConfig{})
rm, err := newRouteManager(env.Nets[0], rt, RMConfig{})
require.NoError(t, err)
defer func() { require.NoError(t, rm.Close()) }()

Expand Down
3 changes: 2 additions & 1 deletion pkg/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func New(n *snet.Network, config *Config) (*Router, error) {
}

// Prepare route manager.
rm, err := NewRouteManager(n, config.RoutingTable, RMConfig{
rm, err := newRouteManager(n, config.RoutingTable, RMConfig{
SetupPKs: config.SetupNodes,
GarbageCollectDuration: config.GarbageCollectDuration,
OnConfirmLoop: r.confirmLoop,
Expand Down Expand Up @@ -428,6 +428,7 @@ fetchRoutesAgain:
return fwdRoutes[0], revRoutes[0], nil
}

// SetupIsTrusted checks if setup node is trusted.
func (r *Router) SetupIsTrusted(sPK cipher.PubKey) bool {
return r.rm.conf.SetupIsTrusted(sPK)
}
1 change: 1 addition & 0 deletions pkg/setup/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ func (sn *Node) createRoute(ctx context.Context, expireAt time.Time, route routi
rulesSetupErr = err
}
}
cancelOnce.Do(cancel)

// close chan to avoid leaks
close(rulesSetupErrs)
Expand Down
15 changes: 11 additions & 4 deletions pkg/setup/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,11 @@ func TestMain(m *testing.M) {
dmsgL: listener,
metrics: metrics.NewDummy(),
}
go func() { _ = sn.Serve(context.TODO()) }() //nolint:errcheck
go func() {
if err := sn.Serve(context.TODO()); err != nil {
sn.Logger.WithError(err).Error("Failed to serve")
}
}()
return sn, func() {
require.NoError(t, sn.Close())
}
Expand Down Expand Up @@ -208,7 +212,8 @@ func TestMain(m *testing.M) {
}
// TODO: This error is not checked due to a bug in dmsg.
_ = proto.WritePacket(RespSuccess, nil) //nolint:errcheck
err = proto.WritePacket(RespSuccess, nil)
_ = err
fmt.Printf("client %v:%v responded for PacketAddRules\n", client, clients[client].Addr)
Expand Down Expand Up @@ -242,7 +247,8 @@ func TestMain(m *testing.M) {
}
// TODO: This error is not checked due to a bug in dmsg.
_ = proto.WritePacket(RespSuccess, nil) //nolint:errcheck
err = proto.WritePacket(RespSuccess, nil)
_ = err
require.NoError(t, tp.Close())
}
Expand Down Expand Up @@ -331,7 +337,8 @@ func TestMain(m *testing.M) {
require.Equal(t, ld.Loop.Local, d.Loop.Remote)
// TODO: This error is not checked due to a bug in dmsg.
_ = proto.WritePacket(RespSuccess, nil) //nolint:errcheck
err = proto.WritePacket(RespSuccess, nil)
_ = err
})
}*/

Expand Down
42 changes: 35 additions & 7 deletions pkg/snet/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@ const (
)

var (
// ErrUnknownNetwork occurs on attempt to dial an unknown network type.
ErrUnknownNetwork = errors.New("unknown network type")
)

// Config represents a network configuration.
type Config struct {
PubKey cipher.PubKey
SecKey cipher.SecKey
Expand All @@ -41,12 +43,13 @@ type Config struct {
DmsgMinSrvs int
}

// Network represents
// Network represents a network between nodes in Skywire.
type Network struct {
conf Config
dmsgC *dmsg.Client
}

// New creates a network from a config.
func New(conf Config) *Network {
dmsgC := dmsg.NewClient(conf.PubKey, conf.SecKey, disc.NewHTTP(conf.DmsgDiscAddr), dmsg.SetLogger(logging.MustGetLogger("snet.dmsgC")))
return &Network{
Expand All @@ -55,13 +58,15 @@ func New(conf Config) *Network {
}
}

// NewRaw creates a network from a config and a dmsg client.
func NewRaw(conf Config, dmsgC *dmsg.Client) *Network {
return &Network{
conf: conf,
dmsgC: dmsgC,
}
}

// Init initiates server connections.
func (n *Network) Init(ctx context.Context) error {
fmt.Println("dmsg: min_servers:", n.conf.DmsgMinSrvs)
if err := n.dmsgC.InitiateServerConnections(ctx, n.conf.DmsgMinSrvs); err != nil {
Expand All @@ -70,6 +75,7 @@ func (n *Network) Init(ctx context.Context) error {
return nil
}

// Close closes underlying connections.
func (n *Network) Close() error {
wg := new(sync.WaitGroup)
wg.Add(1)
Expand All @@ -87,15 +93,19 @@ func (n *Network) Close() error {
return nil
}

// LocalPK returns local public key.
func (n *Network) LocalPK() cipher.PubKey { return n.conf.PubKey }

// LocalSK returns local secure key.
func (n *Network) LocalSK() cipher.SecKey { return n.conf.SecKey }

// TransportNetworks returns network types that are used for transports.
func (n *Network) TransportNetworks() []string { return n.conf.TpNetworks }

// Dmsg returns underlying dmsg client.
func (n *Network) Dmsg() *dmsg.Client { return n.dmsgC }

// Dial dials a node by its public key and returns a connection.
func (n *Network) Dial(network string, pk cipher.PubKey, port uint16) (*Conn, error) {
ctx := context.Background()
switch network {
Expand All @@ -110,6 +120,7 @@ func (n *Network) Dial(network string, pk cipher.PubKey, port uint16) (*Conn, er
}
}

// Listen listens on the specified port.
func (n *Network) Listen(network string, port uint16) (*Listener, error) {
switch network {
case DmsgType:
Expand All @@ -123,6 +134,7 @@ func (n *Network) Listen(network string, port uint16) (*Listener, error) {
}
}

// Listener represents a listener.
type Listener struct {
net.Listener
lPK cipher.PubKey
Expand All @@ -135,10 +147,16 @@ func makeListener(l net.Listener, network string) *Listener {
return &Listener{Listener: l, lPK: lPK, lPort: lPort, network: network}
}

// LocalPK returns a local public key of listener.
func (l Listener) LocalPK() cipher.PubKey { return l.lPK }
func (l Listener) LocalPort() uint16 { return l.lPort }
func (l Listener) Network() string { return l.network }

// LocalPort returns a local port of listener.
func (l Listener) LocalPort() uint16 { return l.lPort }

// Network returns a network of listener.
func (l Listener) Network() string { return l.network }

// AcceptConn accepts a connection from listener.
func (l Listener) AcceptConn() (*Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
Expand All @@ -147,6 +165,7 @@ func (l Listener) AcceptConn() (*Conn, error) {
return makeConn(conn, l.network), nil
}

// Conn represent a connection between nodes in Skywire.
type Conn struct {
net.Conn
lPK cipher.PubKey
Expand All @@ -162,11 +181,20 @@ func makeConn(conn net.Conn, network string) *Conn {
return &Conn{Conn: conn, lPK: lPK, rPK: rPK, lPort: lPort, rPort: rPort, network: network}
}

func (c Conn) LocalPK() cipher.PubKey { return c.lPK }
// LocalPK returns local public key of connection.
func (c Conn) LocalPK() cipher.PubKey { return c.lPK }

// RemotePK returns remote public key of connection.
func (c Conn) RemotePK() cipher.PubKey { return c.rPK }
func (c Conn) LocalPort() uint16 { return c.lPort }
func (c Conn) RemotePort() uint16 { return c.rPort }
func (c Conn) Network() string { return c.network }

// LocalPort returns local port of connection.
func (c Conn) LocalPort() uint16 { return c.lPort }

// RemotePort returns remote port of connection.
func (c Conn) RemotePort() uint16 { return c.rPort }

// Network returns network of connection.
func (c Conn) Network() string { return c.network }

func disassembleAddr(addr net.Addr) (pk cipher.PubKey, port uint16) {
strs := strings.Split(addr.String(), ":")
Expand Down
2 changes: 1 addition & 1 deletion pkg/snet/snettest/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func NewEnv(t *testing.T, keys []KeyPair) *Env {
}
}

// TearDown shutdowns the Env.
// Teardown shutdowns the Env.
func (e *Env) Teardown() { e.teardown() }

func createDmsgSrv(t *testing.T, dc disc.APIClient) (srv *dmsg.Server, srvErr <-chan error) {
Expand Down
3 changes: 2 additions & 1 deletion pkg/therealssh/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ func (s *Session) Run(command string) ([]byte, error) {
}() // Best effort.

// as stated in https://github.com/creack/pty/issues/21#issuecomment-513069505 we can ignore this error
res, _ := ioutil.ReadAll(ptmx) // nolint: err
res, err := ioutil.ReadAll(ptmx)
_ = err
return res, nil
}

Expand Down
Loading

0 comments on commit 4fb40ea

Please sign in to comment.