Skip to content

Commit

Permalink
Improve code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
nkryuchkov committed Dec 13, 2019
1 parent 3750f35 commit 9db2f8b
Show file tree
Hide file tree
Showing 19 changed files with 37 additions and 2 deletions.
2 changes: 2 additions & 0 deletions pkg/app/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ func (c *Client) Dial(remote appnet.Addr) (net.Conn, error) {

conn.freeConnMx.Lock()
free, err := c.cm.Add(connID, conn)

if err != nil {
conn.freeConnMx.Unlock()

if err := conn.Close(); err != nil {
c.log.WithError(err).Error("error closing conn")
}
Expand Down
2 changes: 2 additions & 0 deletions pkg/app/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func TestConn_Read(t *testing.T) {
}

for _, tc := range tt {
tc := tc
t.Run(tc.name, func(t *testing.T) {
rpc := &MockRPCClient{}
rpc.On("Read", connID, tc.readBuff).Return(tc.readN, tc.readErr)
Expand Down Expand Up @@ -67,6 +68,7 @@ func TestConn_Write(t *testing.T) {
}

for _, tc := range tt {
tc := tc
t.Run(tc.name, func(t *testing.T) {
rpc := &MockRPCClient{}
rpc.On("Write", connID, tc.writeBuff).Return(tc.writeN, tc.writeErr)
Expand Down
4 changes: 4 additions & 0 deletions pkg/app/idmanager/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ func TestManager_DoRange(t *testing.T) {

// run full range
gotVals := make([]int, 0, valsCount)

m.DoRange(func(_ uint16, v interface{}) bool {
val, ok := v.(int)
require.True(t, ok)
Expand All @@ -373,6 +374,7 @@ func TestManager_DoRange(t *testing.T) {
// run part range
var gotVal int
gotValsCount := 0

m.DoRange(func(_ uint16, v interface{}) bool {
if gotValsCount == 1 {
return false
Expand All @@ -389,11 +391,13 @@ func TestManager_DoRange(t *testing.T) {
})

found := false

for _, v := range vals {
if v == gotVal {
found = true
}
}

require.True(t, found)
}

Expand Down
4 changes: 4 additions & 0 deletions pkg/app/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func (l *Listener) Accept() (net.Conn, error) {
if err != nil {
return nil, err
}

l.log.Infoln("Accepted conn from app RPC")

conn := &Conn{
Expand All @@ -49,12 +50,14 @@ func (l *Listener) Accept() (net.Conn, error) {
free, err := l.cm.Add(connID, conn)
if err != nil {
conn.freeConnMx.Unlock()

if err := conn.Close(); err != nil {
l.log.WithError(err).Error("error closing listener")
}

return nil, err
}

conn.freeConn = free
conn.freeConnMx.Unlock()

Expand All @@ -71,6 +74,7 @@ func (l *Listener) Close() error {
}

var conns []net.Conn

l.cm.DoRange(func(_ uint16, v interface{}) bool {
conn, err := idmanager.AssertConn(v)
if err != nil {
Expand Down
2 changes: 2 additions & 0 deletions pkg/app/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func NewLogger(appName string) *logging.MasterLogger {

l := newAppLogger()
l.SetOutput(io.MultiWriter(l.Out, db))

os.Args = append([]string{os.Args[0]}, os.Args[2:]...)

return l
Expand All @@ -45,5 +46,6 @@ func newPersistentLogger(path, appName string) (*logging.MasterLogger, LogStore,
func newAppLogger() *logging.MasterLogger {
l := logging.NewMasterLogger()
l.Logger.Formatter.(*logging.TextFormatter).TimestampFormat = time.RFC3339Nano

return l
}
8 changes: 8 additions & 0 deletions pkg/app/log_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ func newBoltDB(path, appName string) (_ LogStore, err error) {
if err != nil {
return nil, err
}

defer func() {
cErr := db.Close()
err = cErr
Expand Down Expand Up @@ -75,6 +76,7 @@ func (l *boltDBappLogs) Write(p []byte) (int, error) {
if err != nil {
return 0, err
}

defer func() {
err := db.Close()
if err != nil {
Expand Down Expand Up @@ -103,12 +105,14 @@ func (l *boltDBappLogs) Store(t time.Time, s string) (err error) {
if err != nil {
return err
}

defer func() {
cErr := db.Close()
err = cErr
}()

parsedTime := []byte(t.Format(time.RFC3339Nano))

return db.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(l.bucket)
return b.Put(parsedTime, []byte(s))
Expand Down Expand Up @@ -148,18 +152,22 @@ func (l *boltDBappLogs) LogsSince(t time.Time) (logs []string, err error) {

func iterateFromKey(c *bbolt.Cursor) []string {
logs := make([]string, 0)

for k, v := c.Next(); k != nil; k, v = c.Next() {
logs = append(logs, string(v))
}

return logs
}

func iterateFromBeginning(c *bbolt.Cursor, parsedTime []byte) []string {
logs := make([]string, 0)

for k, v := c.First(); k != nil; k, v = c.Next() {
if bytes.Compare(k, parsedTime) < 0 {
continue
}

logs = append(logs, string(v))
}

Expand Down
1 change: 0 additions & 1 deletion pkg/app/rpc_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ func TestRPCClient_Dial(t *testing.T) {
require.NoError(t, err)
require.Equal(t, connID, uint16(1))
require.Equal(t, localPort, routing.Port(dmsgLocal.Port))

})

t.Run("dial error", func(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions pkg/dmsgpty/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ func (c *CLI) RequestPty() error {
func (c *CLI) ptyResizeLoop(ctx context.Context, ptyC *pty.Client) error {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGWINCH)

for {
select {
case <-ctx.Done():
Expand Down
2 changes: 2 additions & 0 deletions pkg/dmsgpty/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ func (h *Host) ServeRemoteRequests(ctx context.Context) {
// ServeCLIRequests serves local requests from CLI.
func (h *Host) ServeCLIRequests(ctx context.Context) {
wg := new(sync.WaitGroup)

defer func() {
wg.Wait()
h.cleanup()
Expand Down Expand Up @@ -285,6 +286,7 @@ func (h *Host) handlePtyReq(ctx context.Context, log logrus.FieldLogger, req *Pt
if err != nil {
return nil, err
}

go func() {
<-ctx.Done()
log.WithError(dmsgConn.Close()).
Expand Down
3 changes: 3 additions & 0 deletions pkg/dmsgpty/pty/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,13 @@ func (s *Server) Serve(ctx context.Context, lis *dmsg.Listener) {
if err := st.Close(); err != nil {
log.WithError(err).Warn("close transport error")
}

continue
}

log.Info("request accepted")
wg.Add(1)

go func(st *dmsg.Stream) {
done := make(chan struct{})
defer func() {
Expand Down Expand Up @@ -126,6 +128,7 @@ func (s *Server) handleConn(log logrus.FieldLogger, _ cipher.PubKey, conn net.Co

// Prepare and serve gateway to connection.
ptyG := NewDirectGateway()

defer func() { _ = ptyG.Stop(nil, nil) }() //nolint:errcheck

rpcS := rpc.NewServer()
Expand Down
1 change: 1 addition & 0 deletions pkg/routing/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type BidirectionalRoute struct {
Reverse Path
}

// ForwardAndReverse generate forward and reverse routes for bidirectional route.
func (br *BidirectionalRoute) ForwardAndReverse() (forward, reverse Route) {
forwardRoute := Route{
Desc: br.Desc,
Expand Down
1 change: 1 addition & 0 deletions pkg/snet/snettest/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ func NewEnv(t *testing.T, keys []KeyPair, networks []string) *Env {

// Prepare `snets`.
ns := make([]*snet.Network, len(keys))

for i, pairs := range keys {
var dmsgClient *dmsg.Client
var stcpClient *stcp.Client
Expand Down
2 changes: 2 additions & 0 deletions pkg/snet/stcp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@ func newConn(conn net.Conn, deadline time.Time, hs Handshake, freePort func()) (
lAddr, rAddr, err := hs(conn, deadline)
if err != nil {
_ = conn.Close() //nolint:errcheck

if freePort != nil {
freePort()
}

return nil, err
}
return &Conn{Conn: conn, lAddr: lAddr, rAddr: rAddr, freePort: freePort}, nil
Expand Down
1 change: 1 addition & 0 deletions pkg/snet/stcp/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func prepareConns(t *testing.T) (*Conn, *Conn, func()) {
var b *Conn
var respErr error
done := make(chan struct{})

go func() {
b, respErr = newConn(bConn, time.Now().Add(HandshakeTimeout), rhs, nil)
close(done)
Expand Down
1 change: 1 addition & 0 deletions pkg/snet/stcp/handshake.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ func (f2 *Frame2) Sign(srcSK cipher.SecKey) error {
return err
}
f2.Sig = sig

fmt.Println("SIGN! len(b.Bytes)", len(b.Bytes()), cipher2.SumSHA256(b.Bytes()).Hex())
return nil
}
Expand Down
1 change: 1 addition & 0 deletions pkg/snet/stcp/handshake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func TestHandshake(t *testing.T) {
deadline := time.Now().Add(HandshakeTimeout)

respCh := make(chan hsResult, 1)

go func() {
defer close(respCh)
respHS := ResponderHandshake(func(f2 Frame2) error {
Expand Down
1 change: 1 addition & 0 deletions pkg/snet/stcp/pktable.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func NewTableFromFile(path string) (PKTable, error) {
entries = make(map[cipher.PubKey]string)
s = bufio.NewScanner(f)
)

for s.Scan() {
fields := strings.Fields(s.Text())
if len(fields) != 2 {
Expand Down
1 change: 1 addition & 0 deletions pkg/transport/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func (td *mockDiscoveryClient) GetTransportsByEdge(ctx context.Context, pk ciphe

func (td *mockDiscoveryClient) UpdateStatuses(ctx context.Context, statuses ...*Status) ([]*EntryWithStatus, error) {
res := make([]*EntryWithStatus, 0)

for _, status := range statuses {
entry, err := td.GetTransportByID(ctx, status.ID)
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion pkg/transport/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ func (se *SignedEntry) Signature(pk cipher.PubKey) (cipher.Sig, bool) {
func NewSignedEntry(entry *Entry, pk cipher.PubKey, secKey cipher.SecKey) (*SignedEntry, bool) {
se := &SignedEntry{Entry: entry}
return se, se.Sign(pk, secKey)

}

// Status represents the current state of a Transport from a Transport's single edge.
Expand Down

0 comments on commit 9db2f8b

Please sign in to comment.