main.go 13.3 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
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
18
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr-net"
19

20
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
21 22 23
	cmds "github.com/jbenet/go-ipfs/commands"
	cmdsCli "github.com/jbenet/go-ipfs/commands/cli"
	cmdsHttp "github.com/jbenet/go-ipfs/commands/http"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24
	core "github.com/jbenet/go-ipfs/core"
25
	config "github.com/jbenet/go-ipfs/repo/config"
26
	fsrepo "github.com/jbenet/go-ipfs/repo/fsrepo"
27
	eventlog "github.com/jbenet/go-ipfs/thirdparty/eventlog"
28
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
29
	"github.com/jbenet/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
)
44

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

// 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
58
func main() {
59 60
	rand.Seed(time.Now().UnixNano())
	runtime.GOMAXPROCS(3) // FIXME rm arbitrary choice for n
61
	ctx := eventlog.ContextWithLoggable(context.Background(), eventlog.Uuid("session"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62
	var err error
63 64
	var invoc cmdInvocation
	defer invoc.close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66 67 68 69 70 71

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

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

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

90 91 92 93 94 95
	// 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
96
	// parse the commandline into a command invocation
97
	parseErr := invoc.Parse(ctx, os.Args[1:])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99 100

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

113 114 115 116
	// 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
117
		printHelp(false, os.Stdout)
118 119 120 121
		os.Exit(0)
	}

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

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

135 136 137 138 139
	// 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 {
140
		close(invoc.req.Context().InitDone)
141 142
	}

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

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

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

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

	// 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
165
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166
		return nil, err
Brian Tiger Chow's avatar
Brian Tiger Chow committed
167
	}
168
	if debug || u.GetenvBool("DEBUG") || os.Getenv("IPFS_LOGGING") == "debug" {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
169
		u.Debug = true
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170
		u.SetDebugLogging()
171
	}
172

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

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

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

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

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

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

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

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

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

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

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

237
	// this sets up the function that will initialize the config lazily.
238
	cmdctx := i.req.Context()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
239
	cmdctx.ConfigRoot = repoPath
240
	cmdctx.LoadConfig = loadConfig
241 242
	// 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
243
	cmdctx.ConstructNode = i.constructNodeFunc(ctx)
244

245 246
	// 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
247
	if !i.req.Option("encoding").Found() {
248
		if i.req.Command().Marshalers != nil && i.req.Command().Marshalers[cmds.Text] != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249
			i.req.SetOption("encoding", cmds.Text)
250
		} else {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251
			i.req.SetOption("encoding", cmds.JSON)
252 253 254
		}
	}

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

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

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

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

	return nil
}

278
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
279
	log.Info(config.EnvDir, " ", req.Context().ConfigRoot)
280
	var res cmds.Response
281

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

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

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

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

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

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

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

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

323
		client := cmdsHttp.NewClient(host)
324

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

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

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

	}
337 338

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

342
	return res, nil
343 344
}

345 346 347 348 349
// 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) {
350 351 352 353 354 355 356
	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
357
			return nil, debugerror.Errorf("subcommand %s should be in root", cmp)
358
		}
359

360 361 362
		if cmdDetails, found := cmdDetailsMap[cmd]; found {
			details = cmdDetails
		}
363
	}
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
	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
	}
379 380 381 382 383

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

384
	if details.doesNotUseRepo && details.canRunOnClient() {
385 386 387 388 389
		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.
390
	daemonLocked := fsrepo.LockedByOtherProcess(req.Context().ConfigRoot)
391 392 393

	if daemonLocked {

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

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
		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
411
func isClientError(err error) bool {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
412 413 414 415

	// 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
416
	// cast to cmds.Error
Brian Tiger Chow's avatar
Brian Tiger Chow committed
417 418 419 420 421
	switch e := err.(type) {
	case *cmds.Error:
		return e.Code == cmds.ErrClient
	case cmds.Error:
		return e.Code == cmds.ErrClient
422
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
423
	return false
424 425
}

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

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

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

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

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

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

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

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

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

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

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

500
			n, err := ctx.GetNode()
501 502
			if err != nil {
				log.Error(err)
503
				fmt.Println("Received interrupt signal, terminating...")
504
				os.Exit(-1)
505 506
			}

507 508
			switch count {
			case 0:
509
				fmt.Println("Received interrupt signal, shutting down...")
510 511 512 513 514 515
				go func() {
					n.Close()
					log.Info("Gracefully shut down.")
				}()

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

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

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