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

import (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
5
	"errors"
6 7
	"fmt"
	"io"
8
	"math/rand"
9
	"os"
Matt Bell's avatar
Matt Bell committed
10
	"os/signal"
11
	"runtime"
12
	"runtime/pprof"
13
	"strings"
14
	"syscall"
15
	"time"
16

17 18 19 20 21 22 23 24 25 26 27 28 29
	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"

	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	cmds "github.com/ipfs/go-ipfs/commands"
	cmdsCli "github.com/ipfs/go-ipfs/commands/cli"
	cmdsHttp "github.com/ipfs/go-ipfs/commands/http"
	core "github.com/ipfs/go-ipfs/core"
	config "github.com/ipfs/go-ipfs/repo/config"
	fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"
	u "github.com/ipfs/go-ipfs/util"
	"github.com/ipfs/go-ipfs/util/debugerror"
30 31
)

32
// log is the command logger
33
var log = eventlog.Logger("cmd/ipfs")
34

35 36 37
// signal to output help
var errHelpRequested = errors.New("Help Requested")

38
const (
39 40 41 42
	EnvEnableProfiling = "IPFS_PROF"
	cpuProfile         = "ipfs.cpuprof"
	heapProfile        = "ipfs.memprof"
	errorFormat        = "ERROR: %v\n\n"
43
	shutdownMessage    = "Received interrupt signal, shutting down..."
44
)
45

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48 49
type cmdInvocation struct {
	path []string
	cmd  *cmds.Command
	req  cmds.Request
50
	node *core.IpfsNode
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51 52 53 54 55 56 57 58
}

