forked from ipfs/ipfs-update
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
490 lines (406 loc) · 10.2 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
package main
import (
"archive/zip"
"bufio"
"fmt"
cli "github.com/codegangsta/cli"
api "github.com/ipfs/go-ipfs-api"
. "github.com/whyrusleeping/stump"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
var gateway = "https://ipfs.io"
func httpFetch(url string) (io.ReadCloser, error) {
VLog("fetching url: %s", url)
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("http.Get error: %s", err)
}
if resp.StatusCode >= 400 {
Error("fetching resource: %s", resp.Status)
mes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading error body: %s", err)
}
return nil, fmt.Errorf("%s: %s", resp.Status, string(mes))
}
return resp.Body, nil
}
func Fetch(ipfspath string) (io.ReadCloser, error) {
sh := api.NewShell("http://localhost:5001")
if sh.IsUp() {
return sh.Cat(ipfspath)
}
return httpFetch(gateway + ipfspath)
}
// This function is needed because os.Rename doesnt work across filesystem
// boundaries.
func CopyTo(src, dest string) error {
VLog(" - copying %s to %s", src, dest)
fi, err := os.Open(src)
if err != nil {
return err
}
defer fi.Close()
trgt, err := os.Create(dest)
if err != nil {
return err
}
defer trgt.Close()
_, err = io.Copy(trgt, fi)
return err
}
func GetVersions(ipfspath string) ([]string, error) {
rc, err := Fetch(ipfspath + "/go-ipfs/versions")
if err != nil {
return nil, err
}
defer rc.Close()
var out []string
scan := bufio.NewScanner(rc)
for scan.Scan() {
out = append(out, scan.Text())
}
return out, nil
}
func GetCurrentVersion() (string, error) {
// try checking a locally running daemon first
sh := api.NewShell("http://localhost:5001")
v, _, err := sh.Version()
if err == nil {
return v, nil
}
VLog("daemon check failed: %s", err)
// try running the ipfs binary in the users path
out, err := exec.Command("ipfs", "version", "-n").CombinedOutput()
if err != nil {
return "", fmt.Errorf("version check failed: %s - %s", string(out), err)
}
return string(out), nil
}
func GetLatestVersion(ipfspath string) (string, error) {
vs, err := GetVersions(ipfspath)
if err != nil {
return "", err
}
return vs[len(vs)-1], nil
}
func InstallVersion(root, v string) error {
Log("installing ipfs version %s", v)
tmpd, err := ioutil.TempDir("", "ipfs-update")
if err != nil {
return err
}
binpath := filepath.Join(tmpd, "ipfs-new")
Log("fetching %s binary...", v)
err = GetBinaryForVersion(root, v, binpath)
if err != nil {
return err
}
Log("binary downloaded, verifying...")
err = TestBinary(binpath, v)
if err != nil {
return err
}
Log("success! stashing old binary")
oldpath, err := StashOldBinary()
if err != nil {
return err
}
Log("installing new binary to %s", oldpath)
err = InstallBinaryTo(binpath, oldpath)
if err != nil {
// in case of error here, replace old binary
Error("Install failed: ", err)
revertOldBinary(oldpath)
return err
}
err = CheckMigration()
if err != nil {
Error("Migration Failed: ", err)
revertOldBinary(oldpath)
return err
}
return nil
}
func CheckMigration() error {
Log("checking if repo migration is needed...")
p := ipfsDir()
oldverB, err := ioutil.ReadFile(filepath.Join(p, "version"))
if err != nil {
return err
}
oldver := strings.Trim(string(oldverB), "\n \t")
VLog(" - old repo version is", oldver)
nbinver, err := runCmd("", "ipfs", "version", "--repo")
if err != nil {
Log("Failed to check new binary repo version.")
VLog("Reason: ", err)
Log("This means you may have to manually run the migration")
Log("You will be prompted to do so upon starting the ipfs daemon if necessary")
return nil
}
VLog(" - repo version of new binary is ", nbinver)
if oldver != nbinver {
Log("MIGRATION NEEDED!")
return nil
}
VLog(" - no migration required")
return nil
}
func RunMigration(oldv, newv string) error {
migrateBin := "fs-repo-migrations"
_, err := exec.LookPath(migrateBin)
if err != nil {
Error("could not find migrations binary: ", err)
return err
}
cmd := exec.Command(migrateBin, "-to", newv, "-y")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
Log("running migration: '%s -to %s -y'", migrateBin, newv)
err = cmd.Run()
if err != nil {
return fmt.Errorf("migration failed: %s", err)
}
Log("migration succeeded!")
return nil
}
func revertOldBinary(oldpath string) {
stashpath := filepath.Join(ipfsDir(), "old-bin", "ipfs-old")
rnerr := os.Rename(stashpath, oldpath)
if rnerr != nil {
Log("error replacing binary after install fail: ", rnerr)
Log("sorry :(")
Log("your old ipfs binary should still be located at: ", stashpath)
}
}
func InstallBinaryTo(nbin, nloc string) error {
err := CopyTo(nbin, nloc)
if err != nil {
return fmt.Errorf("error moving new binary into place: %s", err)
}
err = os.Chmod(nloc, 0755)
if err != nil {
return fmt.Errorf("error setting permissions on new binary: %s", err)
}
return nil
}
func ipfsDir() string {
def := filepath.Join(os.Getenv("HOME"), ".ipfs")
ipfs_path := os.Getenv("IPFS_PATH")
if ipfs_path != "" {
def = ipfs_path
}
return def
}
// StashOldBinary moves the existing ipfs binary to a backup directory
// and returns the path to the original location of the old binary
func StashOldBinary() (string, error) {
loc, err := exec.LookPath("ipfs")
if err != nil {
return "", fmt.Errorf("could not find old binary: %s", err)
}
ipfsdir := ipfsDir()
olddir := filepath.Join(ipfsdir, "old-bin")
npath := filepath.Join(olddir, "ipfs-old")
pathpath := filepath.Join(olddir, "path-old")
err = os.MkdirAll(olddir, 0700)
if err != nil {
return "", fmt.Errorf("could not create dir to backup old binary: %s", err)
}
// write the old path of the binary to the backup dir
err = ioutil.WriteFile(pathpath, []byte(loc), 0644)
if err != nil {
return "", fmt.Errorf("couldnt stash path: ", err)
}
VLog(" - moving %s to %s", loc, npath)
err = os.Rename(loc, npath)
if err != nil {
return "", fmt.Errorf("could not move old binary: %s", err)
}
return loc, nil
}
func GetBinaryForVersion(root, vers, target string) error {
dir, err := ioutil.TempDir("", "ipfs-update")
if err != nil {
return err
}
finame := fmt.Sprintf("go-ipfs_%s_%s-%s.zip", vers, runtime.GOOS, runtime.GOARCH)
ipfspath := fmt.Sprintf("%s/go-ipfs/%s/%s", root, vers, finame)
data, err := Fetch(ipfspath)
if err != nil {
return err
}
zippath := filepath.Join(dir, finame)
fi, err := os.Create(zippath)
if err != nil {
return err
}
_, err = io.Copy(fi, data)
if err != nil {
return err
}
fi.Close()
zipr, err := zip.OpenReader(zippath)
if err != nil {
return fmt.Errorf("error opening zipreader: %s", err)
}
defer zipr.Close()
var bin io.ReadCloser
for _, fis := range zipr.File {
if fis.Name == "ipfs/ipfs" {
rc, err := fis.Open()
if err != nil {
return fmt.Errorf("error extracting binary from archive: %s", err)
}
bin = rc
}
}
if bin == nil {
return fmt.Errorf("no ipfs binary found in downloaded archive")
}
binfi, err := os.Create(target)
if err != nil {
return fmt.Errorf("error opening tmp bin path '%s': %s", target, err)
}
defer binfi.Close()
_, err = io.Copy(binfi, bin)
if err != nil {
return err
}
return nil
}
func main() {
app := cli.NewApp()
app.Author = "whyrusleeping"
app.Usage = "update ipfs"
app.Version = "0.1.0"
basehash := "/ipfs/QmXUGEDqzHbeGAwj4w72uA9ZJ6iYEaMyfQuioLSLJvcQY6"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "verbose",
Usage: "print verbose output",
},
}
app.Before = func(c *cli.Context) error {
Verbose = c.Bool("verbose")
return nil
}
app.Commands = []cli.Command{
{
Name: "versions",
Usage: "print out all available versions",
Action: func(c *cli.Context) {
vs, err := GetVersions(basehash)
if err != nil {
fmt.Println("Failed to query versions: ", err)
return
}
for _, v := range vs {
fmt.Println(v)
}
},
},
{
Name: "version",
Usage: "print out currently installed version",
Action: func(c *cli.Context) {
v, err := GetCurrentVersion()
if err != nil {
fmt.Println("Failed to check local version: ", err)
return
}
fmt.Println(v)
},
},
{
Name: "install",
Usage: "install a version of ipfs",
Action: func(c *cli.Context) {
vers := c.Args().First()
if vers == "" {
fmt.Println("Please specify a version to install")
return
}
if vers == "latest" {
latest, err := GetLatestVersion(basehash)
if err != nil {
fmt.Println("error resolving 'latest': ", err)
return
}
vers = latest
}
err := InstallVersion(basehash, vers)
if err != nil {
fmt.Println(err)
return
}
},
},
{
Name: "revert",
Usage: "revert to previously installed version of ipfs",
Description: `revert will check if a previous update left a stashed
binary and overwrite the current ipfs binary with it.`,
Action: func(c *cli.Context) {
oldbinpath := filepath.Join(ipfsDir(), "old-bin", "ipfs-old")
_, err := os.Stat(oldbinpath)
if os.IsNotExist(err) {
fmt.Printf("No prior binary found at: %s\n", err)
return
}
oldpath, err := ioutil.ReadFile(filepath.Join(ipfsDir(), "old-bin", "path-old"))
if err != nil {
fmt.Println("Path for previous installation could not be read: ", err)
return
}
binpath := string(oldpath)
err = InstallBinaryTo(oldbinpath, binpath)
if err != nil {
Error("failed to move old binary: %s\n", oldbinpath)
Log("to path: %s\n%s\n", binpath, err)
return
}
},
},
{
Name: "fetch",
Usage: "fetch a given (default: latest) version of ipfs",
Action: func(c *cli.Context) {
vers := c.Args().First()
if vers == "" || vers == "latest" {
latest, err := GetLatestVersion(basehash)
if err != nil {
fmt.Println("error querying latest version: ", err)
return
}
vers = latest
}
output := "ipfs-" + vers
ofl := c.String("output")
if ofl != "" {
output = ofl
}
err := GetBinaryForVersion(basehash, vers, output)
if err != nil {
fmt.Println("Failed to fetch binary: ", err)
return
}
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "output",
Usage: "specify where to save the downloaded binary",
},
},
},
}
app.Run(os.Args)
}