main.go 17.1 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
// cmd/ipfs implements the primary CLI binary for ipfs
2 3 4
package main

import (
5
	"context"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
6
	"errors"
7 8
	"fmt"
	"io"
9
	"math/rand"
Jeromy's avatar
Jeromy committed
10 11
	"net"
	"net/url"
12
	"os"
Matt Bell's avatar
Matt Bell committed
13
	"os/signal"
14
	"path/filepath"
15
	"runtime/pprof"
16
	"strings"
17
	"sync"
18
	"syscall"
19
	"time"
20

21
	oldcmds "github.com/ipfs/go-ipfs/commands"
22
	core "github.com/ipfs/go-ipfs/core"
23
	coreCmds "github.com/ipfs/go-ipfs/core/commands"
24
	"github.com/ipfs/go-ipfs/plugin/loader"
25
	repo "github.com/ipfs/go-ipfs/repo"
26 27
	config "github.com/ipfs/go-ipfs/repo/config"
	fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
28

Steven Allen's avatar
Steven Allen committed
29 30
	u "gx/ipfs/QmPsAfmDBnZN3kZGSuNwvCNDZiHneERSKmRcFyG3UkvcT3/go-ipfs-util"
	manet "gx/ipfs/QmSGL5Uoa6gKHgBBwQG8u1CWKUC8ZnwaZiLgFVTFBR2bxr/go-multiaddr-net"
31
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
Steven Allen's avatar
Steven Allen committed
32
	loggables "gx/ipfs/QmSvcDkiRwB8LuMhUtnvhum2C851Mproo75ZDD19jx43tD/go-libp2p-loggables"
33 34 35 36
	"gx/ipfs/QmTwKPLyeRKuDawuy6CAn1kRj1FVoqBEM8sviAUWN7NW9K/go-ipfs-cmds"
	"gx/ipfs/QmTwKPLyeRKuDawuy6CAn1kRj1FVoqBEM8sviAUWN7NW9K/go-ipfs-cmds/cli"
	"gx/ipfs/QmTwKPLyeRKuDawuy6CAn1kRj1FVoqBEM8sviAUWN7NW9K/go-ipfs-cmds/http"
	"gx/ipfs/QmVD1W3MC8Hk1WZgFQPWWmBECJ3X72BgUYf9eCQ4PGzPps/go-ipfs-cmdkit"
Steven Allen's avatar
Steven Allen committed
37
	ma "gx/ipfs/QmW8s4zTsUoX1Q6CeYxVKPyqSKbF7H1YDUyTostBtZ8DaG/go-multiaddr"
38
	osh "gx/ipfs/QmXuBJ7DR6k3rmUEKtvVMhwjmXDuJgXXPUt4LQXKBMsU93/go-os-helper"
39 40
)

41
// log is the command logger
Jeromy's avatar
Jeromy committed
42
var log = logging.Logger("cmd/ipfs")
43

44
var errRequestCanceled = errors.New("request canceled")
45

46
const (
47 48 49
	EnvEnableProfiling = "IPFS_PROF"
	cpuProfile         = "ipfs.cpuprof"
	heapProfile        = "ipfs.memprof"
50
)
51

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52
type cmdInvocation struct {
53
	req  *cmds.Request
54
	node *core.IpfsNode
55
	ctx  *oldcmds.Context
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56 57
}

Jan Winkelmann's avatar
Jan Winkelmann committed
58 59 60 61 62 63
type exitErr int

