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

Remove all global log invocations #31

Merged
merged 1 commit into from
Mar 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 6 additions & 4 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ type LocalConnection struct {
errorChan chan<- error
finished <-chan struct{} // closed to signal that actorLoop has finished
senders *gossipSenders
logger *log.Logger
}

// If the connection is successful, it will end up in the local peer's
// connections map.
func startLocalConnection(connRemote *remoteConnection, tcpConn *net.TCPConn, router *Router, acceptNewPeer bool) {
func startLocalConnection(connRemote *remoteConnection, tcpConn *net.TCPConn, router *Router, acceptNewPeer bool, logger *log.Logger) {
if connRemote.local != router.Ourself.Peer {
log.Fatal("Attempt to create local connection from a peer which is not ourself")
panic("attempt to create local connection from a peer which is not ourself")
}
actionChan := make(chan connectionAction, ChannelSize)
errorChan := make(chan error, 1)
Expand All @@ -96,6 +97,7 @@ func startLocalConnection(connRemote *remoteConnection, tcpConn *net.TCPConn, ro
actionChan: actionChan,
errorChan: errorChan,
finished: finished,
logger: logger,
}
conn.senders = newGossipSenders(conn, finished)
go conn.run(actionChan, errorChan, finished, acceptNewPeer)
Expand Down Expand Up @@ -377,14 +379,14 @@ func (conn *LocalConnection) actorLoop(actionChan <-chan connectionAction, error

func (conn *LocalConnection) teardown(err error) {
if conn.remote == nil {
log.Printf("->[%s] connection shutting down due to error during handshake: %v", conn.remoteTCPAddr, err)
conn.logger.Printf("->[%s] connection shutting down due to error during handshake: %v", conn.remoteTCPAddr, err)
} else {
conn.log("connection shutting down due to error:", err)
}

if conn.tcpConn != nil {
if err := conn.tcpConn.Close(); err != nil {
log.Printf("warning: %v", err)
conn.logger.Printf("warning: %v", err)
}
}

Expand Down
10 changes: 6 additions & 4 deletions connection_maker.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type connectionMaker struct {
connections map[Connection]struct{}
directPeers peerAddrs
actionChan chan<- connectionMakerAction
logger *log.Logger
}

// TargetState describes the connection state of a remote target.
Expand Down Expand Up @@ -57,7 +58,7 @@ type connectionMakerAction func() bool
// peers, making outbound connections from localAddr, and listening on
// port. If discovery is true, ConnectionMaker will attempt to
// initiate new connections with peers it's not directly connected to.
func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port int, discovery bool) *connectionMaker {
func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port int, discovery bool, logger *log.Logger) *connectionMaker {
actionChan := make(chan connectionMakerAction, ChannelSize)
cm := &connectionMaker{
ourself: ourself,
Expand All @@ -69,6 +70,7 @@ func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port
targets: make(map[string]*target),
connections: make(map[Connection]struct{}),
actionChan: actionChan,
logger: logger,
}
go cm.queryLoop(actionChan)
return cm
Expand Down Expand Up @@ -365,9 +367,9 @@ func (cm *connectionMaker) connectToTargets(validTarget map[string]struct{}, dir
}

func (cm *connectionMaker) attemptConnection(address string, acceptNewPeer bool) {
log.Printf("->[%s] attempting connection", address)
if err := cm.ourself.createConnection(cm.localAddr, address, acceptNewPeer); err != nil {
log.Printf("->[%s] error during connection attempt: %v", address, err)
cm.logger.Printf("->[%s] attempting connection", address)
if err := cm.ourself.createConnection(cm.localAddr, address, acceptNewPeer, cm.logger); err != nil {
cm.logger.Printf("->[%s] error during connection attempt: %v", address, err)
cm.connectionAborted(address, err)
}
}
Expand Down
26 changes: 12 additions & 14 deletions examples/increment-only-counter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
Expand All @@ -29,20 +30,20 @@ func main() {
flag.Var(peers, "peer", "initial peer (may be repeated)")
flag.Parse()

log.SetPrefix(*nickname + "> ")
logger := log.New(os.Stderr, *nickname+"> ", log.LstdFlags)

host, portStr, err := net.SplitHostPort(*meshListen)
if err != nil {
log.Fatalf("mesh address: %s: %v", *meshListen, err)
logger.Fatalf("mesh address: %s: %v", *meshListen, err)
}
port, err := strconv.Atoi(portStr)
if err != nil {
log.Fatalf("mesh address: %s: %v", *meshListen, err)
logger.Fatalf("mesh address: %s: %v", *meshListen, err)
}

name, err := mesh.PeerNameFromString(*hwaddr)
if err != nil {
log.Fatalf("%s: %v", *hwaddr, err)
logger.Fatalf("%s: %v", *hwaddr, err)
}

router := mesh.NewRouter(mesh.Config{
Expand All @@ -53,38 +54,35 @@ func main() {
ConnLimit: 64,
PeerDiscovery: true,
TrustedSubnets: []*net.IPNet{},
}, name, *nickname, mesh.NullOverlay{})
}, name, *nickname, mesh.NullOverlay{}, log.New(ioutil.Discard, "", 0))

peer := newPeer(name, log.New(os.Stderr, *nickname+"> ", log.LstdFlags))
peer := newPeer(name, logger)
gossip := router.NewGossip(*channel, peer)
peer.register(gossip)

func() {
log.Printf("mesh router starting (%s)", *meshListen)
logger.Printf("mesh router starting (%s)", *meshListen)
router.Start()
}()
defer func() {
log.Printf("mesh router stopping")
logger.Printf("mesh router stopping")
router.Stop()
}()

router.ConnectionMaker.InitiateConnections(peers.slice(), true)

errs := make(chan error, 2)

errs := make(chan error)
go func() {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT)
errs <- fmt.Errorf("%s", <-c)
}()

go func() {
log.Printf("HTTP server starting (%s)", *httpListen)
logger.Printf("HTTP server starting (%s)", *httpListen)
http.HandleFunc("/", handle(peer))
errs <- http.ListenAndServe(*httpListen, nil)
}()

log.Print(<-errs)
logger.Print(<-errs)
}

type counter interface {
Expand Down
8 changes: 5 additions & 3 deletions gossip_channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,18 @@ type gossipChannel struct {
ourself *localPeer
routes *routes
gossiper Gossiper
logger *log.Logger
}

// newGossipChannel returns a named, usable channel.
// It delegates receiving duties to the passed Gossiper.
func newGossipChannel(channelName string, ourself *localPeer, r *routes, g Gossiper) *gossipChannel {
func newGossipChannel(channelName string, ourself *localPeer, r *routes, g Gossiper, logger *log.Logger) *gossipChannel {
return &gossipChannel{
name: channelName,
ourself: ourself,
routes: r,
gossiper: g,
logger: logger,
}
}

Expand Down Expand Up @@ -134,7 +136,7 @@ func (c *gossipChannel) makeBroadcastMsg(srcName PeerName, msg []byte) protocolM
}

func (c *gossipChannel) log(args ...interface{}) {
log.Println(append(append([]interface{}{}, "[gossip "+c.name+"]:"), args...)...)
c.logger.Println(append(append([]interface{}{}, "[gossip "+c.name+"]:"), args...)...)
}

// GobEncode gob-encodes each item and returns the resulting byte slice.
Expand All @@ -143,7 +145,7 @@ func gobEncode(items ...interface{}) []byte {
enc := gob.NewEncoder(buf)
for _, i := range items {
if err := enc.Encode(i); err != nil {
log.Fatal(err)
panic(err)
}
}
return buf.Bytes()
Expand Down
6 changes: 4 additions & 2 deletions gossip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package mesh

import (
"fmt"
"io/ioutil"
"log"
"sync"
"testing"

Expand All @@ -22,7 +24,7 @@ var _ gossipConnection = &mockGossipConnection{}

func newTestRouter(name string) *Router {
peerName, _ := PeerNameFromString(name)
router := NewRouter(Config{}, peerName, "nick", nil)
router := NewRouter(Config{}, peerName, "nick", nil, log.New(ioutil.Discard, "", 0))

This comment was marked as abuse.

This comment was marked as abuse.

This comment was marked as abuse.

This comment was marked as abuse.

This comment was marked as abuse.

router.Start()
return router
}
Expand Down Expand Up @@ -74,7 +76,7 @@ func (router *Router) newTestGossipConnection(r *Router) *mockGossipConnection {
toPeer = router.Peers.fetchWithDefault(toPeer) // Has side-effect of incrementing refcount

conn := &mockGossipConnection{
remoteConnection: remoteConnection{router.Ourself.Peer, toPeer, "", false, true},
remoteConnection: *newRemoteConnection(router.Ourself.Peer, toPeer, "", false, true),
dest: r,
start: make(chan struct{}),
}
Expand Down
14 changes: 7 additions & 7 deletions local_peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (peer *localPeer) ConnectionsTo(names []PeerName) []Connection {
// createConnection creates a new connection, originating from
// localAddr, to peerAddr. If acceptNewPeer is false, peerAddr must
// already be a member of the mesh.
func (peer *localPeer) createConnection(localAddr string, peerAddr string, acceptNewPeer bool) error {
func (peer *localPeer) createConnection(localAddr string, peerAddr string, acceptNewPeer bool, logger *log.Logger) error {
if err := peer.checkConnectionLimit(); err != nil {
return err
}
Expand All @@ -96,7 +96,7 @@ func (peer *localPeer) createConnection(localAddr string, peerAddr string, accep
return err
}
connRemote := newRemoteConnection(peer.Peer, nil, tcpConn.RemoteAddr().String(), true, false)
startLocalConnection(connRemote, tcpConn, peer.router, acceptNewPeer)
startLocalConnection(connRemote, tcpConn, peer.router, acceptNewPeer, logger)
return nil
}

Expand Down Expand Up @@ -150,10 +150,10 @@ func (peer *localPeer) actorLoop(actionChan <-chan localPeerAction) {

func (peer *localPeer) handleAddConnection(conn ourConnection) error {
if peer.Peer != conn.getLocal() {
log.Fatal("Attempt made to add connection to peer where peer is not the source of connection")
panic("Attempt made to add connection to peer where peer is not the source of connection")
}
if conn.Remote() == nil {
log.Fatal("Attempt made to add connection to peer with unknown remote peer")
panic("Attempt made to add connection to peer with unknown remote peer")
}
toName := conn.Remote().Name
dupErr := fmt.Errorf("Multiple connections to %s added to %s", conn.Remote(), peer.String())
Expand Down Expand Up @@ -196,7 +196,7 @@ func (peer *localPeer) handleAddConnection(conn ourConnection) error {

func (peer *localPeer) handleConnectionEstablished(conn ourConnection) {
if peer.Peer != conn.getLocal() {
log.Fatal("Peer informed of active connection where peer is not the source of connection")
panic("Peer informed of active connection where peer is not the source of connection")
}
if dupConn, found := peer.connections[conn.Remote().Name]; !found || conn != dupConn {
conn.shutdown(fmt.Errorf("Cannot set unknown connection active"))
Expand All @@ -211,10 +211,10 @@ func (peer *localPeer) handleConnectionEstablished(conn ourConnection) {

func (peer *localPeer) handleDeleteConnection(conn ourConnection) {
if peer.Peer != conn.getLocal() {
log.Fatal("Attempt made to delete connection from peer where peer is not the source of connection")
panic("Attempt made to delete connection from peer where peer is not the source of connection")
}
if conn.Remote() == nil {
log.Fatal("Attempt made to delete connection to peer with unknown remote peer")
panic("Attempt made to delete connection to peer with unknown remote peer")
}
toName := conn.Remote().Name
if connFound, found := peer.connections[toName]; !found || connFound != conn {
Expand Down
2 changes: 1 addition & 1 deletion metcd/metcdsrv/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func main() {
ConnLimit: 64,
PeerDiscovery: true,
TrustedSubnets: []*net.IPNet{},
}, name, *nickname, mesh.NullOverlay{})
}, name, *nickname, mesh.NullOverlay{}, logger)

// Create a meshconn.Peer.
peer := meshconn.NewPeer(name, router.Ourself.UID, logger)
Expand Down
2 changes: 1 addition & 1 deletion metcd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func NewDefaultServer(minPeerCount int, logger *log.Logger) *wackygrpc.Server {
ConnLimit: 64,
PeerDiscovery: true,
TrustedSubnets: []*net.IPNet{},
}, peerName, nickName, mesh.NullOverlay{})
}, peerName, nickName, mesh.NullOverlay{}, logger)

// Create a meshconn.Peer and connect it to a channel.
peer := meshconn.NewPeer(router.Ourself.Peer.Name, router.Ourself.UID, logger)
Expand Down
6 changes: 3 additions & 3 deletions mocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (peers *Peers) AddTestRemoteConnection(p1, p2 *Peer) {
fromPeer = peers.fetchWithDefault(fromPeer)
toPeer := newPeerFrom(p2)
toPeer = peers.fetchWithDefault(toPeer)
peers.ourself.addConnection(&remoteConnection{fromPeer, toPeer, "", false, false})
peers.ourself.addConnection(newRemoteConnection(fromPeer, toPeer, "", false, false))
}

func (peers *Peers) DeleteTestConnection(p *Peer) {
Expand All @@ -45,8 +45,8 @@ func (peers *Peers) DeleteTestConnection(p *Peer) {
// separate type in order to distinguish what is created by the test
// from what is created by the real code.
func newMockConnection(from, to *Peer) Connection {
type mockConnection struct{ remoteConnection }
return &mockConnection{remoteConnection{from, to, "", false, false}}
type mockConnection struct{ *remoteConnection }
return &mockConnection{newRemoteConnection(from, to, "", false, false)}
}

func checkEqualConns(t *testing.T, ourName PeerName, got, wanted map[PeerName]Connection) {
Expand Down
3 changes: 1 addition & 2 deletions peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"crypto/rand"
"encoding/binary"
"fmt"
"log"
"sort"
"strconv"
)
Expand Down Expand Up @@ -169,7 +168,7 @@ func randomPeerShortID() PeerShortID {
func randBytes(n int) []byte {
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
log.Fatal(err)
panic(err)
}
return buf
}
Expand Down
5 changes: 2 additions & 3 deletions peers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"encoding/gob"
"io"
"log"
"math/rand"
"sync"
)
Expand Down Expand Up @@ -521,7 +520,7 @@ func (peers *Peers) applyDecodedUpdate(decodedUpdate []*Peer, decodedConns [][]c

func (peer *Peer) encode(enc *gob.Encoder) {
if err := enc.Encode(peer.peerSummary); err != nil {
log.Fatal(err)
panic(err)
}

connSummaries := []connectionSummary{}
Expand All @@ -535,7 +534,7 @@ func (peer *Peer) encode(enc *gob.Encoder) {
}

if err := enc.Encode(connSummaries); err != nil {
log.Fatal(err)
panic(err)
}
}

Expand Down
Loading