main.go 12.8 KB
Newer Older
1 2 3
package main

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

15
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
16
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr-net"
17

18
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
19 20 21
	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
22
	core "github.com/jbenet/go-ipfs/core"
23
	config "github.com/jbenet/go-ipfs/repo/config"
24
	fsrepo "github.com/jbenet/go-ipfs/repo/fsrepo"
25
	eventlog "github.com/jbenet/go-ipfs/thirdparty/eventlog"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26
	updates "github.com/jbenet/go-ipfs/updates"
27
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
28
	"github.com/jbenet/go-ipfs/util/debugerror"
29 30 31
)

// log is the command logger
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
	cpuProfile  = "ipfs.cpuprof"
	heapProfile = "ipfs.memprof"
40 41
	errorFormat = "ERROR: %v\n\n"
)
42

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
		helpFunc("ipfs", Root, invoc.path, w)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79 80 81
	}

	// parse the commandline into a command invocation
82
	parseErr := invoc.Parse(ctx, os.Args[1:])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85

	// BEFORE handling the parse error, if we have enough information
	// AND the user requested help, print it out and exit
86
	if invoc.req != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87 88 89 90 91 92
		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
93
			printHelp(longH, os.Stdout)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94 95 96 97
			os.Exit(0)
		}
	}

98 99 100 101
	// 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
102
		printHelp(false, os.Stdout)
103 104 105 106
		os.Exit(0)
	}

	// ok now handle parse error (which means cli input was wrong,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107
	// e.g. incorrect number of args, or nonexistent subcommand)
108 109
	if parseErr != nil {
		printErr(parseErr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111 112 113 114

		// this was a user error, print help.
		if invoc.cmd != nil {
			// we need a newline space.
			fmt.Fprintf(os.Stderr, "\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115
			printHelp(false, os.Stderr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
117 118
		os.Exit(1)
	}
Matt Bell's avatar
Matt Bell committed
119

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120
	// ok, finally, run the command invocation.
121
	output, err := invoc.Run(ctx)
122
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123 124 125 126
		printErr(err)

		// if this error was a client error, print short help too.
		if isClientError(err) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127
			printHelp(false, os.Stderr)
128
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
		os.Exit(1)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
130 131
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133 134 135
	// everything went better than expected :)
	io.Copy(os.Stdout, output)
}

136
func (i *cmdInvocation) Run(ctx context.Context) (output io.Reader, err error) {
137 138
	// setup our global interrupt handler.
	i.setupInterruptHandler()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140 141

	// 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
142
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
		return nil, err
Brian Tiger Chow's avatar
Brian Tiger Chow committed
144
	}
145
	if debug || u.GetenvBool("DEBUG") || os.Getenv("IPFS_LOGGING") == "debug" {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
146
		u.Debug = true
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147
		u.SetDebugLogging()
148
	}
149

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150 151
	// if debugging, let's profile.
	// TODO maybe change this to its own option... profiling makes it slower.
152
	if u.Debug {
153
		stopProfilingFunc, err := startProfiling()
154
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155
			return nil, err
156
		}
157
		defer stopProfilingFunc() // to be executed as late as possible
158
	}
159

160
	res, err := callCommand(ctx, i.req, Root, i.cmd)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
161
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162
		return nil, err
163
	}
164

165 166 167 168
	if err := res.Error(); err != nil {
		return nil, err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
	return res.Reader()
170
}
171

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

178 179 180 181
		cmdctx := i.req.Context()
		if cmdctx == nil {
			return nil, errors.New("constructing node without a request context")
		}
182

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

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

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

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

212
	i.req, i.cmd, i.path, err = cmdsCli.Parse(args, os.Stdin, Root)
213
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214
		return err
215 216
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217
	configPath, err := getConfigRoot(i.req)
218
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
		return err
220
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
221
	log.Debugf("config path is %s", configPath)
222

223
	// this sets up the function that will initialize the config lazily.
224 225 226
	cmdctx := i.req.Context()
	cmdctx.ConfigRoot = configPath
	cmdctx.LoadConfig = loadConfig
227 228
	// 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
229
	cmdctx.ConstructNode = i.constructNodeFunc(ctx)
230

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241
	return nil
242 243
}

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

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

258
	log.Event(ctx, "callPreCommandHooks", &details)
259 260 261
	log.Debug("Calling pre-command hooks...")

	// some hooks only run when the command is executed locally
262
	daemon, err := commandShouldRunOnDaemon(details, req, root)
263 264 265 266 267 268 269
	if err != nil {
		return err
	}

	// check for updates when 1) commands is going to be run locally, 2) the
	// command does not initialize the config, and 3) the command does not
	// pre-empt updates
