main.go 12.8 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" // log is the command logger
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
var log = eventlog.Logger("cmd/ipfs")
33

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

37
const (
38 39 40 41
	EnvEnableProfiling = "IPFS_PROF"
	cpuProfile         = "ipfs.cpuprof"
	heapProfile        = "ipfs.memprof"
	errorFormat        = "ERROR: %v\n\n"
42
)
43

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

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

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

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

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

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
	// ok, finally, run the command invocation.
135
	output, err := invoc.Run(ctx)
136
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139 140
		printErr(err)

		// if this error was a client error, print short help too.
		if isClientError(err) {
141
			printMetaHelp(os.Stderr)
142
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
		os.Exit(1)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
144 145
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147 148 149
	// everything went better than expected :)
	io.Copy(os.Stdout, output)
}

150
func (i *cmdInvocation) Run(ctx context.Context) (output io.Reader, err error) {
151 152
	// setup our global interrupt handler.
	i.setupInterruptHandler()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154 155

	// 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
156
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
		return nil, err
Brian Tiger Chow's avatar
Brian Tiger Chow committed
158
	}
159
	if debug || u.GetenvBool("DEBUG") || os.Getenv("IPFS_LOGGING") == "debug" {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
160
		u.Debug = true
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
		u.SetDebugLogging()
162
	}
163

164
	res, err := callCommand(ctx, i.req, Root, i.cmd)
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
167
	}
168

169 170 171 172
	if err := res.Error(); err != nil {
		return nil, err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173
	return res.Reader()
174
}
175

Brian Tiger Chow's avatar
Brian Tiger Chow committed
176
func (i *cmdInvocation) constructNodeFunc(ctx context.Context) func() (*core.IpfsNode, error) {
177 178 179 180
	return func() (*core.IpfsNode, error) {
		if i.req == nil {
			return nil, errors.New("constructing node without a request")
		}
181

182 183 184 185
		cmdctx := i.req.Context()
		if cmdctx == nil {
			return nil, errors.New("constructing node without a request context")
		}
186

187
		r := fsrepo.At(i.req.Context().ConfigRoot)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
188
		if err := r.Open(); err != nil { // repo is owned by the node
189
			return nil, err
190
		}
191

192 193
		// ok everything is good. set it on the invocation (for ownership)
		// and return it.
194 195 196 197 198 199
		n, err := core.NewIPFSNode(ctx, core.Standard(r, cmdctx.Online))
		if err != nil {
			return nil, err
		}
		i.node = n
		return i.node, nil
200
	}
201 202 203 204 205 206 207 208 209 210 211 212
}

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

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

216
	i.req, i.cmd, i.path, err = cmdsCli.Parse(args, os.Stdin, Root)
217
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
218
		return err
219
	}
220
	i.req.Context().Context = ctx
221

Brian Tiger Chow's avatar
Brian Tiger Chow committed
222
	repoPath, err := getRepoPath(i.req)
223
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224
		return err
225
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
226
	log.Debugf("config path is %s", repoPath)
227

228
	// this sets up the function that will initialize the config lazily.
229
	cmdctx := i.req.Context()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
230
	cmdctx.ConfigRoot = repoPath
231
	cmdctx.LoadConfig = loadConfig
232 233
	// 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
234
	cmdctx.ConstructNode = i.constructNodeFunc(ctx)
235

236 237
	// 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
238
	if !i.req.Option("encoding").Found() {
239
		if i.req.Command().Marshalers != nil && i.req.Command().Marshalers[cmds.Text] != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240
			i.req.SetOption("encoding", cmds.Text)
241
		} else {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242
			i.req.SetOption("encoding", cmds.JSON)
243 244 245
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246
	return nil
247 248
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249 250
func (i *cmdInvocation) requestedHelp() (short bool, long bool, err error) {
	longHelp, _, err := i.req.Option("help").Bool()
251
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252
		return false, false, err
253
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254
	shortHelp, _, err := i.req.Option("h").Bool()
255
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256
		return false, false, err
257
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258
	return longHelp, shortHelp, nil
259
}
260

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

263
	log.Event(ctx, "callPreCommandHooks", &details)
264 265 266 267 268
	log.Debug("Calling pre-command hooks...")

	return nil
}

269
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
270
	log.Info(config.EnvDir, " ", req.Context().ConfigRoot)
271
	var res cmds.Response
272

273 274 275 276 277
	details, err := commandDetails(req.Path(), root)
	if err != nil {
		return nil, err
	}

278
	log.Debug("looking for running daemon...")
279
	useDaemon, err := commandShouldRunOnDaemon(*details, req, root)
280 281 282
	if err != nil {
		return nil, err
	}
283

