main.go 12.2 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
// cmd/ipfs implements the primary CLI binary for ipfs
2 3 4
package main

import (
5
	"context"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
6
	"errors"
7 8
	"fmt"
	"io"
9
	"math/rand"
10
	"os"
Matt Bell's avatar
Matt Bell committed
11
	"os/signal"
12
	"path/filepath"
13
	"runtime/pprof"
14
	"strings"
15
	"sync"
16
	"syscall"
17
	"time"
18

19
	oldcmds "github.com/ipfs/go-ipfs/commands"
20
	core "github.com/ipfs/go-ipfs/core"
21
	coreCmds "github.com/ipfs/go-ipfs/core/commands"
keks's avatar
keks committed
22
	corehttp "github.com/ipfs/go-ipfs/core/corehttp"
keks's avatar
keks committed
23
	loader "github.com/ipfs/go-ipfs/plugin/loader"
24
	repo "github.com/ipfs/go-ipfs/repo"
25 26
	config "github.com/ipfs/go-ipfs/repo/config"
	fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
27

Steven Allen's avatar
Steven Allen committed
28 29
	u "gx/ipfs/QmNiJuT8Ja3hMVpBHXv3Q6dwmperaQ6JjLtpMQgMCD7xvx/go-ipfs-util"
	manet "gx/ipfs/QmRK2LxanhK2gZq6k6R7vk5ZoYZk8ULSSTB7FzDsMUX6CB/go-multiaddr-net"
Steven Allen's avatar
Steven Allen committed
30
	logging "gx/ipfs/QmRb5jh8z2E8hMGN2tkvs1yHynUanqnZ3UeKwgN1i9P1F8/go-log"
Steven Allen's avatar
Steven Allen committed
31
	ma "gx/ipfs/QmWWQ2Txc2c6tqjsBpzg5Ar652cHPGNsQQp2SejkNmkUMb/go-multiaddr"
32
	osh "gx/ipfs/QmXuBJ7DR6k3rmUEKtvVMhwjmXDuJgXXPUt4LQXKBMsU93/go-os-helper"
Steven Allen's avatar
Steven Allen committed
33
	loggables "gx/ipfs/Qmf9JgVLz46pxPXwG2eWSJpkqVCcjD4rp7zCRi2KP6GTNB/go-libp2p-loggables"
34 35 36
	"gx/ipfs/QmfAkMSt9Fwzk48QDJecPcwCUjnf2uG7MLnmCGTp4C6ouL/go-ipfs-cmds"
	"gx/ipfs/QmfAkMSt9Fwzk48QDJecPcwCUjnf2uG7MLnmCGTp4C6ouL/go-ipfs-cmds/cli"
	"gx/ipfs/QmfAkMSt9Fwzk48QDJecPcwCUjnf2uG7MLnmCGTp4C6ouL/go-ipfs-cmds/http"
37 38
)

39
// log is the command logger
Jeromy's avatar
Jeromy committed
40
var log = logging.Logger("cmd/ipfs")
41

42
var errRequestCanceled = errors.New("request canceled")
43

44
const (
45 46 47
	EnvEnableProfiling = "IPFS_PROF"
	cpuProfile         = "ipfs.cpuprof"
	heapProfile        = "ipfs.memprof"
48
)
49

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51
// main roadmap:
// - parse the commandline to get a cmdInvocation
52
// - if user requests help, print it and exit.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54 55
// - run the command invocation
// - output the response
// - if anything fails, print error, maybe with help
56
func main() {
57 58 59 60
	os.Exit(mainRet())
}

