main.go 12.4 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
	"strings"
13
	"syscall"
14
	"time"
15

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

19
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
20 21 22
	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
23
	core "github.com/jbenet/go-ipfs/core"
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"
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 82 83 84 85 86
	// 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
87
	// parse the commandline into a command invocation
88
	parseErr := invoc.Parse(ctx, os.Args[1:])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89 90 91

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

104 105 106 107
	// 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
108
		printHelp(false, os.Stdout)
109 110 111 112
		os.Exit(0)
	}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126
	// ok, finally, run the command invocation.
127
	output, err := invoc.Run(ctx)
128
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130 131 132
		printErr(err)

		// if this error was a client error, print short help too.
		if isClientError(err) {
133
			printMetaHelp(os.Stderr)
134
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135
		os.Exit(1)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
136 137
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138 139 140 141
	// everything went better than expected :)
	io.Copy(os.Stdout, output)
}

142
func (i *cmdInvocation) Run(ctx context.Context) (output io.Reader, err error) {
143 144
	// setup our global interrupt handler.
	i.setupInterruptHandler()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145 146 147

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

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

166
	res, err := callCommand(ctx, i.req, Root, i.cmd)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
167
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168
		return nil, err
169
	}
170

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

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

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

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

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

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

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

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248
	return nil
249 250
}

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

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

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

	return nil
}

271
func callCommand(ctx context.Context, req cmds.Request, root *cmds.Command, cmd *cmds.Command) (cmds.Response, error) {
272
	log.Info(config.EnvDir, req.Context().ConfigRoot)
273
	var res cmds.Response
274

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
298
	if useDaemon {
299

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

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

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

316
		client := cmdsHttp.NewClient(host)
317

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

323
	} else {
324
		log.Info("Executing command locally")
325

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

	}
330 331

	if cmd.PostRun != nil {
332
		cmd.PostRun(req, res)
333 334
	}

335
	return res, nil
336 337
}

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

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

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

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

	if daemonLocked {

387 388
		log.Info("a daemon is running...")

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

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

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

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

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

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

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

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

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

	go func() {
477
		// first time, try to shut down.
478

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
483 484
			// TODO cancel the command context instead

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

492 493 494 495 496 497 498 499 500 501 502 503
			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
504 505 506
		}
	}()
}
507 508 509 510

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