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

import (
4
	"errors"
5 6 7
	"fmt"
	"io"
	"os"
Matt Bell's avatar
Matt Bell committed
8
	"os/signal"
9 10
	"runtime/pprof"

11
	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-logging"
12 13 14
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net"

15 16 17
	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
18 19
	config "github.com/jbenet/go-ipfs/config"
	core "github.com/jbenet/go-ipfs/core"
20
	daemon "github.com/jbenet/go-ipfs/daemon2"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21
	updates "github.com/jbenet/go-ipfs/updates"
22 23 24 25 26 27
	u "github.com/jbenet/go-ipfs/util"
)

// log is the command logger
var log = u.Logger("cmd/ipfs")

28 29 30
// signal to output help
var errHelpRequested = errors.New("Help Requested")

31
const (
32 33
	cpuProfile  = "ipfs.cpuprof"
	heapProfile = "ipfs.memprof"
34 35
	errorFormat = "ERROR: %v\n\n"
)
36

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37 38 39 40 41 42 43 44 45 46 47 48
type cmdInvocation struct {
	path []string
	cmd  *cmds.Command
	req  cmds.Request
}

// 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
49
func main() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	var invoc cmdInvocation
	var err error

	// 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.
	printHelp := func(long bool) {
		helpFunc := cmdsCli.ShortHelp
		if long {
			helpFunc = cmdsCli.LongHelp
		}

Matt Bell's avatar
Matt Bell committed
67
		helpFunc("ipfs", Root, invoc.path, os.Stderr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69 70
	}

	// parse the commandline into a command invocation
71
	parseErr := invoc.Parse(os.Args[1:])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
72 73 74

	// BEFORE handling the parse error, if we have enough information
	// AND the user requested help, print it out and exit
75
	if invoc.req != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76 77 78 79 80 81 82 83 84 85 86
		longH, shortH, err := invoc.requestedHelp()
		if err != nil {
			printErr(err)
			os.Exit(1)
		}
		if longH || shortH {
			printHelp(longH)
			os.Exit(0)
		}
	}

87 88 89 90 91 92 93 94 95
	// 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 {
		printHelp(false)
		os.Exit(0)
	}

	// ok now handle parse error (which means cli input was wrong,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
	// e.g. incorrect number of args, or nonexistent subcommand)