func mainRet() int {
61
	rand.Seed(time.Now().UnixNano())
62
	ctx := logging.ContextWithLoggable(context.Background(), loggables.Uuid("session"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63 64 65 66 67 68 69 70
	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())
	}

71 72 73
	stopFunc, err := profileIfEnabled()
	if err != nil {
		printErr(err)
74
		return 1
75 76 77
	}
	defer stopFunc() // to be executed as late as possible

keks's avatar
keks committed
78 79
	intrh, ctx := setupInterruptHandler(ctx)
	defer intrh.Close()
80

Etienne Laurin's avatar
Etienne Laurin committed
81
	// Handle `ipfs help'
82 83
	if len(os.Args) == 2 {
		if os.Args[1] == "help" {
keks's avatar
keks committed
84
			os.Args[1] = "-h"
85 86 87
		} else if os.Args[1] == "--version" {
			os.Args[1] = "version"
		}
Etienne Laurin's avatar
Etienne Laurin committed
88 89
	}

90 91 92 93
	// output depends on excecutable name passed in os.Args
	// so we need to make sure it's stable
	os.Args[0] = "ipfs"

Jeromy's avatar
Jeromy committed
94
	buildEnv := func(ctx context.Context, req *cmds.Request) (cmds.Environment, error) {
keks's avatar
keks committed
95
		repoPath, err := getRepoPath(req)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
		if err != nil {
keks's avatar
keks committed
97
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98
		}
keks's avatar
keks committed
99
		log.Debugf("config path is %s", repoPath)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100

keks's avatar
keks committed
101 102 103 104 105 106 107 108 109 110
		// this sets up the function that will initialize the node
		// this is so that we can construct the node lazily.
		return &oldcmds.Context{
			ConfigRoot: repoPath,
			LoadConfig: loadConfig,
			ReqLog:     &oldcmds.ReqLog{},
			ConstructNode: func() (n *core.IpfsNode, err error) {
				if req == nil {
					return nil, errors.New("constructing node without a request")
				}
Etienne Laurin's avatar
Etienne Laurin committed
111

keks's avatar
keks committed
112 113 114 115
				r, err := fsrepo.Open(repoPath)
				if err != nil { // repo is owned by the node
					return nil, err
				}
Jan Winkelmann's avatar
Jan Winkelmann committed
116

keks's avatar
keks committed
117 118 119 120 121 122 123 124
				// ok everything is good. set it on the invocation (for ownership)
				// and return it.
				n, err = core.NewNode(ctx, &core.BuildCfg{
					Repo: r,
				})
				if err != nil {
					return nil, err
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125

keks's avatar
keks committed
126 127 128 129 130 131 132 133
				n.SetLocal(true)
				return n, nil
			},
		}, nil
	}

	err = cli.Run(ctx, Root, os.Args, os.Stdin, os.Stdout, os.Stderr, buildEnv, makeExecutor)
	if err != nil {
134
		return 1
Brian Tiger Chow's avatar
Brian Tiger Chow committed
135 136
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	// everything went better than expected :)
138
	return 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140
}

keks's avatar
keks committed
141
func checkDebug(req *cmds.Request) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142
	// check if user wants to debug. option OR env var.
keks's avatar
keks committed
143
	debug, _ := req.Options["debug"].(bool)
144
	if debug || os.Getenv("IPFS_LOGGING") == "debug" {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
145
		u.Debug = true
Jeromy's avatar
Jeromy committed
146
		logging.SetDebugLogging()
147
	}
148 149 150
	if u.GetenvBool("DEBUG") {
		u.Debug = true
	}
151 152
}

keks's avatar
keks committed
153 154 155
func makeExecutor(req *cmds.Request, env interface{}) (cmds.Executor, error) {
	checkDebug(req)
	details, err := commandDetails(req.Path, Root)
156
	if err != nil {
keks's avatar
keks committed
157
		return nil, err
158
	}
159

Łukasz Magiera's avatar
Łukasz Magiera committed
160
	client, err := commandShouldRunOnDaemon(*details, req, env.(*oldcmds.Context))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
	if err != nil {
keks's avatar
keks committed
162
		return nil, err
Jan Winkelmann's avatar
Jan Winkelmann committed
163 164
	}

keks's avatar
keks committed
165 166 167
	var exctr cmds.Executor
	if client != nil && !req.Command.External {
		exctr = client.(cmds.Executor)
168
	} else {
169 170 171 172 173 174 175 176 177 178 179 180
		cctx := env.(*oldcmds.Context)
		pluginpath := filepath.Join(cctx.ConfigRoot, "plugins")

		// check if repo is accessible before loading plugins
		ok, err := checkPermissions(cctx.ConfigRoot)
		if err != nil {
			return nil, err
		}
		if ok {
			if _, err := loader.LoadPlugins(pluginpath); err != nil {
				log.Warning("error loading plugins: ", err)
			}
181 182
		}

keks's avatar
keks committed
183
		exctr = cmds.NewExecutor(req.Root)
184 185
	}

keks's avatar
keks committed
186
	return exctr, nil
187 188
}

189 190 191 192 193 194 195 196 197 198 199 200 201 202
func checkPermissions(path string) (bool, error) {
	_, err := os.Open(path)
	if os.IsNotExist(err) {
		// repo does not exist yet - don't load plugins, but also don't fail
		return false, nil
	}
	if os.IsPermission(err) {
		// repo is not accessible. error out.
		return false, fmt.Errorf("error opening repository at %s: permission denied", path)
	}

	return true, nil
}

203 204 205 206 207
// 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) {
208 209 210 211
	var details cmdDetails
	// find the last command in path that has a cmdDetailsMap entry
	cmd := root
	for _, cmp := range path {
212
		cmd = cmd.Subcommands[cmp]
Jan Winkelmann's avatar
Jan Winkelmann committed
213
		if cmd == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214
			return nil, fmt.Errorf("subcommand %s should be in root", cmp)
215
		}
216

Jan Winkelmann's avatar
Jan Winkelmann committed
217
		if cmdDetails, found := cmdDetailsMap[strings.Join(path, "/")]; found {
218 219
			details = cmdDetails
		}
220
	}