func (e exitErr) Error() string {
	return fmt.Sprint("exit code", int(e))
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65
// main roadmap:
// - parse the commandline to get a cmdInvocation
66
// - if user requests help, print it and exit.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69
// - run the command invocation
// - output the response
// - if anything fails, print error, maybe with help
70
func main() {
71 72 73 74
	os.Exit(mainRet())
}

func mainRet() int {
75
	rand.Seed(time.Now().UnixNano())
76
	ctx := logging.ContextWithLoggable(context.Background(), loggables.Uuid("session"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78 79 80 81 82 83 84
	var err error

	// we'll call this local helper to output errors.
	// this is so we control how to print errors in one place.
	printErr := func(err error) {
		fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
	}

85 86 87
	stopFunc, err := profileIfEnabled()
	if err != nil {
		printErr(err)
88
		return 1
89 90 91
	}
	defer stopFunc() // to be executed as late as possible

Jan Winkelmann's avatar
Jan Winkelmann committed
92 93 94
	var invoc cmdInvocation
	defer invoc.close()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95 96
	// this is a local helper to print out help text.
	// there's some considerations that this makes easier.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
	printHelp := func(long bool, w io.Writer) {
Jan Winkelmann's avatar
Jan Winkelmann committed
98
		helpFunc := cli.ShortHelp
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99
		if long {
Jan Winkelmann's avatar
Jan Winkelmann committed
100
			helpFunc = cli.LongHelp
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101 102
		}

103 104 105 106 107 108
		var p []string
		if invoc.req != nil {
			p = invoc.req.Path
		}

		helpFunc("ipfs", Root, p, w)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110
	}

111 112
	// this is a message to tell the user how to get the help text
	printMetaHelp := func(w io.Writer) {
113
		cmdPath := strings.Join(invoc.req.Path, " ")
114 115 116
		fmt.Fprintf(w, "Use 'ipfs %s --help' for information about this command\n", cmdPath)
	}

Etienne Laurin's avatar
Etienne Laurin committed
117
	// Handle `ipfs help'
118 119 120
	if len(os.Args) == 2 {
		if os.Args[1] == "help" {
			printHelp(false, os.Stdout)
121
			return 0
122 123 124
		} else if os.Args[1] == "--version" {
			os.Args[1] = "version"
		}
Etienne Laurin's avatar
Etienne Laurin committed
125 126
	}

127 128 129
	intrh, ctx := invoc.SetupInterruptHandler(ctx)
	defer intrh.Close()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
	// parse the commandline into a command invocation
131
	parseErr := invoc.Parse(ctx, os.Args[1:])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133 134

	// BEFORE handling the parse error, if we have enough information
	// AND the user requested help, print it out and exit
135
	if invoc.req != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137 138
		longH, shortH, err := invoc.requestedHelp()
		if err != nil {
			printErr(err)
139
			return 1
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141
		}
		if longH || shortH {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142
			printHelp(longH, os.Stdout)
143
			return 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144 145 146
		}
	}

147
	// ok now handle parse error (which means cli input was wrong,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
	// e.g. incorrect number of args, or nonexistent subcommand)
149 150
	if parseErr != nil {
		printErr(parseErr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151 152

		// this was a user error, print help.
153
		if invoc.req != nil && invoc.req.Command != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
			// we need a newline space.
			fmt.Fprintf(os.Stderr, "\n")
156
			printHelp(false, os.Stderr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
		}
158
		return 1
Brian Tiger Chow's avatar
Brian Tiger Chow committed
159
	}
Matt Bell's avatar
Matt Bell committed
160

Etienne Laurin's avatar
Etienne Laurin committed
161 162 163
	// here we handle the cases where
	// - commands with no Run func are invoked directly.
	// - the main command is invoked.
164
	if invoc.req == nil || invoc.req.Command == nil || invoc.req.Command.Run == nil {
Etienne Laurin's avatar
Etienne Laurin committed
165
		printHelp(false, os.Stdout)
166
		return 0
Etienne Laurin's avatar
Etienne Laurin committed
167 168
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
	// ok, finally, run the command invocation.
Jan Winkelmann's avatar
Jan Winkelmann committed
170
	err = invoc.Run(ctx)
171
	if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
172 173 174 175
		if code, ok := err.(exitErr); ok {
			return int(code)
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176 177 178 179
		printErr(err)

		// if this error was a client error, print short help too.
		if isClientError(err) {
180
			printMetaHelp(os.Stderr)
181
		}
182
		return 1
Brian Tiger Chow's avatar
Brian Tiger Chow committed
183 184
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185
	// everything went better than expected :)
186
	return 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187 188
}

Jan Winkelmann's avatar
Jan Winkelmann committed
189
func (i *cmdInvocation) Run(ctx context.Context) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191

	// check if user wants to debug. option OR env var.
192
	debug, _ := i.req.Options["debug"].(bool)
193
	if debug || os.Getenv("IPFS_LOGGING") == "debug" {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
194
		u.Debug = true
Jeromy's avatar
Jeromy committed
195
		logging.SetDebugLogging()
196
	}
197 198 199
	if u.GetenvBool("DEBUG") {
		u.Debug = true
	}
200

201
	return callCommand(ctx, i.req, Root, i.ctx)
202
}
203

Brian Tiger Chow's avatar
Brian Tiger Chow committed
204
func (i *cmdInvocation) constructNodeFunc(ctx context.Context) func() (*core.IpfsNode, error) {
Jan Winkelmann's avatar
Jan Winkelmann committed
205
	return func() (n *core.IpfsNode, err error) {
206 207 208
		if i.req == nil {
			return nil, errors.New("constructing node without a request")
		}
209

210
		r, err := fsrepo.Open(i.ctx.ConfigRoot)
211
		if err != nil { // repo is owned by the node
212
			return nil, err
213
		}
214

215 216
		// ok everything is good. set it on the invocation (for ownership)
		// and return it.
Jan Winkelmann's avatar
Jan Winkelmann committed
217
		n, err = core.NewNode(ctx, &core.BuildCfg{
218
			Online: i.ctx.Online,
219 220
			Repo:   r,
		})
221 222 223
		if err != nil {
			return nil, err
		}
224
		n.SetLocal(true)
225 226
		i.node = n
		return i.node, nil
227
	}
228 229 230 231 232 233 234 235 236 237 238 239
}

func (i *cmdInvocation) close() {
	// let's not forget teardown. If a node was initialized, we must close it.
	// Note that this means the underlying req.Context().Node variable is exposed.
	// this is gross, and should be changed when we extract out the exec Context.
	if i.node != nil {
		log.Info("Shutting down node...")
		i.node.Close()
	}
}

240
func (i *cmdInvocation) Parse(ctx context.Context, args []string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241
	var err error
242

243
	i.req, err = cli.Parse(args, os.Stdin, Root)
244
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
		return err
246 247
	}

248 249 250 251 252 253
	//TODO remove this
	//fmt.Printf("%#v\n", i.req)

	// TODO(keks): pass this as arg to cli.Parse()
	i.req.Context = ctx

Brian Tiger Chow's avatar
Brian Tiger Chow committed
254
	repoPath, err := getRepoPath(i.req)
255
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256
		return err
257
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
258
	log.Debugf("config path is %s", repoPath)
259

260
	// this sets up the function that will initialize the config lazily.
261 262 263 264 265
	if i.ctx == nil {
		i.ctx = &oldcmds.Context{}
	}
	i.ctx.ConfigRoot = repoPath
	i.ctx.LoadConfig = loadConfig
266 267
	// this sets up the function that will initialize the node
	// this is so that we can construct the node lazily.
268
	i.ctx.ConstructNode = i.constructNodeFunc(ctx)
269

270 271
	// if no encoding was specified by user, default to plaintext encoding
	// (if command doesn't support plaintext, use JSON instead)
272 273 274
	if enc := i.req.Options[cmds.EncShort]; enc == "" {
		if i.req.Command.Encoders != nil && i.req.Command.Encoders[cmds.Text] != nil {
			i.req.SetOption(cmds.EncShort, cmds.Text)
275
		} else {
276
			i.req.SetOption(cmds.EncShort, cmds.JSON)
277 278 279
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280
	return nil
281 282
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283
func (i *cmdInvocation) requestedHelp() (short bool, long bool, err error) {
284 285
	longHelp, _ := i.req.Options["help"].(bool)
	shortHelp, _ := i.req.Options["h"].(bool)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286
	return longHelp, shortHelp, nil
287
}
288

289
func callPreCommandHooks(ctx context.Context, details cmdDetails, req *cmds.Request, root *cmds.Command) error {
290

291
	log.Event(ctx, "callPreCommandHooks", &details)
292
	log.Debug("calling pre-command hooks...")
293 294 295 296

	return nil
}

297 298 299
func callCommand(ctx context.Context, req *cmds.Request, root *cmds.Command, cctx *oldcmds.Context) error {
	log.Info(config.EnvDir, " ", cctx.ConfigRoot)
	cmd := req.Command
300

301
	details, err := commandDetails(req.Path, root)
Jeromy's avatar
Jeromy committed
302
	if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
303
		return err
Jeromy's avatar
Jeromy committed
304
	}
305

306
	client, err := commandShouldRunOnDaemon(*details, req, root, cctx)
307
	if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
308
		return err
309
	}
310

311
	err = callPreCommandHooks(ctx, *details, req, root)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
312
	if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
313 314 315
		return err
	}

316
	encTypeStr, _ := req.Options[cmds.EncShort].(string)
Jan Winkelmann's avatar
Jan Winkelmann committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330
	encType := cmds.EncodingType(encTypeStr)

	var (
		re     cmds.ResponseEmitter
		exitCh <-chan int
	)

	// first if condition checks the command's encoder map, second checks global encoder map (cmd vs. cmds)
	if enc, ok := cmd.Encoders[encType]; ok {
		re, exitCh = cli.NewResponseEmitter(os.Stdout, os.Stderr, enc, req)
	} else if enc, ok := cmds.Encoders[encType]; ok {
		re, exitCh = cli.NewResponseEmitter(os.Stdout, os.Stderr, enc, req)
	} else {
		return fmt.Errorf("could not find matching encoder for enctype %#v", encType)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
331
	}
332

333
	if cmd.PreRun != nil {
334
		err = cmd.PreRun(req, cctx)
335
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
336
			return err
337 338 339
		}
	}

Jan Winkelmann's avatar
Jan Winkelmann committed
340 341 342 343
	if cmd.PostRun != nil && cmd.PostRun[cmds.CLI] != nil {
		re = cmd.PostRun[cmds.CLI](req, re)
	}

Jeromy's avatar
Jeromy committed
344
	if client != nil && !cmd.External {
345
		log.Debug("executing command via API")
Jan Winkelmann's avatar
Jan Winkelmann committed
346 347

		res, err := client.Send(req)
348
		if err != nil {
349 350 351
			if isConnRefused(err) {
				err = repo.ErrApiNotRunning
			}
Jan Winkelmann's avatar
Jan Winkelmann committed
352 353

			return wrapContextCanceled(err)
354
		}
355

Jan Winkelmann's avatar
Jan Winkelmann committed
356
		go func() {
keks's avatar
keks committed
357
			err := cmds.Copy(re, res)
Jan Winkelmann's avatar
Jan Winkelmann committed
358
			if err != nil {
keks's avatar
keks committed
359 360 361 362
				err = re.Emit(cmdkit.Error{err.Error(), cmdkit.ErrNormal | cmdkit.ErrFatal})
				if err != nil {
					log.Error(err)
				}
Jan Winkelmann's avatar
Jan Winkelmann committed
363 364
			}
		}()
365
	} else {
366
		log.Debug("executing command locally")
367

368
		pluginpath := filepath.Join(cctx.ConfigRoot, "plugins")
369
		if _, err := loader.LoadPlugins(pluginpath); err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
370
			return err
371 372
		}

373
		// Okay!!!!! NOW we can call the command.
Jan Winkelmann's avatar
Jan Winkelmann committed
374
		go func() {
375
			err := root.Call(req, re, cctx)
Jan Winkelmann's avatar
Jan Winkelmann committed
376 377 378 379
			if err != nil {
				re.SetError(err, cmdkit.ErrNormal)
			}
		}()
380
	}
381

Jan Winkelmann's avatar
Jan Winkelmann committed
382 383
	if returnCode := <-exitCh; returnCode != 0 {
		err = exitErr(returnCode)
384 385
	}

Jan Winkelmann's avatar
Jan Winkelmann committed
386
	return err
387 388
}

389 390 391 392 393
// commandDetails returns a command's details for the command given by |path|
// within the |root| command tree.
//
// Returns an error if the command is not found in the Command tree.
func commandDetails(path []string, root *cmds.Command) (*cmdDetails, error) {
394 395 396 397
	var details cmdDetails
	// find the last command in path that has a cmdDetailsMap entry
	cmd := root
	for _, cmp := range path {
Jan Winkelmann's avatar
Jan Winkelmann committed
398 399
		cmd = cmd.Subcommand(cmp)
		if cmd == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
400
			return nil, fmt.Errorf("subcommand %s should be in root", cmp)
401
		}
402

Jan Winkelmann's avatar
Jan Winkelmann committed
403
		if cmdDetails, found := cmdDetailsMap[strings.Join(path, "/")]; found {
404 405
			details = cmdDetails
		}
406
	}
407 408 409 410
	return &details, nil
}

