forked from datahop/libp2p-das
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
239 lines (199 loc) · 5.77 KB
/
main.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package main
import (
"context"
"encoding/csv"
"flag"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/protocol"
"github.com/multiformats/go-multiaddr"
)
type Config struct {
Port int
ProtocolID string
Rendezvous string
Seed int64
DiscoveryPeers addrList
Debug bool
Duration int
}
type Stats struct {
TotalPutMessages int
TotalGetMessages int
TotalFailedGets int
TotalSuccessGets int
// Array of latencies for puts
PutLatencies []time.Duration
// Array of latencies for gets
GetLatencies []time.Duration
// Array of hops for gets
GetHops []int
}
func colorize(word string, colorName string) string {
var c *color.Color
switch colorName {
case "red":
c = color.New(color.FgRed)
case "green":
c = color.New(color.FgGreen)
case "yellow":
c = color.New(color.FgYellow)
case "blue":
c = color.New(color.FgBlue)
default:
c = color.New(color.Reset)
}
return c.Sprint(word)
}
func main() {
config := Config{}
stats := &Stats{}
var debugMode bool = false
flag.StringVar(&config.Rendezvous, "rendezvous", "/echo", "")
flag.Int64Var(&config.Seed, "seed", 0, "Seed value for generating a PeerID, 0 is random")
flag.Var(&config.DiscoveryPeers, "peer", "Peer multiaddress for peer discovery")
flag.StringVar(&config.ProtocolID, "protocolid", "/p2p/rpc", "")
flag.IntVar(&config.Port, "port", 0, "")
flag.IntVar(&config.Duration, "duration", 15, "How long to run the test for (in seconds).")
flag.BoolVar(&debugMode, "debug", false, "Enable debug mode - see more messages about what is happening.")
flag.Parse()
if debugMode {
log.Printf("Running libp2p-das with the following config:\n")
log.Printf("\tRendezvous: %s\n", config.Rendezvous)
log.Printf("\tSeed: %d\n", config.Seed)
log.Printf("\tDiscoveryPeers: %s\n", config.DiscoveryPeers)
log.Printf("\tProtocolID: %s\n", config.ProtocolID)
log.Printf("\tPort: %d\n\n", config.Port)
}
ctx, cancel := context.WithCancel(context.Background())
h, err := NewHost(ctx, config.Seed, config.Port)
if err != nil {
fmt.Printf("NewHost() failed\n")
log.Fatal(err)
}
log.Print(colorize("Created Host ID: "+h.ID()[0:7].Pretty()+"\n", "white"))
// if debugMode {
// log.Printf("Created new host:\n\tID: [%s] \n\tSeed: [%d] \n\tPort: [%d]", h.ID().Pretty(), config.Seed, config.Port)
// }
log.Printf("Connect to me on:")
for _, addr := range h.Addrs() {
log.Printf(" %s/p2p/%s", addr, h.ID().Pretty())
}
dht, err := NewDHT(ctx, h, config.DiscoveryPeers)
if err != nil {
log.Printf("Error creating dht\n")
log.Fatal(err)
}
go Discover(ctx, h, dht, config.Rendezvous)
service := NewService(h, protocol.ID(config.ProtocolID))
err = service.SetupRPC()
if err != nil {
log.Fatal(err)
}
// Create a timer that runs for x seconds
timer := time.NewTimer(time.Duration(config.Duration) * time.Second)
// Start the messaging service in a separate goroutine
go func() {
service.StartMessaging(dht, stats, ctx)
}()
// Wait for the timer to expire
<-timer.C
log.Printf("Timer expired, shutting down...\n")
if err := writeTotalStatsToFile(stats, h); err != nil {
log.Fatal(err)
}
log.Printf("[%s] Total Stats written to %s\n", h.ID()[0:5].Pretty(), h.ID()[0:10].Pretty()+"_total_stats.csv")
if err := writeLatencyStatsToFile(stats, h); err != nil {
log.Fatal(err)
}
log.Printf("[%s] Latencies written to %s\n", h.ID()[0:5].Pretty(), h.ID()[0:10].Pretty()+"_latency_stats.csv")
// Cancel the context and exit
cancel()
if err := h.Close(); err != nil {
panic(err)
}
os.Exit(0)
}
func writeTotalStatsToFile(stats *Stats, h host.Host) error {
// Write total stats to CSV file
f, err := os.Create(h.ID()[0:10].Pretty() + "_total_stats.csv")
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"Total PUT messages", "Total GET messages", "Total failed GETs", "Total successful GETs"}
rows := [][]string{
{strconv.Itoa(stats.TotalPutMessages), strconv.Itoa(stats.TotalGetMessages), strconv.Itoa(stats.TotalFailedGets), strconv.Itoa(stats.TotalSuccessGets)},
}
// Write headers and rows to CSV file
w.Write(headers)
w.WriteAll(rows)
if err := w.Error(); err != nil {
return err
}
return nil
}
func writeLatencyStatsToFile(stats *Stats, h host.Host) error {
// Convert latencies and hops to rows
var latencyRows [][]string
for i := 0; i < len(stats.PutLatencies) || i < len(stats.GetLatencies) || i < len(stats.GetHops); i++ {
var row []string
if i < len(stats.PutLatencies) {
row = append(row, strconv.FormatInt(stats.PutLatencies[i].Microseconds(), 10))
} else {
row = append(row, "")
}
if i < len(stats.GetLatencies) {
row = append(row, strconv.FormatInt(stats.GetLatencies[i].Microseconds(), 10))
} else {
row = append(row, "")
}
if i < len(stats.GetHops) {
row = append(row, strconv.Itoa(stats.GetHops[i]))
} else {
row = append(row, "")
}
latencyRows = append(latencyRows, row)
}
// Write latency stats to CSV file
f, err := os.Create(h.ID()[0:10].Pretty() + "_latency_stats.csv")
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
headers := []string{"PUT latencies (us)", "GET latencies (us)", "GET hops"}
rows := latencyRows
// Write headers and rows to CSV file
w.Write(headers)
w.WriteAll(rows)
if err := w.Error(); err != nil {
return err
}
return nil
}
type addrList []multiaddr.Multiaddr
func (al *addrList) String() string {
strs := make([]string, len(*al))
for i, addr := range *al {
strs[i] = addr.String()
}
return strings.Join(strs, ",")
}
func (al *addrList) Set(value string) error {
addr, err := multiaddr.NewMultiaddr(value)
if err != nil {
return err
}
*al = append(*al, addr)
return nil
}