221 222 223 224
	return &details, nil
}

// commandShouldRunOnDaemon determines, from commmand details, whether a
225
// command ought to be executed on an ipfs daemon.
226
//
227
// It returns a client if the command should be executed on a daemon and nil if
228 229
// it should be executed on a client. It returns an error if the command must
// NOT be executed on either.
Łukasz Magiera's avatar
Łukasz Magiera committed
230
func commandShouldRunOnDaemon(details cmdDetails, req *cmds.Request, cctx *oldcmds.Context) (http.Client, error) {
231
	path := req.Path
232 233
	// root command.
	if len(path) < 1 {
234
		return nil, nil
235
	}
236 237

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

241
	if details.doesNotUseRepo && details.canRunOnClient() {
242
		return nil, nil
243 244
	}

245 246 247 248
	// at this point need to know whether api is running. we defer
	// to this point so that we dont check unnecessarily

	// did user specify an api to use for this command?
249
	apiAddrStr, _ := req.Options[coreCmds.ApiOption].(string)
250

251
	client, err := getApiClient(cctx.ConfigRoot, apiAddrStr)
252
	if err == repo.ErrApiNotRunning {
253
		if apiAddrStr != "" && req.Command != daemonCmd {
254 255 256 257
			// if user SPECIFIED an api, and this cmd is not daemon
			// we MUST use it. so error out.
			return nil, err
		}
258

259 260 261 262
		// ok for api not to be running
	} else if err != nil { // some other api error
		return nil, err
	}
263

michael's avatar
michael committed
264
	if client != nil {
265
		if details.cannotRunOnDaemon {
266
			// check if daemon locked. legacy error text, for now.
michael's avatar
michael committed
267
			log.Debugf("Command cannot run on daemon. Checking if daemon is locked")
268
			if daemonLocked, _ := fsrepo.LockedByOtherProcess(cctx.ConfigRoot); daemonLocked {
rht's avatar
rht committed
269
				return nil, cmds.ClientError("ipfs daemon is running. please stop it to run this command")
270
			}
rht's avatar
rht committed
271
			return nil, nil
272 273
		}

274
		return client, nil
275 276 277
	}

	if details.cannotRunOnClient {
278
		return nil, cmds.ClientError("must run on the ipfs daemon")
279 280
	}

281
	return nil, nil
282 283
}

284 285
func getRepoPath(req *cmds.Request) (string, error) {
	repoOpt, found := req.Options["config"].(string)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
286 287
	if found && repoOpt != "" {
		return repoOpt, nil
288 289
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
290
	repoPath, err := fsrepo.BestKnownPath()
291 292 293
	if err != nil {
		return "", err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
294
	return repoPath, nil
295 296
}

297
func loadConfig(path string) (*config.Config, error) {
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
298
	return fsrepo.ConfigAt(path)
299
}
300

301 302 303 304 305 306 307 308 309
// 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)
310
	go func() {
311
		for range time.NewTicker(time.Second * 30).C {
312 313
			err := writeHeapProfileToFile()
			if err != nil {
rht's avatar
rht committed
314
				log.Error(err)
315 316 317
			}
		}
	}()
318 319 320 321 322 323 324 325

	stopProfiling := func() {
		pprof.StopCPUProfile()
		defer ofi.Close() // captured by the closure
	}
	return stopProfiling, nil
}

326 327 328
func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
329
		return err
330
	}
331
	defer mprof.Close() // _after_ writing the heap profile
332 333
	return pprof.WriteHeapProfile(mprof)
}
334

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
// IntrHandler helps set up an interrupt handler that can
// be cleanly shut down through the io.Closer interface.
type IntrHandler struct {
	sig chan os.Signal
	wg  sync.WaitGroup
}

func NewIntrHandler() *IntrHandler {
	ih := &IntrHandler{}
	ih.sig = make(chan os.Signal, 1)
	return ih
}

