Skip to content

Commit bad4db3

Browse files
author
Brian Tiger Chow
committedNov 25, 2014
Merge pull request #363 from jbenet/misc/2014-10-2X
miscellaneous fixes
2 parents 1820216 + 0fc95d5 commit bad4db3

File tree

18 files changed

+96
-66
lines changed

18 files changed

+96
-66
lines changed
 

‎cmd/ipfs/daemon.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"fmt"
55
"net/http"
6+
"os"
67

78
manners "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/braintree/manners"
89
ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
@@ -23,6 +24,7 @@ const (
2324
ipnsMountKwd = "mount-ipns"
2425
// apiAddrKwd = "address-api"
2526
// swarmAddrKwd = "address-swarm"
27+
originEnvKey = "API_ORIGIN"
2628
)
2729

2830
var daemonCmd = &cmds.Command{
@@ -144,9 +146,11 @@ func listenAndServeAPI(node *core.IpfsNode, req cmds.Request, addr ma.Multiaddr)
144146
return err
145147
}
146148

149+
origin := os.Getenv(originEnvKey)
150+
147151
server := manners.NewServer()
148152
mux := http.NewServeMux()
149-
cmdHandler := cmdsHttp.NewHandler(*req.Context(), commands.Root)
153+
cmdHandler := cmdsHttp.NewHandler(*req.Context(), commands.Root, origin)
150154
mux.Handle(cmdsHttp.ApiPath+"/", cmdHandler)
151155

152156
ifpsHandler := &ipfsHandler{node}

‎cmd/ipfs/main.go

+9-6
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
1515
manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr-net"
1616