// main roadmap:
// - parse the commandline to get a cmdInvocation
// - if user requests, help, print it and exit.
// - run the command invocation
// - output the response
// - if anything fails, print error, maybe with help
59
func main() {
60 61
	rand.Seed(time.Now().UnixNano())
	runtime.GOMAXPROCS(3) // FIXME rm arbitrary choice for n
62
	ctx := eventlog.ContextWithLoggable(context.Background(), eventlog.Uuid("session"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
	var err error
64 65
	var invoc cmdInvocation
	defer invoc.close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66 67 68 69 70 71 72

	// 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())
	}

73 74 75 76 77 78 79
	stopFunc, err := profileIfEnabled()
	if err != nil {
		printErr(err)
		os.Exit(1)
	}
	defer stopFunc() // to be executed as late as possible

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80 81
	// 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
82
	printHelp := func(long bool, w io.Writer) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85 86 87
		helpFunc := cmdsCli.ShortHelp
		if long {
			helpFunc = cmdsCli.LongHelp
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88
		helpFunc("ipfs", Root, invoc.path, w)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89 90
	}

91 92 93 94 95 96
	// this is a message to tell the user how to get the help text
	printMetaHelp := func(w io.Writer) {
		cmdPath := strings.Join(invoc.path, " ")
		fmt.Fprintf(w, "Use 'ipfs %s --help' for information about this command\n", cmdPath)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
	// parse the commandline into a command invocation
98
	parseErr := invoc.Parse(ctx, os.Args[1:])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99 100 101

	// BEFORE handling the parse error, if we have enough information
	// AND the user requested help, print it out and exit
102
	if invoc.req != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104 105 106 107 108
		longH, shortH, err := invoc.requestedHelp()
		if err != nil {
			printErr(err)
			os.Exit(1)
		}
		if longH || shortH {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
			printHelp(longH, os.Stdout)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111 112 113
			os.Exit(0)
		}
	}

114 115 116 117
	// here we handle the cases where
	// - commands with no Run func are invoked directly.
	// - the main command is invoked.
	if invoc.cmd == nil || invoc.cmd.Run == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
		printHelp(false, os.Stdout)
119 120 121 122
		os.Exit(0)
	}

	// ok now handle parse error (which means cli input was wrong,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123
	// e.g. incorrect number of args, or nonexistent subcommand)
124 125
	if parseErr != nil {
		printErr(parseErr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126 127 128 129 130

		// this was a user error, print help.
		if invoc.cmd != nil {
			// we need a newline space.
			fmt.Fprintf(os.Stderr, "\n")
131
			printMetaHelp(os.Stderr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
133 134
		os.Exit(1)
	}
Matt Bell's avatar
Matt Bell committed
135

136 137 138 139 140
	// our global interrupt handler may try to stop the daemon
	// before the daemon is ready to be stopped; this dirty
	// workaround is for the daemon only; other commands are always
	// ready to be stopped
	if invoc.cmd != daemonCmd {
141
		close(invoc.req.Context().InitDone)
142 143
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144
	// ok, finally, run the command invocation.
145
	output, err := invoc.Run(ctx)
146
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147 148 149 150
		printErr(err)

		// if this error was a client error, print short help too.
		if isClientError(err) {
151
			printMetaHelp(os.Stderr)
152
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153
		os.Exit(1)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
154 155
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156 157 158 159
	// everything went better than expected :)
	io.Copy(os.Stdout, output)
}

160
func (i *cmdInvocation) Run(ctx context.Context) (output io.Reader, err error) {
161 162
	// setup our global interrupt handler.
	i.setupInterruptHandler()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163 164 165

	// check if user wants to debug. option OR env var.
	debug, _, err := i.req.Option("debug").Bool()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
166
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167
		return nil, err
Brian Tiger Chow's avatar
Brian Tiger Chow committed
168
	}
169
	if debug || u.GetenvBool("DEBUG") || os.Getenv("IPFS_LOGGING") == "debug" {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
170
		u.Debug = true
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171
		u.SetDebugLogging()
172
	}
173

174
	res, err := callCommand(ctx, i.req, Root, i.cmd)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
175
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
		return nil, err
177
	}
178

179 180 181 182
	if err := res.Error(); err != nil {
		return nil, err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
	return res.Reader()
184
}
185

Brian Tiger Chow's avatar
Brian Tiger Chow committed
186
func (i *cmdInvocation) constructNodeFunc(ctx context.Context) func() (*core.IpfsNode, error) {
187 188 189 190
	return func() (*core.IpfsNode, error) {
		if i.req == nil {
			return nil, errors.New("constructing node without a request")
		}
191

192 193 194 195
		cmdctx := i.req.Context()
		if cmdctx == nil {
			return nil, errors.New("constructing node without a request context")
		}
196

197 198
		r, err := fsrepo.Open(i.req.Context().ConfigRoot)
		if err != nil { // repo is owned by the node
199
			return nil, err
200
		}
201

202 203
		// ok everything is good. set it on the invocation (for ownership)
		// and return it.
204 205 206 207 208 209
		n, err := core.NewIPFSNode(ctx, core.Standard(r, cmdctx.Online))
		if err != nil {
			return nil, err
		}
		i.node = n
		return i.node, nil
210
	}
211 212 213 214 215 216 217 218 219 220 221 222
}

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()
	}
}

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

226
	i.req, i.cmd, i.path, err = cmdsCli.Parse(args, os.Stdin, Root)
227
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228
		return err
229
	}
230
	i.req.Context().Context = ctx
231

Brian Tiger Chow's avatar
Brian Tiger Chow committed
232
	repoPath, err := getRepoPath(i.req)
233
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234
		return err
235
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
236
	log.Debugf("config path is %s", repoPath)
237

238
	// this sets up the function that will initialize the config lazily.
239
	cmdctx := i.req.Context()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
240
	cmdctx.ConfigRoot = repoPath
241
	cmdctx.LoadConfig = loadConfig
242 243
	// this sets up the function that will initialize the node
	// this is so that we can construct the node lazily.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
244
	cmdctx.ConstructNode = i.constructNodeFunc(ctx)
245

246 247
	// if no encoding was specified by user, default to plaintext encoding
	// (if command doesn't support plaintext, use JSON instead)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248
	if !i.req.Option("encoding").Found() {
249
		if i.req.Command().Marshalers != nil && i.req.Command().Marshalers[cmds.Text] != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250
			i.req.SetOption("encoding", cmds.Text)
251
		} else {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252
			i.req.SetOption("encoding", cmds.JSON)
253 254 255
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256
	return nil
257 258
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259 260
func (i *cmdInvocation) requestedHelp() (short bool, long bool, err error) {
	longHelp, _, err := i.req.Option("help").Bool()
261
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262
		return false, false, err
263
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
264
	shortHelp, _, err := i.req.Option("h").Bool()
265
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266
		return false, false, err
267
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
268
	return longHelp, shortHelp, nil
269
}
270

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

273
	log.Event(ctx, "callPreCommandHooks", &details)
274 275 276 277 278
	log.Debug("Calling pre-command hooks...")

	return nil
}

279
func callCommand(ctx context.Context, req cmds.Request, root *cmds.Command, cmd *cmds.Command) (cmds.Response, error) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
280
	log.Info(config.EnvDir, " ", req.Context().ConfigRoot)
281
	var res cmds.Response
282

283 284 285 286 287
	details, err := commandDetails(req.Path(), root)
	if err != nil {
		return nil, err
	}

288
	log.Debug("looking for running daemon...")
289
	useDaemon, err := commandShouldRunOnDaemon(*details, req, root)
290 291 292
	if err != nil {
		return nil, err
	}
293

294
	err = callPreCommandHooks(ctx, *details, req, root)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295 296 297
	if err != nil {
		return nil, err
	}
298

299 300 301 302 303 304 305
	if cmd.PreRun != nil {
		err = cmd.PreRun(req)
		if err != nil {
			return nil, err
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
306
	if useDaemon {
307

308 309 310 311 312
		cfg, err := req.Context().GetConfig()
		if err != nil {
			return nil, err
		}

313 314 315 316
		addr, err := ma.NewMultiaddr(cfg.Addresses.API)
		if err != nil {
			return nil, err
		}
317

318
		log.Infof("Executing command on daemon running at %s", addr)
319 320 321 322
		_, host, err := manet.DialArgs(addr)
		if err != nil {
			return nil, err
		}
323

324
		client := cmdsHttp.NewClient(host)
325

326 327 328 329
		res, err = client.Send(req)
		if err != nil {
			return nil, err
		}
330

331
	} else {
332
		log.Debug("Executing command locally")
333

334 335
		// Okay!!!!! NOW we can call the command.
		res = root.Call(req)
336 337

	}
338 339

	if cmd.PostRun != nil {
340
		cmd.PostRun(req, res)
341 342
	}

343
	return res, nil
344 345
}

346 347 348 349 350
// 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) {
351 352 353 354 355 356 357
	var details cmdDetails
	// find the last command in path that has a cmdDetailsMap entry
	cmd := root
	for _, cmp := range path {
		var found bool
		cmd, found = cmd.Subcommands[cmp]
		if !found {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
358
			return nil, debugerror.Errorf("subcommand %s should be in root", cmp)
359
		}
360

361 362 363
		if cmdDetails, found := cmdDetailsMap[cmd]; found {
			details = cmdDetails
		}
364
	}
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
	return &details, nil
}

// commandShouldRunOnDaemon determines, from commmand details, whether a
// command ought to be executed on an IPFS daemon.
//
// It returns true if the command should be executed on a daemon and false if
// it should be executed on a client. It returns an error if the command must
// NOT be executed on either.
func commandShouldRunOnDaemon(details cmdDetails, req cmds.Request, root *cmds.Command) (bool, error) {
	path := req.Path()
	// root command.
	if len(path) < 1 {
		return false, nil
	}
380 381 382 383 384

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

385
	if details.doesNotUseRepo && details.canRunOnClient() {
386 387 388 389 390
		return false, nil
	}

	// at this point need to know whether daemon is running. we defer
	// to this point so that some commands dont open files unnecessarily.
391
	daemonLocked := fsrepo.LockedByOtherProcess(req.Context().ConfigRoot)
392 393 394

	if daemonLocked {

395 396
		log.Info("a daemon is running...")

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
		if details.cannotRunOnDaemon {
			e := "ipfs daemon is running. please stop it to run this command"
			return false, cmds.ClientError(e)
		}

		return true, nil
	}

	if details.cannotRunOnClient {
		return false, cmds.ClientError("must run on the ipfs daemon")
	}

	return false, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
412
func isClientError(err error) bool {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
413 414 415 416

	// Somewhat suprisingly, the pointer cast fails to recognize commands.Error
	// passed as values, so we check both.

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
417
	// cast to cmds.Error
Brian Tiger Chow's avatar
Brian Tiger Chow committed
418 419 420 421 422
	switch e := err.(type) {
	case *cmds.Error:
		return e.Code == cmds.ErrClient
	case cmds.Error:
		return e.Code == cmds.ErrClient
423
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
424
	return false
425 426
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
427 428
func getRepoPath(req cmds.Request) (string, error) {
	repoOpt, found, err := req.Option("config").String()
429 430 431
	if err != nil {
		return "", err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
432 433
	if found && repoOpt != "" {
		return repoOpt, nil
434 435
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
436
	repoPath, err := fsrepo.BestKnownPath()
437 438 439
	if err != nil {
		return "", err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
440
	return repoPath, nil
441 442
}

443
func loadConfig(path string) (*config.Config, error) {
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
444
	return fsrepo.ConfigAt(path)
445
}
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
// 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)

	stopProfiling := func() {
		pprof.StopCPUProfile()
		defer ofi.Close() // captured by the closure
		err := writeHeapProfileToFile()
		if err != nil {
			log.Critical(err)
		}
	}
	return stopProfiling, nil
}

469 470 471
func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
472
		return err
473
	}
474
	defer mprof.Close() // _after_ writing the heap profile
475 476
	return pprof.WriteHeapProfile(mprof)
}
477

Matt Bell's avatar
Matt Bell committed
478
// listen for and handle SIGTERM
479 480 481 482
func (i *cmdInvocation) setupInterruptHandler() {

	ctx := i.req.Context()
	sig := allInterruptSignals()
Matt Bell's avatar
Matt Bell committed
483 484

	go func() {
485
		// first time, try to shut down.
486

487 488
		// loop because we may be
		for count := 0; ; count++ {
489 490
			<-sig

491 492 493
			// if we're still initializing, cannot use `ctx.GetNode()`
			select {
			default: // initialization not done
494
				fmt.Println(shutdownMessage)
495 496 497 498
				os.Exit(-1)
			case <-ctx.InitDone:
			}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
499 500
			// TODO cancel the command context instead

501
			n, err := ctx.GetNode()
502 503
			if err != nil {
				log.Error(err)
504
				fmt.Println(shutdownMessage)
505
				os.Exit(-1)
506 507
			}

508 509
			switch count {
			case 0:
510
				fmt.Println(shutdownMessage)
511 512 513 514 515 516
				go func() {
					n.Close()
					log.Info("Gracefully shut down.")
				}()

			default:
517
				fmt.Println("Received another interrupt before graceful shutdown, terminating...")
518 519
				os.Exit(-1)
			}
Matt Bell's avatar
Matt Bell committed
520 521 522
		}
	}()
}
523 524 525 526

func allInterruptSignals() chan os.Signal {
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGHUP, syscall.SIGINT,
Jeromy's avatar
Jeromy committed
527
		syscall.SIGTERM)
528 529
	return sigc
}
530 531 532 533

func profileIfEnabled() (func(), error) {
	// FIXME this is a temporary hack so profiling of asynchronous operations
	// works as intended.
534
	if os.Getenv(EnvEnableProfiling) != "" {
535 536 537 538 539 540 541 542
		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
}