func (ih *IntrHandler) Close() error {
	close(ih.sig)
	ih.wg.Wait()
	return nil
}
353

354 355 356 357 358 359 360 361
// Handle starts handling the given signals, and will call the handler
// callback function each time a signal is catched. The function is passed
// the number of times the handler has been triggered in total, as
// well as the handler itself, so that the handling logic can use the
// handler's wait group to ensure clean shutdown when Close() is called.
func (ih *IntrHandler) Handle(handler func(count int, ih *IntrHandler), sigs ...os.Signal) {
	signal.Notify(ih.sig, sigs...)
	ih.wg.Add(1)
Matt Bell's avatar
Matt Bell committed
362
	go func() {
363 364
		defer ih.wg.Done()
		count := 0
365
		for range ih.sig {
366 367 368 369 370 371 372
			count++
			handler(count, ih)
		}
		signal.Stop(ih.sig)
	}()
}

keks's avatar
keks committed
373
func setupInterruptHandler(ctx context.Context) (io.Closer, context.Context) {
374
	intrh := NewIntrHandler()
375 376
	ctx, cancelFunc := context.WithCancel(ctx)

377 378 379
	handlerFunc := func(count int, ih *IntrHandler) {
		switch count {
		case 1:
380
			fmt.Println() // Prevent un-terminated ^C character in terminal
381 382 383 384

			ih.wg.Add(1)
			go func() {
				defer ih.wg.Done()
385
				cancelFunc()
386
			}()
387

388 389 390
		default:
			fmt.Println("Received another interrupt before graceful shutdown, terminating...")
			os.Exit(-1)
Matt Bell's avatar
Matt Bell committed
391
		}
392 393 394
	}

	intrh.Handle(handlerFunc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
395

396
	return intrh, ctx
397
}
398 399 400 401

func profileIfEnabled() (func(), error) {
	// FIXME this is a temporary hack so profiling of asynchronous operations
	// works as intended.
402
	if os.Getenv(EnvEnableProfiling) != "" {
403 404 405 406 407 408 409 410
		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
}
411

412 413 414 415
var apiFileErrorFmt string = `Failed to parse '%[1]s/api' file.
	error: %[2]s
If you're sure go-ipfs isn't running, you can just delete it.
`
416 417
var checkIPFSUnixFmt = "Otherwise check:\n\tps aux | grep ipfs"
var checkIPFSWinFmt = "Otherwise check:\n\ttasklist | findstr ipfs"
418

419 420 421
// getApiClient checks the repo, and the given options, checking for
// a running API service. if there is one, it returns a client.
// otherwise, it returns errApiNotRunning, or another error.
Jan Winkelmann's avatar
Jan Winkelmann committed
422
func getApiClient(repoPath, apiAddrStr string) (http.Client, error) {
423 424 425 426 427 428 429 430 431
	var apiErrorFmt string
	switch {
	case osh.IsUnix():
		apiErrorFmt = apiFileErrorFmt + checkIPFSUnixFmt
	case osh.IsWindows():
		apiErrorFmt = apiFileErrorFmt + checkIPFSWinFmt
	default:
		apiErrorFmt = apiFileErrorFmt
	}
432

433 434 435 436 437 438 439 440
	var addr ma.Multiaddr
	var err error
	if len(apiAddrStr) != 0 {
		addr, err = ma.NewMultiaddr(apiAddrStr)
		if err != nil {
			return nil, err
		}
		if len(addr.Protocols()) == 0 {
Lars Gierth's avatar
Lars Gierth committed
441
			return nil, fmt.Errorf("multiaddr doesn't provide any protocols")
442 443 444 445
		}
	} else {
		addr, err = fsrepo.APIAddr(repoPath)
		if err == repo.ErrApiNotRunning {
446 447 448
			return nil, err
		}

449 450 451 452 453 454
		if err != nil {
			return nil, fmt.Errorf(apiErrorFmt, repoPath, err.Error())
		}
	}
	if len(addr.Protocols()) == 0 {
		return nil, fmt.Errorf(apiErrorFmt, repoPath, "multiaddr doesn't provide any protocols")
455
	}
rht's avatar
rht committed
456
	return apiClientForAddr(addr)
457 458
}

Jan Winkelmann's avatar
Jan Winkelmann committed
459
func apiClientForAddr(addr ma.Multiaddr) (http.Client, error) {
460 461 462 463 464
	_, host, err := manet.DialArgs(addr)
	if err != nil {
		return nil, err
	}

keks's avatar
keks committed
465
	return http.NewClient(host, http.ClientWithAPIPrefix(corehttp.APIPath)), nil
466
}