270
	if !daemon && details.usesConfigAsInput() && details.doesNotPreemptAutoUpdate() {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

		log.Debug("Calling hook: Check for updates")

		cfg, err := req.Context().GetConfig()
		if err != nil {
			return err
		}
		// Check for updates and potentially install one.
		if err := updates.CliCheckForUpdates(cfg, req.Context().ConfigRoot); err != nil {
			return err
		}
	}

	return nil
}

287
func callCommand(ctx context.Context, req cmds.Request, root *cmds.Command, cmd *cmds.Command) (cmds.Response, error) {
288
	var res cmds.Response
289

290 291 292 293 294
	details, err := commandDetails(req.Path(), root)
	if err != nil {
		return nil, err
	}

295
	log.Info("looking for running daemon...")
296
	useDaemon, err := commandShouldRunOnDaemon(*details, req, root)
297 298 299
	if err != nil {
		return nil, err
	}
300

301
	err = callPreCommandHooks(ctx, *details, req, root)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
302 303 304
	if err != nil {
		return nil, err
	}
305

306 307 308 309 310 311 312
	if cmd.PreRun != nil {
		err = cmd.PreRun(req)
		if err != nil {
			return nil, err
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
313
	if useDaemon {
314

315 316 317 318 319
		cfg, err := req.Context().GetConfig()
		if err != nil {
			return nil, err
		}

320 321 322 323
		addr, err := ma.NewMultiaddr(cfg.Addresses.API)
		if err != nil {
			return nil, err
		}
324

325
		log.Infof("Executing command on daemon running at %s", addr)
326 327 328 329
		_, host, err := manet.DialArgs(addr)
		if err != nil {
			return nil, err
		}
330

331
		client := cmdsHttp.NewClient(host)
332

333 334 335 336
		res, err = client.Send(req)
		if err != nil {
			return nil, err
		}
337

338
	} else {
339
		log.Info("Executing command locally")
340

341 342
		// Okay!!!!! NOW we can call the command.
		res = root.Call(req)
343 344

	}
345 346

	if cmd.PostRun != nil {
347
		cmd.PostRun(req, res)
348 349
	}

350
	return res, nil
351 352
}

353 354 355 356 357
// 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) {
358 359 360 361 362 363 364
	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
365
			return nil, debugerror.Errorf("subcommand %s should be in root", cmp)
366
		}
367

368 369 370
		if cmdDetails, found := cmdDetailsMap[cmd]; found {
			details = cmdDetails
		}
371
	}
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	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
	}
387 388 389 390 391

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

392
	if details.doesNotUseRepo && details.canRunOnClient() {
393 394 395 396 397
		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.
398
	daemonLocked := fsrepo.LockedByOtherProcess(req.Context().ConfigRoot)
399 400 401

	if daemonLocked {

402 403
		log.Info("a daemon is running...")

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
		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
419
func isClientError(err error) bool {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
420 421 422 423

	// 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
424
	// cast to cmds.Error
Brian Tiger Chow's avatar
Brian Tiger Chow committed
425 426 427 428 429
	switch e := err.(type) {
	case *cmds.Error:
		return e.Code == cmds.ErrClient
	case cmds.Error:
		return e.Code == cmds.ErrClient
430
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
431
	return false
432 433 434
}

func getConfigRoot(req cmds.Request) (string, error) {
435
	configOpt, found, err := req.Option("config").String()
436 437 438
	if err != nil {
		return "", err
	}
439
	if found && configOpt != "" {
440
		return configOpt, nil
441 442 443 444 445 446 447 448 449
	}

	configPath, err := config.PathRoot()
	if err != nil {
		return "", err
	}
	return configPath, nil
}

450
func loadConfig(path string) (*config.Config, error) {
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
451
	return fsrepo.ConfigAt(path)
452
}
453

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
// 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
}

476 477 478
func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
479
		return err
480
	}
481
	defer mprof.Close() // _after_ writing the heap profile
482 483
	return pprof.WriteHeapProfile(mprof)
}
484

Matt Bell's avatar
Matt Bell committed
485
// listen for and handle SIGTERM
486 487 488 489
func (i *cmdInvocation) setupInterruptHandler() {

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

	go func() {
492
		// first time, try to shut down.
493

494 495
		// loop because we may be
		for count := 0; ; count++ {
496 497 498
			<-sig

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

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

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

func allInterruptSignals() chan os.Signal {
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGHUP, syscall.SIGINT,
Jeromy's avatar
Jeromy committed
524
		syscall.SIGTERM)
525 526
	return sigc
}