main.go 13 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
	repo "github.com/jbenet/go-ipfs/repo"
24
	config "github.com/jbenet/go-ipfs/repo/config"
25
	fsrepo "github.com/jbenet/go-ipfs/repo/fsrepo"
26
	eventlog "github.com/jbenet/go-ipfs/thirdparty/eventlog"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
	updates "github.com/jbenet/go-ipfs/updates"
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
	cpuProfile  = "ipfs.cpuprof"
	heapProfile = "ipfs.memprof"
41 42
	errorFormat = "ERROR: %v\n\n"
)
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 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())
	}

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

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

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

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

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

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

		// 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
116
			printHelp(false, os.Stderr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
118 119
		os.Exit(1)
	}
Matt Bell's avatar
Matt Bell committed
120

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
	// ok, finally, run the command invocation.
122
	output, err := invoc.Run(ctx)
123
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125 126 127
		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
128
			printHelp(false, os.Stderr)
129
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
		os.Exit(1)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
131 132
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245 246
func (i *cmdInvocation) requestedHelp() (short bool, long bool, err error) {
	longHelp, _, err := i.req.Option("help").Bool()
247
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248
		return false, false, err
249
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250
	shortHelp, _, err := i.req.Option("h").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
	return longHelp, shortHelp, nil
255
}
256

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

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

	// some hooks only run when the command is executed locally
263
	daemon, err := commandShouldRunOnDaemon(details, req, root)
264 265 266 267 268 269 270
	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
271
	if !daemon && details.usesConfigAsInput() && details.doesNotPreemptAutoUpdate() {
272 273 274 275 276 277 278 279 280 281 282 283 284

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

285 286
	// When the upcoming command may use the config and repo, we know it's safe
	// for the log config hook to touch the config/repo
287
	if repo.IsInitialized(req.Context().ConfigRoot) {
288 289 290 291 292
		log.Debug("Calling hook: Configure Event Logger")
		cfg, err := req.Context().GetConfig()
		if err != nil {
			return err
		}
293
		repo.ConfigureEventLogger(cfg.Logs)
294 295
	}

296 297 298
	return nil
}

299
func callCommand(ctx context.Context, req cmds.Request, root *cmds.Command) (cmds.Response, error) {
300
	var res cmds.Response
301

302 303 304 305 306
	details, err := commandDetails(req.Path(), root)
	if err != nil {
		return nil, err
	}

307
	log.Info("looking for running daemon...")
308
	useDaemon, err := commandShouldRunOnDaemon(*details, req, root)
309 310 311
	if err != nil {
		return nil, err
	}
312

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
318
	if useDaemon {
319

320 321 322 323 324
		cfg, err := req.Context().GetConfig()
		if err != nil {
			return nil, err
		}

325 326 327 328
		addr, err := ma.NewMultiaddr(cfg.Addresses.API)
		if err != nil {
			return nil, err
		}
329

330
		log.Infof("Executing command on daemon running at %s", addr)
331 332 333 334
		_, host, err := manet.DialArgs(addr)
		if err != nil {
			return nil, err
		}
335

336
		client := cmdsHttp.NewClient(host)
337

338 339 340 341
		res, err = client.Send(req)
		if err != nil {
			return nil, err
		}
342

343
	} else {
344
		log.Info("Executing command locally")
345

346 347
		// Okay!!!!! NOW we can call the command.
		res = root.Call(req)
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
}