284
	err = callPreCommandHooks(ctx, *details, req, root)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
285 286 287
	if err != nil {
		return nil, err
	}
288

289 290 291 292 293 294 295
	if cmd.PreRun != nil {
		err = cmd.PreRun(req)
		if err != nil {
			return nil, err
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296
	if useDaemon {
297

298 299 300 301 302
		cfg, err := req.Context().GetConfig()
		if err != nil {
			return nil, err
		}

303 304 305 306
		addr, err := ma.NewMultiaddr(cfg.Addresses.API)
		if err != nil {
			return nil, err
		}
307

308
		log.Infof("Executing command on daemon running at %s", addr)
309 310 311 312
		_, host, err := manet.DialArgs(addr)
		if err != nil {
			return nil, err
		}
313

314
		client := cmdsHttp.NewClient(host)
315

316 317 318 319
		res, err = client.Send(req)
		if err != nil {
			return nil, err
		}
320

321
	} else {
322
		log.Debug("Executing command locally")
323

324 325
		// Okay!!!!! NOW we can call the command.
		res = root.Call(req)
326 327

	}
328 329

	if cmd.PostRun != nil {
330
		cmd.PostRun(req, res)
331 332
	}

333
	return res, nil
334 335
}

336 337 338 339 340
// 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) {
341 342 343 344 345 346 347
	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
348
			return nil, debugerror.Errorf("subcommand %s should be in root", cmp)
349
		}
350

351 352 353
		if cmdDetails, found := cmdDetailsMap[cmd]; found {
			details = cmdDetails
		}
354
	}
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
	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
	}
370 371 372 373 374

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

375
	if details.doesNotUseRepo && details.canRunOnClient() {
376 377 378 379 380
		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.
381
	daemonLocked := fsrepo.LockedByOtherProcess(req.Context().ConfigRoot)
382 383 384

	if daemonLocked {

385 386
		log.Info("a daemon is running...")

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
		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
402
func isClientError(err error) bool {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
403 404 405 406

	// 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
407
	// cast to cmds.Error
Brian Tiger Chow's avatar
Brian Tiger Chow committed
408 409 410 411 412
	switch e := err.(type) {
	case *cmds.Error:
		return e.Code == cmds.ErrClient
	case cmds.Error:
		return e.Code == cmds.ErrClient
413
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
414
	return false
415 416
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
417 418
func getRepoPath(req cmds.Request) (string, error) {
	repoOpt, found, err := req.Option("config").String()
419 420 421
	if err != nil {
		return "", err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
422 423
	if found && repoOpt != "" {
		return repoOpt, nil
424 425
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
426
	repoPath, err := fsrepo.BestKnownPath()
427 428 429
	if err != nil {
		return "", err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
430
	return repoPath, nil
431 432
}

433
func loadConfig(path string) (*config.Config, error) {
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
434
	return fsrepo.ConfigAt(path)
435
}
436

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
// 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
}

459 460 461
func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
462
		return err
463
	}
464
	defer mprof.Close() // _after_ writing the heap profile
465 466
	return pprof.WriteHeapProfile(mprof)
}
467

Matt Bell's avatar
Matt Bell committed
468
// listen for and handle SIGTERM
469 470 471 472
func (i *cmdInvocation) setupInterruptHandler() {

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

	go func() {
475
		// first time, try to shut down.
476

477 478
		// loop because we may be
		for count := 0; ; count++ {
479 480
			<-sig

Brian Tiger Chow's avatar
Brian Tiger Chow committed
481 482
			// TODO cancel the command context instead

483
			n, err := ctx.GetNode()
484 485
			if err != nil {
				log.Error(err)
486
				fmt.Println("Received interrupt signal, terminating...")
487
				os.Exit(-1)
488 489
			}

490 491
			switch count {
			case 0:
492
				fmt.Println("Received interrupt signal, shutting down...")
493 494 495 496 497 498
				go func() {
					n.Close()
					log.Info("Gracefully shut down.")
				}()

			default:
499
				fmt.Println("Received another interrupt before graceful shutdown, terminating...")
500 501
				os.Exit(-1)
			}
Matt Bell's avatar
Matt Bell committed
502 503 504
		}
	}()
}
505 506 507 508

func allInterruptSignals() chan os.Signal {
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGHUP, syscall.SIGINT,
Jeromy's avatar
Jeromy committed
509
		syscall.SIGTERM)
510 511
	return sigc
}
512 513 514 515

func profileIfEnabled() (func(), error) {
	// FIXME this is a temporary hack so profiling of asynchronous operations
	// works as intended.
516
	if os.Getenv(EnvEnableProfiling) != "" {
517 518 519 520 521 522 523 524
		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
}