17+
context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
1718
cmds "github.com/jbenet/go-ipfs/commands"
1819
cmdsCli "github.com/jbenet/go-ipfs/commands/cli"
1920
cmdsHttp "github.com/jbenet/go-ipfs/commands/http"
@@ -53,6 +54,7 @@ type cmdInvocation struct {
5354
// - output the response
5455
// - if anything fails, print error, maybe with help
5556
func main() {
57+
ctx := context.Background()
5658
var err error
5759
var invoc cmdInvocation
5860
defer invoc.close()
@@ -114,7 +116,7 @@ func main() {
114116
}
115117

116118
// ok, finally, run the command invocation.
117-
output, err := invoc.Run()
119+
output, err := invoc.Run(ctx)
118120
if err != nil {
119121
printErr(err)
120122

@@ -129,7 +131,7 @@ func main() {
129131
io.Copy(os.Stdout, output)
130132
}
131133

132-
func (i *cmdInvocation) Run() (output io.Reader, err error) {
134+
func (i *cmdInvocation) Run(ctx context.Context) (output io.Reader, err error) {
133135
// setup our global interrupt handler.
134136
i.setupInterruptHandler()
135137

@@ -153,7 +155,7 @@ func (i *cmdInvocation) Run() (output io.Reader, err error) {
153155
defer stopProfilingFunc() // to be executed as late as possible
154156
}
155157

156-
res, err := callCommand(i.req, Root)
158+
res, err := callCommand(ctx, i.req, Root)
157159
if err != nil {
158160
return nil, err
159161
}
@@ -243,8 +245,9 @@ func (i *cmdInvocation) requestedHelp() (short bool, long bool, err error) {
243245
return longHelp, shortHelp, nil
244246
}
245247

246-
func callPreCommandHooks(details cmdDetails, req cmds.Request, root *cmds.Command) error {
248+
func callPreCommandHooks(ctx context.Context, details cmdDetails, req cmds.Request, root *cmds.Command) error {
247249

250+
log.Event(ctx, "callPreCommandHooks", &details)
248251
log.Debug("Calling pre-command hooks...")
249252

250253
// some hooks only run when the command is executed locally
@@ -284,7 +287,7 @@ func callPreCommandHooks(details cmdDetails, req cmds.Request, root *cmds.Comman
284287
return nil
285288
}
286289

287-
func callCommand(req cmds.Request, root *cmds.Command) (cmds.Response, error) {
290+
func callCommand(ctx context.Context, req cmds.Request, root *cmds.Command) (cmds.Response, error) {
288291
var res cmds.Response
289292

290293
details, err := commandDetails(req.Path(), root)
@@ -297,7 +300,7 @@ func callCommand(req cmds.Request, root *cmds.Command) (cmds.Response, error) {
297300
return nil, err
298301
}
299302

300-
err = callPreCommandHooks(*details, req, root)
303+
err = callPreCommandHooks(ctx, *details, req, root)
301304
if err != nil {
302305
return nil, err
303306
}

‎commands/http/handler.go

+15-4
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ import (
1212
var log = u.Logger("commands/http")
1313

1414
type Handler struct {
15-
ctx cmds.Context
16-
root *cmds.Command
15+
ctx cmds.Context
16+
root *cmds.Command
17+
origin string
1718
}
1819

1920
var ErrNotFound = errors.New("404 page not found")
@@ -29,13 +30,23 @@ var mimeTypes = map[string]string{
2930
cmds.Text: "text/plain",
3031
}
3132

32-
func NewHandler(ctx cmds.Context, root *cmds.Command) *Handler {
33-
return &Handler{ctx, root}
33+
func NewHandler(ctx cmds.Context, root *cmds.Command, origin string) *Handler {
34+
// allow whitelisted origins (so we can make API requests from the browser)
35+
if len(origin) > 0 {
36+
log.Info("Allowing API requests from origin: " + origin)
37+
}
38+
39+
return &Handler{ctx, root, origin}
3440
}
3541

3642
func (i Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
3743
log.Debug("Incoming API request: ", r.URL)
3844

45+
if len(i.origin) > 0 {
46+
w.Header().Set("Access-Control-Allow-Origin", i.origin)
47+
}
48+
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
49+
3950
req, err := Parse(r, i.root)
4051
if err != nil {
4152
if err == ErrNotFound {

‎config/config.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ func (i *Identity) DecodePrivateKey(passphrase string) (crypto.PrivateKey, error
146146
// Load reads given file and returns the read config, or error.
147147
func Load(filename string) (*Config, error) {
148148
// if nothing is there, fail. User must run 'ipfs init'
149-
if _, err := os.Stat(filename); os.IsNotExist(err) {
149+
if !u.FileExists(filename) {
150150
return nil, debugerror.New("ipfs not initialized, please run 'ipfs init'")
151151
}
152152

‎core/core.go

+9-4
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,12 @@ import (
2929
u "github.com/jbenet/go-ipfs/util"
3030
ctxc "github.com/jbenet/go-ipfs/util/ctxcloser"
3131
"github.com/jbenet/go-ipfs/util/debugerror"
32+
"github.com/jbenet/go-ipfs/util/eventlog"
3233
)
3334

3435
const IpnsValidatorTag = "ipns"
3536

36-
var log = u.Logger("core")
37+
var log = eventlog.Logger("core")
3738

3839
// IpfsNode is IPFS Core module. It represents an IPFS instance.
3940
type IpfsNode struct {
@@ -242,9 +243,11 @@ func initIdentity(cfg *config.Identity, peers peer.Peerstore, online bool) (peer
242243
}
243244

244245
func initConnections(ctx context.Context, cfg *config.Config, pstore peer.Peerstore, route *dht.IpfsDHT) {
246+
// TODO consider stricter error handling
247+
// TODO consider Criticalf error logging
245248
for _, p := range cfg.Bootstrap {
246249
if p.PeerID == "" {
247-
log.Errorf("error: peer does not include PeerID. %v", p)
250+
log.Criticalf("error: peer does not include PeerID. %v", p)
248251
}
249252

250253
maddr, err := ma.NewMultiaddr(p.Address)
@@ -256,14 +259,16 @@ func initConnections(ctx context.Context, cfg *config.Config, pstore peer.Peerst
256259
// setup peer
257260
npeer, err := pstore.Get(peer.DecodePrettyID(p.PeerID))
258261
if err != nil {
259-
log.Errorf("Bootstrapping error: %v", err)
262+
log.Criticalf("Bootstrapping error: %v", err)
260263
continue
261264
}
262265
npeer.AddAddress(maddr)
263266

264267
if _, err = route.Connect(ctx, npeer); err != nil {
265-
log.Errorf("Bootstrapping error: %v", err)
268+
log.Criticalf("Bootstrapping error: %v", err)
269+
continue
266270
}
271+
log.Event(ctx, "bootstrap", npeer)
267272
}
268273
}
269274

‎exchange/bitswap/bitswap.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,8 @@ func New(ctx context.Context, p peer.Peer,
3131

3232
notif := notifications.New()
3333
go func() {
34-
select {
35-
case <-ctx.Done():
36-
notif.Shutdown()
37-
}
34+
<-ctx.Done()
35+
notif.Shutdown()
3836
}()
3937

4038
bs := &bitswap{

‎exchange/bitswap/notifications/notifications.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func (ps *impl) Publish(block blocks.Block) {
3434
func (ps *impl) Subscribe(ctx context.Context, k u.Key) <-chan blocks.Block {
3535
topic := string(k)
3636
subChan := ps.wrapped.SubOnce(topic)
37-
blockChannel := make(chan blocks.Block)
37+
blockChannel := make(chan blocks.Block, 1) // buffered so the sender doesn't wait on receiver
3838
go func() {
3939
defer close(blockChannel)
4040
select {

‎importer/chunk/splitting.go

+11-22
Original file line numberDiff line numberDiff line change
@@ -28,28 +28,17 @@ func (ss *SizeSplitter) Split(r io.Reader) chan []byte {
2828
for {
2929
// log.Infof("making chunk with size: %d", ss.Size)
3030
chunk := make([]byte, ss.Size)
31-
sofar := 0
32-
33-
// this-chunk loop (keep reading until this chunk full)
34-
for {
35-
nread, err := r.Read(chunk[sofar:])
36-
sofar += nread
37-
if err == io.EOF {
38-
if sofar > 0 {
39-
// log.Infof("sending out chunk with size: %d", sofar)
40-
out <- chunk[:sofar]
41-
}
42-
return
43-
}
44-
if err != nil {
45-
log.Errorf("Block split error: %s", err)
46-
return
47-
}
48-
if sofar == ss.Size {
49-
// log.Infof("sending out chunk with size: %d", sofar)
50-
out <- chunk[:sofar]
51-
break // break out of this-chunk loop
52-
}
31+
nread, err := io.ReadFull(r, chunk)
32+
if nread > 0 {
33+
// log.Infof("sending out chunk with size: %d", sofar)
34+
out <- chunk[:nread]
35+
}
36+
if err == io.EOF || err == io.ErrUnexpectedEOF {
37+
return
38+
}
39+
if err != nil {
40+
log.Errorf("Block split error: %s", err)
41+
return
5342
}
5443
}
5544
}()

‎net/message/message.go

+11
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
type NetMessage interface {
1111
Peer() peer.Peer
1212
Data() []byte
13+
Loggable() map[string]interface{}
1314
}
1415

1516
// New is the interface for constructing a new message.
@@ -35,6 +36,16 @@ func (m *message) Data() []byte {
3536
return m.data
3637
}
3738

39+
func (m *message) Loggable() map[string]interface{} {
40+
return map[string]interface{}{
41+
"netMessage": map[string]interface{}{
42+
"recipient": m.Peer(),
43+
// TODO sizeBytes? bytes? lenBytes?
44+
"size": len(m.Data()),
45+
},
46+
}
47+
}
48+
3849
// FromObject creates a message from a protobuf-marshallable message.
3950
func FromObject(p peer.Peer, data proto.Message) (NetMessage, error) {
4051
bytes, err := proto.Marshal(data)

‎net/swarm/conn.go

+3-4
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,6 @@ func (s *Swarm) peerMultiConn(p peer.Peer) (*conn.MultiConn, error) {
122122
s.Children().Add(1)
123123
mc.Children().Add(1) // child of Conn as well.
124124
go s.fanInSingle(mc)
125-
log.Debugf("added new multiconn: %s", mc)
126125
return mc, nil
127126
}
128127

@@ -133,7 +132,7 @@ func (s *Swarm) connSetup(c conn.Conn) (conn.Conn, error) {
133132
return nil, errors.New("Tried to start nil connection.")
134133
}
135134

136-
log.Debugf("%s Started connection: %s", c.LocalPeer(), c.RemotePeer())
135+
log.Event(context.TODO(), "connSetupBegin", c.LocalPeer(), c.RemotePeer())
137136

138137
// add address of connection to Peer. Maybe it should happen in connSecure.
139138
// NOT adding this address here, because the incoming address in TCP
@@ -163,8 +162,7 @@ func (s *Swarm) connSetup(c conn.Conn) (conn.Conn, error) {
163162
return nil, err
164163
}
165164
mc.Add(c)
166-
log.Debugf("multiconn added new conn %s", c)
167-
165+
log.Event(context.TODO(), "connSetupSuccess", c.LocalPeer(), c.RemotePeer())
168166
return c, nil
169167
}
170168

@@ -200,6 +198,7 @@ func (s *Swarm) fanOut() {
200198

201199
i++
202200
log.Debugf("%s sent message to %s (%d)", s.local, msg.Peer(), i)
201+
log.Event(context.TODO(), "sendMessage", s.local, msg)
203202
// queue it in the connection's buffer
204203
c.Out() <- msg.Data()
205204
}

‎net/swarm/swarm.go

+2
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ func (s *Swarm) Dial(peer peer.Peer) (conn.Conn, error) {
151151
return nil, err
152152
}
153153

154+
// TODO replace the TODO ctx with a context passed in from caller
155+
log.Event(context.TODO(), "dial", peer)
154156
return c, nil
155157
}
156158

‎routing/dht/dht.go

+5-6
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,6 @@ func NewDHT(ctx context.Context, p peer.Peer, ps peer.Peerstore, dialer inet.Dia
9898

9999
// Connect to a new peer at the given address, ping and add to the routing table
100100
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.Peer) (peer.Peer, error) {
101-
log.Debugf("Connect to new peer: %s", npeer)
102-
103101
// TODO(jbenet,whyrusleeping)
104102
//
105103
// Connect should take in a Peer (with ID). In a sense, we shouldn't be
@@ -120,8 +118,9 @@ func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.Peer) (peer.Peer, er
120118
if err != nil {
121119
return nil, fmt.Errorf("failed to ping newly connected peer: %s\n", err)
122120
}
121+
log.Event(ctx, "connect", dht.self, npeer)
123122

124-
dht.Update(npeer)
123+
dht.Update(ctx, npeer)
125124

126125
return npeer, nil
127126
}
@@ -150,7 +149,7 @@ func (dht *IpfsDHT) HandleMessage(ctx context.Context, mes msg.NetMessage) msg.N
150149
}
151150

152151
// update the peer (on valid msgs only)
153-
dht.Update(mPeer)
152+
dht.Update(ctx, mPeer)
154153

155154
log.Event(ctx, "foo", dht.self, mPeer, pmes)
156155

@@ -397,8 +396,8 @@ func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
397396

398397
// Update signals to all routingTables to Update their last-seen status
399398
// on the given peer.
400-
func (dht *IpfsDHT) Update(p peer.Peer) {
401-
log.Debugf("updating peer: %s latency = %f\n", p, p.GetLatency().Seconds())
399+
func (dht *IpfsDHT) Update(ctx context.Context, p peer.Peer) {
400+
log.Event(ctx, "updatePeer", p)
402401
removedCount := 0
403402
for _, route := range dht.routingTables {
404403
removed := route.Update(p)

‎routing/dht/ext_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ func TestGetFailures(t *testing.T) {
129129

130130
d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
131131
other := makePeer(nil)
132-
d.Update(other)
132+
d.Update(ctx, other)
133133

134134
// This one should time out
135135
// u.POut("Timout Test\n")
@@ -232,7 +232,7 @@ func TestNotFound(t *testing.T) {
232232
var ps []peer.Peer
233233
for i := 0; i < 5; i++ {
234234
ps = append(ps, _randPeer())
235-
d.Update(ps[i])
235+
d.Update(ctx, ps[i])
236236
}
237237

238238
// Reply with random peers to every message
@@ -298,7 +298,7 @@ func TestLessThanKResponses(t *testing.T) {
298298
var ps []peer.Peer
299299
for i := 0; i < 5; i++ {
300300
ps = append(ps, _randPeer())
301-
d.Update(ps[i])
301+
d.Update(ctx, ps[i])
302302
}
303303
other := _randPeer()
304304

0 commit comments

Comments
 (0)