/
hub.go
213 lines (183 loc) · 4.99 KB
/
hub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main
import (
"context"
"encoding/csv"
"encoding/hex"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/libp2p/go-libp2p-core/routing"
kbucket "github.com/libp2p/go-libp2p-kbucket"
"github.com/libp2p/go-libp2p-core/protocol"
u "github.com/ipfs/go-ipfs-util"
"go.uber.org/atomic"
log "github.com/sirupsen/logrus"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multiaddr"
)
type EventHub struct {
mutex sync.RWMutex
events map[peer.ID][]Event
relevant sync.Map
stopped *atomic.Bool
startTime time.Time
stopTime time.Time
}
func NewEventHub() *EventHub {
return &EventHub{
events: map[peer.ID][]Event{},
relevant: sync.Map{},
stopped: atomic.NewBool(false),
}
}
func (eh *EventHub) MarkAsRelevant(peerID peer.ID) {
eh.relevant.Store(peerID, struct{}{})
}
func (eh *EventHub) PushEvent(event Event) {
if eh == nil || eh.stopped.Load() {
return
}
eh.mutex.Lock()
defer eh.mutex.Unlock()
events, found := eh.events[event.PeerID()]
if !found {
eh.events[event.PeerID()] = []Event{}
}
// log.WithField("peerID", event.PeerID().Pretty()[:16]).
// WithField("event", fmt.Sprintf("%T", event)).
// Infoln("Pushing Event")
eh.events[event.PeerID()] = append(events, event)
}
func (eh *EventHub) Start(ctx context.Context, h host.Host) context.Context {
eh.startTime = time.Now()
h.Network().Notify(eh)
ctx, queryEvents := routing.RegisterForQueryEvents(ctx)
go eh.handleQueryEvents(queryEvents)
return ctx
}
func (eh *EventHub) handleQueryEvents(queryEvents <-chan *routing.QueryEvent) {
for event := range queryEvents {
eh.MarkAsRelevant(event.ID)
}
}
func (eh *EventHub) Stop(h host.Host) {
eh.stopped.Store(true)
eh.stopTime = time.Now()
eh.mutex.Lock()
defer eh.mutex.Unlock()
h.Network().StopNotify(eh)
// Since we collected all Dials and whatnot we filter the events
// for peer IDs that were used for getting the closest peers in
// the call to dht.Provide. Those relevant peers are marked as
// relevant in the handleQueryEvents method.
relevant := map[peer.ID][]Event{}
eh.relevant.Range(func(key, value interface{}) bool {
relevant[key.(peer.ID)] = eh.events[key.(peer.ID)]
return true
})
eh.events = relevant
}
func (eh *EventHub) Listen(n network.Network, multiaddr multiaddr.Multiaddr) {
}
func (eh *EventHub) ListenClose(n network.Network, multiaddr multiaddr.Multiaddr) {
}
func (eh *EventHub) Connected(n network.Network, conn network.Conn) {
eh.PushEvent(&ConnectedEvent{
BaseEvent: BaseEvent{
ID: conn.RemotePeer(),
Time: time.Now(),
},
})
}
func (eh *EventHub) Disconnected(n network.Network, conn network.Conn) {
eh.PushEvent(&DisconnectedEvent{
BaseEvent: BaseEvent{
ID: conn.RemotePeer(),
Time: time.Now(),
},
})
}
func (eh *EventHub) OpenedStream(n network.Network, stream network.Stream) {
eh.PushEvent(&OpenedStream{
BaseEvent: BaseEvent{
ID: stream.Conn().RemotePeer(),
Time: time.Now(),
},
Protocol: stream.Protocol(),
})
}
func (eh *EventHub) ClosedStream(n network.Network, stream network.Stream) {
eh.PushEvent(&ClosedStream{
BaseEvent: BaseEvent{
ID: stream.Conn().RemotePeer(),
Time: time.Now(),
},
Protocol: stream.Protocol(),
})
}
func (eh *EventHub) Serialize(content *Content) {
f, err := os.Create("events.csv")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
// Write header
w.Write([]string{
"peer_id",
"distance",
"time",
"type",
"has_error",
"error",
"extra",
})
for peerID, events := range eh.events {
distance := u.XOR(kbucket.ConvertPeerID(peerID), kbucket.ConvertKey(string(content.mhash)))
for _, evt := range events {
extra := ""
switch event := evt.(type) {
case *DialStart:
extra = event.Maddr.String()
case *DialEnd:
extra = event.Maddr.String()
case *OpenStreamStart:
extra = strings.Join(protocol.ConvertToStrings(event.Protocols), ",")
case *OpenStreamEnd:
extra = strings.Join(protocol.ConvertToStrings(event.Protocols), ",")
case *OpenedStream:
extra = protocol.ConvertToStrings([]protocol.ID{event.Protocol})[0]
case *ClosedStream:
extra = protocol.ConvertToStrings([]protocol.ID{event.Protocol})[0]
case *SendRequestStart:
extra = event.Request.Type.String()
case *SendRequestEnd:
if event.Err == nil {
extra = event.Response.Type.String()
}
case *SendMessageStart:
extra = event.Message.Type.String()
case *DiscoveredPeer:
extra = hex.EncodeToString(u.XOR(kbucket.ConvertPeerID(event.Discovered), kbucket.ConvertKey(string(content.mhash))))
}
errorStr := ""
if evt.Error() != nil {
errorStr = strings.ReplaceAll(evt.Error().Error(), "\n", " ")
}
w.Write([]string{
peerID.Pretty(),
hex.EncodeToString(distance),
fmt.Sprintf("%.6f", evt.TimeStamp().Sub(eh.startTime).Seconds()),
fmt.Sprintf("%T", evt),
fmt.Sprintf("%t", evt.Error() != nil),
errorStr,
extra,
})
}
}
}