Skip to content

Commit 7c9314f

Browse files
nonsensegbalint
authored andcommitted
swarm: integrate OpenTracing; propagate ctx to internal APIs (#17169)
* swarm: propagate ctx, enable opentracing * swarm/tracing: log error when tracing is misconfigured
1 parent f7d3678 commit 7c9314f

170 files changed

Lines changed: 21762 additions & 249 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎cmd/swarm/main.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import (
4343
"github.com/ethereum/go-ethereum/swarm"
4444
bzzapi "github.com/ethereum/go-ethereum/swarm/api"
4545
swarmmetrics "github.com/ethereum/go-ethereum/swarm/metrics"
46+
"github.com/ethereum/go-ethereum/swarm/tracing"
4647

4748
"gopkg.in/urfave/cli.v1"
4849
)
@@ -430,12 +431,14 @@ pv(1) tool to get a progress bar:
430431
app.Flags = append(app.Flags, rpcFlags...)
431432
app.Flags = append(app.Flags, debug.Flags...)
432433
app.Flags = append(app.Flags, swarmmetrics.Flags...)
434+
app.Flags = append(app.Flags, tracing.Flags...)
433435
app.Before = func(ctx *cli.Context) error {
434436
runtime.GOMAXPROCS(runtime.NumCPU())
435437
if err := debug.Setup(ctx, ""); err != nil {
436438
return err
437439
}
438440
swarmmetrics.Setup(ctx)
441+
tracing.Setup(ctx)
439442
return nil
440443
}
441444
app.After = func(ctx *cli.Context) error {

‎cmd/swarm/swarm-smoke/upload_and_sync.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,9 @@ func cliUploadAndSync(c *cli.Context) error {
7777
log.Info("uploaded successfully", "hash", hash, "digest", fmt.Sprintf("%x", fhash))
7878

7979
if filesize < 10 {
80-
time.Sleep(15 * time.Second)
80+
time.Sleep(35 * time.Second)
8181
} else {
82+
time.Sleep(15 * time.Second)
8283
time.Sleep(2 * time.Duration(filesize) * time.Second)
8384
}
8485

@@ -108,7 +109,7 @@ func cliUploadAndSync(c *cli.Context) error {
108109
// fetch is getting the requested `hash` from the `endpoint` and compares it with the `original` file
109110
func fetch(hash string, endpoint string, original []byte, ruid string) error {
110111
log.Trace("sleeping", "ruid", ruid)
111-
time.Sleep(1 * time.Second)
112+
time.Sleep(5 * time.Second)
112113

113114
log.Trace("http get request", "ruid", ruid, "api", endpoint, "hash", hash)
114115
res, err := http.Get(endpoint + "/bzz:/" + hash + "/")

‎p2p/protocols/protocol.go‎

Lines changed: 81 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ devp2p subprotocols by abstracting away code standardly shared by protocols.
2929
package protocols
3030

3131
import (
32+
"bufio"
33+
"bytes"
3234
"context"
3335
"fmt"
3436
"io"
@@ -39,6 +41,10 @@ import (
3941
"github.com/ethereum/go-ethereum/log"
4042
"github.com/ethereum/go-ethereum/metrics"
4143
"github.com/ethereum/go-ethereum/p2p"
44+
"github.com/ethereum/go-ethereum/rlp"
45+
"github.com/ethereum/go-ethereum/swarm/spancontext"
46+
"github.com/ethereum/go-ethereum/swarm/tracing"
47+
opentracing "github.com/opentracing/opentracing-go"
4248
)
4349

4450
// error codes used by this protocol scheme
@@ -109,6 +115,13 @@ func errorf(code int, format string, params ...interface{}) *Error {
109115
}
110116
}
111117

118+
// WrappedMsg is used to propagate marshalled context alongside message payloads
119+
type WrappedMsg struct {
120+
Context []byte
121+
Size uint32
122+
Payload []byte
123+
}
124+
112125
// Spec is a protocol specification including its name and version as well as
113126
// the types of messages which are exchanged
114127
type Spec struct {
@@ -201,7 +214,7 @@ func NewPeer(p *p2p.Peer, rw p2p.MsgReadWriter, spec *Spec) *Peer {
201214
// the handler argument is a function which is called for each message received
202215
// from the remote peer, a returned error causes the loop to exit
203216
// resulting in disconnection
204-
func (p *Peer) Run(handler func(msg interface{}) error) error {
217+
func (p *Peer) Run(handler func(ctx context.Context, msg interface{}) error) error {
205218
for {
206219
if err := p.handleIncoming(handler); err != nil {
207220
if err != io.EOF {
@@ -225,14 +238,47 @@ func (p *Peer) Drop(err error) {
225238
// message off to the peer
226239
// this low level call will be wrapped by libraries providing routed or broadcast sends
227240
// but often just used to forward and push messages to directly connected peers
228-
func (p *Peer) Send(msg interface{}) error {
241+
func (p *Peer) Send(ctx context.Context, msg interface{}) error {
229242
defer metrics.GetOrRegisterResettingTimer("peer.send_t", nil).UpdateSince(time.Now())
230243
metrics.GetOrRegisterCounter("peer.send", nil).Inc(1)
244+
245+
var b bytes.Buffer
246+
if tracing.Enabled {
247+
writer := bufio.NewWriter(&b)
248+
249+
tracer := opentracing.GlobalTracer()
250+
251+
sctx := spancontext.FromContext(ctx)
252+
253+
if sctx != nil {
254+
err := tracer.Inject(
255+
sctx,
256+
opentracing.Binary,
257+
writer)
258+
if err != nil {
259+
return err
260+
}
261+
}
262+
263+
writer.Flush()
264+
}
265+
266+
r, err := rlp.EncodeToBytes(msg)
267+
if err != nil {
268+
return err
269+
}
270+
271+
wmsg := WrappedMsg{
272+
Context: b.Bytes(),
273+
Size: uint32(len(r)),
274+
Payload: r,
275+
}
276+
231277
code, found := p.spec.GetCode(msg)
232278
if !found {
233279
return errorf(ErrInvalidMsgType, "%v", code)
234280
}
235-
return p2p.Send(p.rw, code, msg)
281+
return p2p.Send(p.rw, code, wmsg)
236282
}
237283

238284
// handleIncoming(code)
@@ -243,7 +289,7 @@ func (p *Peer) Send(msg interface{}) error {
243289
// * checks for out-of-range message codes,
244290
// * handles decoding with reflection,
245291
// * call handlers as callbacks
246-
func (p *Peer) handleIncoming(handle func(msg interface{}) error) error {
292+
func (p *Peer) handleIncoming(handle func(ctx context.Context, msg interface{}) error) error {
247293
msg, err := p.rw.ReadMsg()
248294
if err != nil {
249295
return err
@@ -255,11 +301,38 @@ func (p *Peer) handleIncoming(handle func(msg interface{}) error) error {
255301
return errorf(ErrMsgTooLong, "%v > %v", msg.Size, p.spec.MaxMsgSize)
256302
}
257303

304+
// unmarshal wrapped msg, which might contain context
305+
var wmsg WrappedMsg
306+
err = msg.Decode(&wmsg)
307+
if err != nil {
308+
log.Error(err.Error())
309+
return err
310+
}
311+
312+
ctx := context.Background()
313+
314+
// if tracing is enabled and the context coming within the request is
315+
// not empty, try to unmarshal it
316+
if tracing.Enabled && len(wmsg.Context) > 0 {
317+
var sctx opentracing.SpanContext
318+
319+
tracer := opentracing.GlobalTracer()
320+
sctx, err = tracer.Extract(
321+
opentracing.Binary,
322+
bytes.NewReader(wmsg.Context))
323+
if err != nil {
324+
log.Error(err.Error())
325+
return err
326+
}
327+
328+
ctx = spancontext.WithContext(ctx, sctx)
329+
}
330+
258331
val, ok := p.spec.NewMsg(msg.Code)
259332
if !ok {
260333
return errorf(ErrInvalidMsgCode, "%v", msg.Code)
261334
}
262-
if err := msg.Decode(val); err != nil {
335+
if err := rlp.DecodeBytes(wmsg.Payload, val); err != nil {
263336
return errorf(ErrDecode, "<= %v: %v", msg, err)
264337
}
265338

@@ -268,7 +341,7 @@ func (p *Peer) handleIncoming(handle func(msg interface{}) error) error {
268341
// which the handler is supposed to cast to the appropriate type
269342
// it is entirely safe not to check the cast in the handler since the handler is
270343
// chosen based on the proper type in the first place
271-
if err := handle(val); err != nil {
344+
if err := handle(ctx, val); err != nil {
272345
return errorf(ErrHandler, "(msg code %v): %v", msg.Code, err)
273346
}
274347
return nil
@@ -288,14 +361,14 @@ func (p *Peer) Handshake(ctx context.Context, hs interface{}, verify func(interf
288361
return nil, errorf(ErrHandshake, "unknown handshake message type: %T", hs)
289362
}
290363
errc := make(chan error, 2)
291-
handle := func(msg interface{}) error {
364+
handle := func(ctx context.Context, msg interface{}) error {
292365
rhs = msg
293366
if verify != nil {
294367
return verify(rhs)
295368
}
296369
return nil
297370
}
298-
send := func() { errc <- p.Send(hs) }
371+
send := func() { errc <- p.Send(ctx, hs) }
299372
receive := func() { errc <- p.handleIncoming(handle) }
300373

301374
go func() {

‎p2p/protocols/protocol_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func newProtocol(pp *p2ptest.TestPeerPool) func(*p2p.Peer, p2p.MsgReadWriter) er
104104
return fmt.Errorf("handshake mismatch remote %v > local %v", rmhs.C, lhs.C)
105105
}
106106

107-
handle := func(msg interface{}) error {
107+
handle := func(ctx context.Context, msg interface{}) error {
108108
switch msg := msg.(type) {
109109

110110
case *protoHandshake:
@@ -116,7 +116,7 @@ func newProtocol(pp *p2ptest.TestPeerPool) func(*p2p.Peer, p2p.MsgReadWriter) er
116116
return fmt.Errorf("handshake mismatch remote %v > local %v", rhs.C, lhs.C)
117117
}
118118
lhs.C += rhs.C
119-
return peer.Send(lhs)
119+
return peer.Send(ctx, lhs)
120120

121121
case *kill:
122122
// demonstrates use of peerPool, killing another peer connection as a response to a message

‎p2p/testing/protocoltester.go‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,8 @@ func (m *mockNode) Run(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
180180
for {
181181
select {
182182
case trig := <-m.trigger:
183-
m.err <- p2p.Send(rw, trig.Code, trig.Msg)
183+
wmsg := Wrap(trig.Msg)
184+
m.err <- p2p.Send(rw, trig.Code, wmsg)
184185
case exps := <-m.expect:
185186
m.err <- expectMsgs(rw, exps)
186187
case <-m.stop:
@@ -220,7 +221,7 @@ func expectMsgs(rw p2p.MsgReadWriter, exps []Expect) error {
220221
}
221222
var found bool
222223
for i, exp := range exps {
223-
if exp.Code == msg.Code && bytes.Equal(actualContent, mustEncodeMsg(exp.Msg)) {
224+
if exp.Code == msg.Code && bytes.Equal(actualContent, mustEncodeMsg(Wrap(exp.Msg))) {
224225
if matched[i] {
225226
return fmt.Errorf("message #%d received two times", i)
226227
}
@@ -235,7 +236,7 @@ func expectMsgs(rw p2p.MsgReadWriter, exps []Expect) error {
235236
if matched[i] {
236237
continue
237238
}
238-
expected = append(expected, fmt.Sprintf("code %d payload %x", exp.Code, mustEncodeMsg(exp.Msg)))
239+
expected = append(expected, fmt.Sprintf("code %d payload %x", exp.Code, mustEncodeMsg(Wrap(exp.Msg))))
239240
}
240241
return fmt.Errorf("unexpected message code %d payload %x, expected %s", msg.Code, actualContent, strings.Join(expected, " or "))
241242
}
@@ -267,3 +268,17 @@ func mustEncodeMsg(msg interface{}) []byte {
267268
}
268269
return contentEnc
269270
}
271+
272+
type WrappedMsg struct {
273+
Context []byte
274+
Size uint32
275+
Payload []byte
276+
}
277+
278+
func Wrap(msg interface{}) interface{} {
279+
data, _ := rlp.EncodeToBytes(msg)
280+
return &WrappedMsg{
281+
Size: uint32(len(data)),
282+
Payload: data,
283+
}
284+
}

‎swarm/api/api.go‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,10 @@ import (
3737
"github.com/ethereum/go-ethereum/metrics"
3838
"github.com/ethereum/go-ethereum/swarm/log"
3939
"github.com/ethereum/go-ethereum/swarm/multihash"
40+
"github.com/ethereum/go-ethereum/swarm/spancontext"
4041
"github.com/ethereum/go-ethereum/swarm/storage"
4142
"github.com/ethereum/go-ethereum/swarm/storage/mru"
43+
opentracing "github.com/opentracing/opentracing-go"
4244
)
4345

4446
var (
@@ -263,6 +265,12 @@ func (a *API) Resolve(ctx context.Context, uri *URI) (storage.Address, error) {
263265
apiResolveCount.Inc(1)
264266
log.Trace("resolving", "uri", uri.Addr)
265267

268+
var sp opentracing.Span
269+
ctx, sp = spancontext.StartSpan(
270+
ctx,
271+
"api.resolve")
272+
defer sp.Finish()
273+
266274
// if the URI is immutable, check if the address looks like a hash
267275
if uri.Immutable() {
268276
key := uri.Address()
@@ -347,7 +355,7 @@ func (a *API) Get(ctx context.Context, manifestAddr storage.Address, path string
347355
log.Trace("resource type", "key", manifestAddr, "hash", entry.Hash)
348356
ctx, cancel := context.WithCancel(context.Background())
349357
defer cancel()
350-
rsrc, err := a.resource.Load(storage.Address(common.FromHex(entry.Hash)))
358+
rsrc, err := a.resource.Load(ctx, storage.Address(common.FromHex(entry.Hash)))
351359
if err != nil {
352360
apiGetNotFound.Inc(1)
353361
status = http.StatusNotFound
@@ -486,7 +494,7 @@ func (a *API) GetDirectoryTar(ctx context.Context, uri *URI) (io.ReadCloser, err
486494

487495
// retrieve the entry's key and size
488496
reader, _ := a.Retrieve(ctx, storage.Address(common.Hex2Bytes(entry.Hash)))
489-
size, err := reader.Size(nil)
497+
size, err := reader.Size(ctx, nil)
490498
if err != nil {
491499
return err
492500
}
@@ -883,7 +891,7 @@ func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver
883891
// ResourceLookup Looks up mutable resource updates at specific periods and versions
884892
func (a *API) ResourceLookup(ctx context.Context, addr storage.Address, period uint32, version uint32, maxLookup *mru.LookupParams) (string, []byte, error) {
885893
var err error
886-
rsrc, err := a.resource.Load(addr)
894+
rsrc, err := a.resource.Load(ctx, addr)
887895
if err != nil {
888896
return "", nil, err
889897
}

‎swarm/api/api_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ func testGet(t *testing.T, api *API, bzzhash, path string) *testResponse {
9090
t.Fatalf("unexpected error: %v", err)
9191
}
9292
quitC := make(chan bool)
93-
size, err := reader.Size(quitC)
93+
size, err := reader.Size(context.TODO(), quitC)
9494
if err != nil {
9595
t.Fatalf("unexpected error: %v", err)
9696
}

‎swarm/api/filesystem.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ func retrieveToFile(quitC chan bool, fileStore *storage.FileStore, addr storage.
277277
}
278278
reader, _ := fileStore.Retrieve(context.TODO(), addr)
279279
writer := bufio.NewWriter(f)
280-
size, err := reader.Size(quitC)
280+
size, err := reader.Size(context.TODO(), quitC)
281281
if err != nil {
282282
return err
283283
}

0 commit comments

Comments
 (0)