// commandShouldRunOnDaemon determines, from commmand details, whether a
411
// command ought to be executed on an ipfs daemon.
412
//
413
// It returns a client if the command should be executed on a daemon and nil if
414 415
// it should be executed on a client. It returns an error if the command must
// NOT be executed on either.
416 417
func commandShouldRunOnDaemon(details cmdDetails, req *cmds.Request, root *cmds.Command, cctx *oldcmds.Context) (http.Client, error) {
	path := req.Path
418 419
	// root command.
	if len(path) < 1 {
420
		return nil, nil
421
	}
422 423

	if details.cannotRunOnClient && details.cannotRunOnDaemon {
424
		return nil, fmt.Errorf("command disabled: %s", path[0])
425 426
	}

427
	if details.doesNotUseRepo && details.canRunOnClient() {
428
		return nil, nil
429 430
	}

431 432 433 434
	// at this point need to know whether api is running. we defer
	// to this point so that we dont check unnecessarily

	// did user specify an api to use for this command?
435
	apiAddrStr, _ := req.Options[coreCmds.ApiOption].(string)
436

437
	client, err := getApiClient(cctx.ConfigRoot, apiAddrStr)
438
	if err == repo.ErrApiNotRunning {
439
		if apiAddrStr != "" && req.Command != daemonCmd {
440 441 442 443
			// if user SPECIFIED an api, and this cmd is not daemon
			// we MUST use it. so error out.
			return nil, err
		}
444

445 446 447 448
		// ok for api not to be running
	} else if err != nil { // some other api error
		return nil, err
	}
449

michael's avatar
michael committed
450
	if client != nil {
451
		if details.cannotRunOnDaemon {
452
			// check if daemon locked. legacy error text, for now.
michael's avatar
michael committed
453
			log.Debugf("Command cannot run on daemon. Checking if daemon is locked")
454
			if daemonLocked, _ := fsrepo.LockedByOtherProcess(cctx.ConfigRoot); daemonLocked {
rht's avatar
rht committed
455
				return nil, cmds.ClientError("ipfs daemon is running. please stop it to run this command")
456
			}
rht's avatar
rht committed
457
			return nil, nil
458 459
		}

460
		return client, nil
461 462 463
	}

	if details.cannotRunOnClient {
464
		return nil, cmds.ClientError("must run on the ipfs daemon")
465 466
	}

467
	return nil, nil
468 469
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
470
func isClientError(err error) bool {
Jan Winkelmann's avatar
Jan Winkelmann committed
471 472
	if e, ok := err.(*cmdkit.Error); ok {
		return e.Code == cmdkit.ErrClient
473
	}
Jan Winkelmann's avatar
Jan Winkelmann committed
474

Brian Tiger Chow's avatar
Brian Tiger Chow committed
475
	return false
476 477
}

478 479
func getRepoPath(req *cmds.Request) (string, error) {
	repoOpt, found := req.Options["config"].(string)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
480 481
	if found && repoOpt != "" {
		return repoOpt, nil
482 483
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
484
	repoPath, err := fsrepo.BestKnownPath()
485 486 487
	if err != nil {
		return "", err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
488
	return repoPath, nil
489 490
}

491
func loadConfig(path string) (*config.Config, error) {
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
492
	return fsrepo.ConfigAt(path)
493
}
494

495 496 497 498 499 500 501 502 503 504
// startProfiling begins CPU profiling and returns a `stop` function to be
// executed as late as possible. The stop function captures the memprofile.
func startProfiling() (func(), error) {

	// start CPU profiling as early as possible
	ofi, err := os.Create(cpuProfile)
	if err != nil {
		return nil, err
	}
	pprof.StartCPUProfile(ofi)
505
	go func() {
506
		for range time.NewTicker(time.Second * 30).C {
507 508
			err := writeHeapProfileToFile()
			if err != nil {
rht's avatar
rht committed
509
				log.Error(err)
510 511 512
			}
		}
	}()
513 514 515 516 517 518 519 520

	stopProfiling := func() {
		pprof.StopCPUProfile()
		defer ofi.Close() // captured by the closure
	}
	return stopProfiling, nil
}

521 522 523
func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
524
		return err
525
	}
526
	defer mprof.Close() // _after_ writing the heap profile
527 528
	return pprof.WriteHeapProfile(mprof)
}
529

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
// IntrHandler helps set up an interrupt handler that can
// be cleanly shut down through the io.Closer interface.
type IntrHandler struct {
	sig chan os.Signal
	wg  sync.WaitGroup
}

func NewIntrHandler() *IntrHandler {
	ih := &IntrHandler{}
	ih.sig = make(chan os.Signal, 1)
	return ih
}

func (ih *IntrHandler) Close() error {
	close(ih.sig)
	ih.wg.Wait()
	return nil
}
548

549 550 551 552 553 554 555 556
// Handle starts handling the given signals, and will call the handler
// callback function each time a signal is catched. The function is passed
// the number of times the handler has been triggered in total, as
// well as the handler itself, so that the handling logic can use the
// handler's wait group to ensure clean shutdown when Close() is called.
func (ih *IntrHandler) Handle(handler func(count int, ih *IntrHandler), sigs ...os.Signal) {
	signal.Notify(ih.sig, sigs...)
	ih.wg.Add(1)
Matt Bell's avatar
Matt Bell committed
557
	go func() {
558 559
		defer ih.wg.Done()
		count := 0
560
		for range ih.sig {
561 562 563 564 565 566 567
			count++
			handler(count, ih)
		}
		signal.Stop(ih.sig)
	}()
}

568
func (i *cmdInvocation) SetupInterruptHandler(ctx context.Context) (io.Closer, context.Context) {
569

570
	intrh := NewIntrHandler()
571 572
	ctx, cancelFunc := context.WithCancel(ctx)

573 574 575
	handlerFunc := func(count int, ih *IntrHandler) {
		switch count {
		case 1:
576
			fmt.Println() // Prevent un-terminated ^C character in terminal
577 578 579 580

			ih.wg.Add(1)
			go func() {
				defer ih.wg.Done()
581
				cancelFunc()
582
			}()
583

584 585 586
		default:
			fmt.Println("Received another interrupt before graceful shutdown, terminating...")
			os.Exit(-1)
Matt Bell's avatar
Matt Bell committed
587
		}
588 589 590
	}

	intrh.Handle(handlerFunc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
591

592
	return intrh, ctx
593
}
594 595 596 597

func profileIfEnabled() (func(), error) {
	// FIXME this is a temporary hack so profiling of asynchronous operations
	// works as intended.
598
	if os.Getenv(EnvEnableProfiling) != "" {
599 600 601 602 603 604 605 606
		stopProfilingFunc, err := startProfiling() // TODO maybe change this to its own option... profiling makes it slower.
		if err != nil {
			return nil, err
		}
		return stopProfilingFunc, nil
	}
	return func() {}, nil
}
607

608 609 610 611
var apiFileErrorFmt string = `Failed to parse '%[1]s/api' file.
	error: %[2]s
If you're sure go-ipfs isn't running, you can just delete it.
`
612 613
var checkIPFSUnixFmt = "Otherwise check:\n\tps aux | grep ipfs"
var checkIPFSWinFmt = "Otherwise check:\n\ttasklist | findstr ipfs"
614

615 616 617
// getApiClient checks the repo, and the given options, checking for
// a running API service. if there is one, it returns a client.
// otherwise, it returns errApiNotRunning, or another error.
Jan Winkelmann's avatar
Jan Winkelmann committed
618
func getApiClient(repoPath, apiAddrStr string) (http.Client, error) {
619 620 621 622 623 624 625 626 627
	var apiErrorFmt string
	switch {
	case osh.IsUnix():
		apiErrorFmt = apiFileErrorFmt + checkIPFSUnixFmt
	case osh.IsWindows():
		apiErrorFmt = apiFileErrorFmt + checkIPFSWinFmt
	default:
		apiErrorFmt = apiFileErrorFmt
	}
628

629 630 631 632 633 634 635 636 637 638 639 640 641
	var addr ma.Multiaddr
	var err error
	if len(apiAddrStr) != 0 {
		addr, err = ma.NewMultiaddr(apiAddrStr)
		if err != nil {
			return nil, err
		}
		if len(addr.Protocols()) == 0 {
			return nil, fmt.Errorf("mulitaddr doesn't provide any protocols")
		}
	} else {
		addr, err = fsrepo.APIAddr(repoPath)
		if err == repo.ErrApiNotRunning {
642 643 644
			return nil, err
		}

645 646 647 648 649 650
		if err != nil {
			return nil, fmt.Errorf(apiErrorFmt, repoPath, err.Error())
		}
	}
	if len(addr.Protocols()) == 0 {
		return nil, fmt.Errorf(apiErrorFmt, repoPath, "multiaddr doesn't provide any protocols")
651
	}
rht's avatar
rht committed
652
	return apiClientForAddr(addr)
653 654
}

Jan Winkelmann's avatar
Jan Winkelmann committed
655
func apiClientForAddr(addr ma.Multiaddr) (http.Client, error) {
656 657 658 659 660
	_, host, err := manet.DialArgs(addr)
	if err != nil {
		return nil, err
	}

Jan Winkelmann's avatar
Jan Winkelmann committed
661
	return http.NewClient(host), nil
662 663 664
}

func isConnRefused(err error) bool {
Jeromy's avatar
Jeromy committed
665 666 667 668 669 670 671 672 673 674 675
	// unwrap url errors from http calls
	if urlerr, ok := err.(*url.Error); ok {
		err = urlerr.Err
	}

	netoperr, ok := err.(*net.OpError)
	if !ok {
		return false
	}

	return netoperr.Op == "dial"
676
}
rht's avatar
rht committed
677 678 679 680 681 682 683

func wrapContextCanceled(err error) error {
	if strings.Contains(err.Error(), "request canceled") {
		err = errRequestCanceled
	}
	return err
}