-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
498 lines (432 loc) · 10.7 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path"
"strconv"
"sync"
"syscall"
"time"
ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
manet "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr-net"
serial "github.com/ipfs/go-ipfs/repo/fsrepo/serialize"
)
// GetNumNodes returns the number of testbed nodes configured in the testbed directory
func GetNumNodes() int {
for i := 0; i < 2000; i++ {
_, err := os.Stat(IpfsDirN(i))
if os.IsNotExist(err) {
return i
}
}
panic("i dont know whats going on")
}
func TestBedDir() string {
tbd := os.Getenv("IPTB_ROOT")
if len(tbd) != 0 {
return tbd
}
home := os.Getenv("HOME")
if len(home) == 0 {
panic("could not find home")
}
return path.Join(home, "testbed")
}
func IpfsDirN(n int) string {
return path.Join(TestBedDir(), fmt.Sprint(n))
}
func YesNoPrompt(prompt string) bool {
var s string
for {
fmt.Println(prompt)
fmt.Scanf("%s", &s)
switch s {
case "y", "Y":
return true
case "n", "N":
return false
}
fmt.Println("Please press either 'y' or 'n'")
}
}
type initCfg struct {
Count int
Force bool
Bootstrap string
PortStart int
}
func (c *initCfg) swarmAddrForPeer(i int) string {
return fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", c.PortStart+i)
}
func (c *initCfg) apiAddrForPeer(i int) string {
return fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", c.PortStart+1000+i)
}
func IpfsInit(cfg *initCfg) error {
p := IpfsDirN(0)
if _, err := os.Stat(p); !os.IsNotExist(err) {
if !cfg.Force && !YesNoPrompt("testbed nodes already exist, overwrite? [y/n]") {
return nil
}
err := os.RemoveAll(TestBedDir())
if err != nil {
return err
}
}
wait := sync.WaitGroup{}
for i := 0; i < cfg.Count; i++ {
wait.Add(1)
go func(v int) {
defer wait.Done()
dir := IpfsDirN(v)
err := os.MkdirAll(dir, 0777)
if err != nil {
log.Println("ERROR: ", err)
return
}
cmd := exec.Command("ipfs", "init", "-b=1024")
cmd.Env = append(cmd.Env, "IPFS_PATH="+dir)
out, err := cmd.CombinedOutput()
if err != nil {
log.Println("ERROR: ", err)
log.Println(string(out))
}
}(i)
}
wait.Wait()
// Now setup bootstrapping
switch cfg.Bootstrap {
case "star":
err := starBootstrap(cfg)
if err != nil {
return err
}
case "none":
err := clearBootstrapping(cfg)
if err != nil {
return err
}
default:
return fmt.Errorf("unrecognized bootstrapping option: %s", cfg.Bootstrap)
}
return nil
}
func starBootstrap(icfg *initCfg) error {
// '0' node is the bootstrap node
cfgpath := path.Join(IpfsDirN(0), "config")
bcfg, err := serial.Load(cfgpath)
if err != nil {
return err
}
bcfg.Bootstrap = nil
bcfg.Addresses.Swarm = []string{icfg.swarmAddrForPeer(0)}
bcfg.Addresses.API = icfg.apiAddrForPeer(0)
bcfg.Addresses.Gateway = ""
err = serial.WriteConfigFile(cfgpath, bcfg)
if err != nil {
return err
}
for i := 1; i < icfg.Count; i++ {
cfgpath := path.Join(IpfsDirN(i), "config")
cfg, err := serial.Load(cfgpath)
if err != nil {
return err
}
cfg.Bootstrap = []string{fmt.Sprintf("%s/ipfs/%s", bcfg.Addresses.Swarm[0], bcfg.Identity.PeerID)}
cfg.Addresses.Gateway = ""
cfg.Addresses.Swarm = []string{
icfg.swarmAddrForPeer(i),
}
cfg.Addresses.API = icfg.apiAddrForPeer(i)
err = serial.WriteConfigFile(cfgpath, cfg)
if err != nil {
return err
}
}
return nil
}
func clearBootstrapping(icfg *initCfg) error {
for i := 0; i < icfg.Count; i++ {
cfgpath := path.Join(IpfsDirN(i), "config")
cfg, err := serial.Load(cfgpath)
if err != nil {
return err
}
cfg.Bootstrap = nil
cfg.Addresses.Gateway = ""
cfg.Addresses.Swarm = []string{icfg.swarmAddrForPeer(i)}
cfg.Addresses.API = icfg.apiAddrForPeer(i)
err = serial.WriteConfigFile(cfgpath, cfg)
if err != nil {
return err
}
}
return nil
}
func IpfsPidOf(n int) (int, error) {
dir := IpfsDirN(n)
b, err := ioutil.ReadFile(path.Join(dir, "daemon.pid"))
if err != nil {
return -1, err
}
return strconv.Atoi(string(b))
}
func IpfsKill() error {
n := GetNumNodes()
for i := 0; i < n; i++ {
pid, err := IpfsPidOf(i)
if err != nil {
fmt.Printf("error killing daemon %d: %s\n", i, err)
continue
}
p, err := os.FindProcess(pid)
if err != nil {
fmt.Printf("error killing daemon %d: %s\n", i, err)
continue
}
err = p.Kill()
if err != nil {
fmt.Printf("error killing daemon %d: %s\n", i, err)
continue
}
p.Wait()
err = os.Remove(path.Join(IpfsDirN(i), "daemon.pid"))
if err != nil {
fmt.Printf("error removing pid file for daemon %d: %s\n", i, err)
continue
}
}
return nil
}
func IpfsStart(waitall bool) error {
var addrs []string
n := GetNumNodes()
for i := 0; i < n; i++ {
dir := IpfsDirN(i)
cmd := exec.Command("ipfs", "daemon")
cmd.Dir = dir
cmd.Env = []string{"IPFS_PATH=" + dir}
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
stdout, err := os.Create(path.Join(dir, "daemon.stdout"))
if err != nil {
return err
}
stderr, err := os.Create(path.Join(dir, "daemon.stderr"))
if err != nil {
return err
}
cmd.Stdout = stdout
cmd.Stderr = stderr
err = cmd.Start()
if err != nil {
return err
}
pid := cmd.Process.Pid
fmt.Printf("Started daemon %d, pid = %d\n", i, pid)
err = ioutil.WriteFile(path.Join(dir, "daemon.pid"), []byte(fmt.Sprint(pid)), 0666)
if err != nil {
return err
}
// Make sure node 0 is up before starting the rest so
// bootstrapping works properly
if i == 0 || waitall {
cfg, err := serial.Load(path.Join(IpfsDirN(i), "config"))
if err != nil {
return err
}
maddr := ma.StringCast(cfg.Addresses.API)
_, addr, err := manet.DialArgs(maddr)
if err != nil {
return err
}
addrs = append(addrs, addr)
err = waitOnAPI(cfg.Identity.PeerID, addr)
if err != nil {
return err
}
}
}
if waitall {
for i := 0; i < n; i++ {
err := waitOnSwarmPeers(addrs[i])
if err != nil {
return err
}
}
}
return nil
}
func waitOnAPI(peerid, addr string) error {
for i := 0; i < 50; i++ {
resp, err := http.Get("http://" + addr + "/api/v0/id")
if err == nil {
out := make(map[string]interface{})
err := json.NewDecoder(resp.Body).Decode(&out)
if err != nil {
return fmt.Errorf("liveness check failed: %s", err)
}
id, ok := out["ID"]
if !ok {
return fmt.Errorf("liveness check failed: ID field not present in output")
}
idstr := id.(string)
if idstr != peerid {
return fmt.Errorf("liveness check failed: unexpected peer at endpoint")
}
return nil
}
time.Sleep(time.Millisecond * 200)
}
return fmt.Errorf("node at %s failed to come online in given time period", addr)
}
func waitOnSwarmPeers(addr string) error {
for i := 0; i < 50; i++ {
resp, err := http.Get("http://" + addr + "/api/v0/swarm/peers")
if err == nil {
out := make(map[string]interface{})
err := json.NewDecoder(resp.Body).Decode(&out)
if err != nil {
return fmt.Errorf("liveness check failed: %s", err)
}
peers := out["Strings"].([]interface{})
if len(peers) == 0 {
time.Sleep(time.Millisecond * 200)
continue
}
return nil
}
time.Sleep(time.Millisecond * 200)
}
return fmt.Errorf("node at %s failed to bootstrap in given time period", addr)
}
// GetPeerID reads the config of node 'n' and returns its peer ID
func GetPeerID(n int) (string, error) {
cfg, err := serial.Load(path.Join(IpfsDirN(n), "config"))
if err != nil {
return "", err
}
return cfg.Identity.PeerID, nil
}
// IpfsShell sets up environment variables for a new shell to more easily
// control the given daemon
func IpfsShell(n int) error {
shell := os.Getenv("SHELL")
if shell == "" {
return fmt.Errorf("couldnt find shell!")
}
dir := IpfsDirN(n)
nenvs := []string{"IPFS_PATH=" + dir}
nnodes := GetNumNodes()
for i := 0; i < nnodes; i++ {
peerid, err := GetPeerID(i)
if err != nil {
return err
}
nenvs = append(nenvs, fmt.Sprintf("NODE%d=%s", i, peerid))
}
nenvs = append(os.Environ(), nenvs...)
return syscall.Exec(shell, []string{shell}, nenvs)
}
func GetAttr(attr string, node int) (string, error) {
switch attr {
case "id":
return GetPeerID(node)
default:
return "", errors.New("unrecognized attribute")
}
}
var helptext = `Ipfs Testbed
Commands:
init
creates and initializes 'n' repos
Options:
-n=[number of nodes]
-f - force overwriting of existing nodes
-bootstrap - select bootstrapping style for cluster
choices: star, none
start
starts up all testbed nodes
Options:
-wait - wait until daemons are fully initialized
stop
kills all testbed nodes
restart
kills, then restarts all testbed nodes
shell [n]
execs your shell with environment variables set as follows:
IPFS_PATH - set to testbed node n's IPFS_PATH
NODE[x] - set to the peer ID of node x
get [attribute] [node]
get an attribute of the given node
currently supports: "id"
Env Vars:
IPTB_ROOT:
Used to specify the directory that nodes will be created in.
`
func handleErr(s string, err error) {
if err != nil {
fmt.Fprintln(os.Stderr, s, err)
os.Exit(1)
}
}
func main() {
cfg := new(initCfg)
flag.IntVar(&cfg.Count, "n", 0, "number of ipfs nodes to initialize")
flag.IntVar(&cfg.PortStart, "p", 4002, "port to start allocations from")
flag.BoolVar(&cfg.Force, "f", false, "force initialization (overwrite existing configs)")
flag.StringVar(&cfg.Bootstrap, "bootstrap", "star", "select bootstrapping style for cluster")
wait := flag.Bool("wait", false, "wait for nodes to come fully online before exiting")
flag.Usage = func() {
fmt.Println(helptext)
}
flag.Parse()
switch flag.Arg(0) {
case "init":
if cfg.Count == 0 {
fmt.Printf("please specify number of nodes: '%s -n=10 init'\n", os.Args[0])
os.Exit(1)
}
err := IpfsInit(cfg)
handleErr("ipfs init err: ", err)
case "start":
err := IpfsStart(*wait)
handleErr("ipfs start err: ", err)
case "stop", "kill":
err := IpfsKill()
handleErr("ipfs kill err: ", err)
case "restart":
err := IpfsKill()
handleErr("ipfs kill err: ", err)
err = IpfsStart(*wait)
handleErr("ipfs start err: ", err)
case "shell":
if len(flag.Args()) < 2 {
fmt.Println("please specify which node you want a shell for")
os.Exit(1)
}
n, err := strconv.Atoi(flag.Arg(1))
handleErr("parse err: ", err)
err = IpfsShell(n)
handleErr("ipfs shell err: ", err)
case "get":
if len(flag.Args()) < 3 {
fmt.Println("iptb get [attr] [node]")
os.Exit(1)
}
attr := flag.Arg(1)
num, err := strconv.Atoi(flag.Arg(2))
handleErr("error parsing node number: ", err)
val, err := GetAttr(attr, num)
handleErr("error getting attribute: ", err)
fmt.Println(val)
default:
flag.Usage()
os.Exit(1)
}
}