97 98
	if parseErr != nil {
		printErr(parseErr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99 100 101 102 103 104 105

		// this was a user error, print help.
		if invoc.cmd != nil {
			// we need a newline space.
			fmt.Fprintf(os.Stderr, "\n")
			printHelp(false)
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
106 107
		os.Exit(1)
	}
Matt Bell's avatar
Matt Bell committed
108

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110
	// ok, finally, run the command invocation.
	output, err := invoc.Run()
111
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113 114 115 116
		printErr(err)

		// if this error was a client error, print short help too.
		if isClientError(err) {
			printHelp(false)
117
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
		os.Exit(1)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
119 120
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121 122 123 124 125 126 127 128 129
	// everything went better than expected :)
	io.Copy(os.Stdout, output)
}

func (i *cmdInvocation) Run() (output io.Reader, err error) {
	handleInterrupt()

	// 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
130
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
		return nil, err
Brian Tiger Chow's avatar
Brian Tiger Chow committed
132
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133
	if debug || u.GetenvBool("DEBUG") {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
134 135
		u.Debug = true
		u.SetAllLoggers(logging.DEBUG)
136
	}
137

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138 139
	// if debugging, let's profile.
	// TODO maybe change this to its own option... profiling makes it slower.
140
	if u.Debug {
141
		stopProfilingFunc, err := startProfiling()
142
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
			return nil, err
144
		}
145
		defer stopProfilingFunc() // to be executed as late as possible
146
	}
147

Matt Bell's avatar
Matt Bell committed
148
	res, err := callCommand(i.req, Root)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
149
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150
		return nil, err
151
	}
152

153 154 155 156
	if err := res.Error(); err != nil {
		return nil, err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
	return res.Reader()
158
}
159

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160 161
func (i *cmdInvocation) Parse(args []string) error {
	var err error
162

163
	i.req, i.cmd, i.path, err = cmdsCli.Parse(args, os.Stdin, Root)
164
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165
		return err
166 167
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168
	configPath, err := getConfigRoot(i.req)
169
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170
		return err
171 172
	}

173
	// this sets up the function that will initialize the config lazily.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174
	ctx := i.req.Context()
175
	ctx.ConfigRoot = configPath
176
	ctx.LoadConfig = loadConfig
177

178 179
	// 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
180
	if !i.req.Option("encoding").Found() {
181
		if i.req.Command().Marshalers != nil && i.req.Command().Marshalers[cmds.Text] != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
			i.req.SetOption("encoding", cmds.Text)
183
		} else {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
184
			i.req.SetOption("encoding", cmds.JSON)
185 186 187
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
	return nil
189 190
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191 192
func (i *cmdInvocation) requestedHelp() (short bool, long bool, err error) {
	longHelp, _, err := i.req.Option("help").Bool()
193
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
		return false, false, err
195
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196
	shortHelp, _, err := i.req.Option("h").Bool()
197
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198
		return false, false, err
199
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200
	return longHelp, shortHelp, nil
201
}
202

203
func callCommand(req cmds.Request, root *cmds.Command) (cmds.Response, error) {
204
	var res cmds.Response
205

206
	useDaemon, err := commandShouldRunOnDaemon(req, root)
207 208 209
	if err != nil {
		return nil, err
	}
210

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211 212 213 214
	cfg, err := req.Context().GetConfig()
	if err != nil {
		return nil, err
	}
215

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
	if useDaemon {
217

218 219 220 221
		addr, err := ma.NewMultiaddr(cfg.Addresses.API)
		if err != nil {
			return nil, err
		}
222

223
		log.Infof("Executing command on daemon running at %s", addr)
224 225 226 227
		_, host, err := manet.DialArgs(addr)
		if err != nil {
			return nil, err
		}
228

229
		client := cmdsHttp.NewClient(host)
230

231 232 233 234
		res, err = client.Send(req)
		if err != nil {
			return nil, err
		}
235

236
	} else {
237
		log.Info("Executing command locally")
238

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239 240 241 242 243
		// Check for updates and potentially install one.
		if err := updates.CliCheckForUpdates(cfg, req.Context().ConfigRoot); err != nil {
			return nil, err
		}

244 245 246 247 248
		// this sets up the function that will initialize the node
		// this is so that we can construct the node lazily.
		ctx := req.Context()
		ctx.ConstructNode = func() (*core.IpfsNode, error) {
			cfg, err := ctx.GetConfig()
249
			if err != nil {
250
				return nil, err
251
			}
252 253 254 255 256
			return core.NewIpfsNode(cfg, false)
		}

		// Okay!!!!! NOW we can call the command.
		res = root.Call(req)
257

258 259 260 261 262 263
		// 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.
		node := req.Context().NodeWithoutConstructing()
		if node != nil {
			node.Close()
264 265
		}
	}
266
	return res, nil
267 268
}

269 270 271 272 273 274 275
func commandShouldRunOnDaemon(req cmds.Request, root *cmds.Command) (bool, error) {
	path := req.Path()
	// root command.
	if len(path) < 1 {
		return false, nil
	}

276 277 278 279 280 281 282 283 284
	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 {
			return false, fmt.Errorf("subcommand %s should be in root", cmp)
		}
285

286 287 288
		if cmdDetails, found := cmdDetailsMap[cmd]; found {
			details = cmdDetails
		}
289
	}
290
	log.Debugf("cmd perms for +%v: %s", path, details.String())
291 292 293 294 295

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

296
	if details.doesNotUseRepo && details.canRunOnClient() {
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
		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.
	daemonLocked := daemon.Locked(req.Context().ConfigRoot)
	log.Info("Daemon is running.")

	if daemonLocked {

		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
322
func isClientError(err error) bool {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
323 324 325 326

	// 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
327
	// cast to cmds.Error
Brian Tiger Chow's avatar
Brian Tiger Chow committed
328 329 330 331 332
	switch e := err.(type) {
	case *cmds.Error:
		return e.Code == cmds.ErrClient
	case cmds.Error:
		return e.Code == cmds.ErrClient
333
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
334
	return false
335 336 337
}

func getConfigRoot(req cmds.Request) (string, error) {
338
	configOpt, found, err := req.Option("config").String()
339 340 341
	if err != nil {
		return "", err
	}
342
	if found && configOpt != "" {
343
		return configOpt, nil
344 345 346 347 348 349 350 351 352
	}

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

353
func loadConfig(path string) (*config.Config, error) {
354 355 356 357 358 359 360
	configFile, err := config.Filename(path)
	if err != nil {
		return nil, err
	}

	return config.Load(configFile)
}
361

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
// 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
}

384 385 386
func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
387
		return err
388
	}
389
	defer mprof.Close() // _after_ writing the heap profile
390 391
	return pprof.WriteHeapProfile(mprof)
}
392

Matt Bell's avatar
Matt Bell committed
393 394 395 396 397 398 399 400
// listen for and handle SIGTERM
func handleInterrupt() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	go func() {
		for _ = range c {
			log.Info("Received interrupt signal, terminating...")
401
			os.Exit(0)
Matt Bell's avatar
Matt Bell committed
402 403 404
		}
	}()
}