main.go 6.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 18 19 20 21 22 23 24 25 26 27
	cmds "github.com/jbenet/go-ipfs/commands"
	cmdsCli "github.com/jbenet/go-ipfs/commands/cli"
	cmdsHttp "github.com/jbenet/go-ipfs/commands/http"
	"github.com/jbenet/go-ipfs/config"
	"github.com/jbenet/go-ipfs/core"
	commands "github.com/jbenet/go-ipfs/core/commands2"
	daemon "github.com/jbenet/go-ipfs/daemon2"
	u "github.com/jbenet/go-ipfs/util"
)

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

28
const (
29 30
	cpuProfile  = "ipfs.cpuprof"
	heapProfile = "ipfs.memprof"
31 32
	errorFormat = "ERROR: %v\n\n"
)
33

34
func main() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
35 36 37 38 39 40 41 42
	err := run()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func run() error {
Matt Bell's avatar
Matt Bell committed
43 44
	handleInterrupt()

45
	args := os.Args[1:]
46 47
	req, root, err := createRequest(args)
	if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
48 49 50 51 52 53 54 55 56 57
		return err
	}

	debug, err := req.Option("debug").Bool()
	if err != nil {
		return err
	}
	if debug {
		u.Debug = true
		u.SetAllLoggers(logging.DEBUG)
58
	}
59 60

	if u.Debug {
61
		stopProfilingFunc, err := startProfiling()
62
		if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
63
			return err
64
		}
65
		defer stopProfilingFunc() // to be executed as late as possible
66
	}
67

Brian Tiger Chow's avatar
Brian Tiger Chow committed
68 69 70 71 72 73 74 75
	helpTextDisplayed, err := handleHelpOption(req, root)
	if err != nil {
		return err
	}
	if helpTextDisplayed {
		return nil
	}

76 77 78 79
	res, err := callCommand(req, root)
	if err != nil {
		return err
	}
80 81 82 83 84

	err = outputResponse(res, root)
	if err != nil {
		return err
	}
85

Brian Tiger Chow's avatar
Brian Tiger Chow committed
86
	return nil
87
}
88

89
func createRequest(args []string) (cmds.Request, *cmds.Command, error) {
90 91 92 93
	req, root, cmd, path, err := cmdsCli.Parse(args, Root, commands.Root)

	// handle parse error (which means the commandline input was wrong,
	// e.g. incorrect number of args, or nonexistent subcommand)
94
	if err != nil {
95
		// if the -help flag wasn't specified, show the error message
96 97
		// or if a path was returned (user specified a valid subcommand), show the error message
		// (this means there was an option or argument error)
98
		if path != nil && len(path) > 0 {
99
			help, _ := req.Option("help").Bool()
100 101 102
			if !help {
				fmt.Printf(errorFormat, err)
			}
103 104 105
		}

		if cmd == nil {
Matt Bell's avatar
Matt Bell committed
106
			root = commands.Root
107 108 109
		}

		// generate the help text for the command the user was trying to call (or root)
110
		htErr := cmdsCli.LongHelp("ipfs", root, path, os.Stdout)
111 112
		if htErr != nil {
			fmt.Println(htErr)
113
		}
114
		return nil, nil, err
115 116
	}

117
	configPath, err := getConfigRoot(req)
118
	if err != nil {
119
		return nil, nil, err
120 121 122 123
	}

	conf, err := getConfig(configPath)
	if err != nil {
124
		return nil, nil, err
125 126 127 128 129
	}
	ctx := req.Context()
	ctx.ConfigRoot = configPath
	ctx.Config = conf

130 131
	// if no encoding was specified by user, default to plaintext encoding
	// (if command doesn't support plaintext, use JSON instead)
132
	if !req.Option("encoding").Found() {
133
		if req.Command().Marshallers != nil && req.Command().Marshallers[cmds.Text] != nil {
134 135 136 137 138 139
			req.SetOption("encoding", cmds.Text)
		} else {
			req.SetOption("encoding", cmds.JSON)
		}
	}

140
	return req, root, nil
141 142
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
143
func handleHelpOption(req cmds.Request, root *cmds.Command) (helpTextDisplayed bool, err error) {
144
	help, err := req.Option("help").Bool()
145
	if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
146
		return false, err
147
	}
148 149 150
	if !help {
		return false, nil
	}
151
	err = cmdsCli.LongHelp("ipfs", root, req.Path(), os.Stdout)
152 153
	if err != nil {
		return false, err
154
	}
155
	return true, nil
156
}
157

158
func callCommand(req cmds.Request, root *cmds.Command) (cmds.Response, error) {
159
	var res cmds.Response
160

161
	if root == Root { // TODO explain what it means when root == Root
162
		res = root.Call(req)
163 164

	} else {
165 166
		local, err := req.Option("local").Bool()
		if err != nil {
167
			return nil, err
168
		}
169

170
		if (!req.Option("local").Found() || !local) && daemon.Locked(req.Context().ConfigRoot) {
171 172
			addr, err := ma.NewMultiaddr(req.Context().Config.Addresses.API)
			if err != nil {
173
				return nil, err
174 175 176 177
			}

			_, host, err := manet.DialArgs(addr)
			if err != nil {
178
				return nil, err
179 180 181 182 183
			}

			client := cmdsHttp.NewClient(host)

			res, err = client.Send(req)
184
			if err != nil {
185
				return nil, err
186 187 188
			}

		} else {
189
			node, err := core.NewIpfsNode(req.Context().Config, false)
190
			if err != nil {
191
				return nil, err
192
			}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
193
			defer node.Close()
194
			req.Context().Node = node
195

196
			res = root.Call(req)
197 198 199
		}
	}

200
	return res, nil
201 202
}

203
func outputResponse(res cmds.Response, root *cmds.Command) error {
204
	if res.Error() != nil {
205
		fmt.Printf(errorFormat, res.Error().Error())
206

207 208 209 210 211
		if res.Error().Code != cmds.ErrClient {
			return res.Error()
		}

		// if this is a client error, we try to display help text
212
		if res.Error().Code == cmds.ErrClient {
213
			err := cmdsCli.LongHelp("ipfs", root, res.Request().Path(), os.Stdout)
214
			if err != nil {
215
				fmt.Println(err)
216
			}
217 218
		}

219
		emptyErr := errors.New("") // already displayed error text
220
		return emptyErr
221 222
	}

223
	out, err := res.Reader()
224
	if err != nil {
225
		return err
226
	}
227 228

	io.Copy(os.Stdout, out)
229
	return nil
230 231 232
}

func getConfigRoot(req cmds.Request) (string, error) {
233 234 235 236 237 238
	configOpt, err := req.Option("config").String()
	if err != nil {
		return "", err
	}
	if configOpt != "" {
		return configOpt, nil
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
	}

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

func getConfig(path string) (*config.Config, error) {
	configFile, err := config.Filename(path)
	if err != nil {
		return nil, err
	}

	return config.Load(configFile)
}
256

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
// 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
}

279 280 281
func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
282
		return err
283
	}
284
	defer mprof.Close() // _after_ writing the heap profile
285 286
	return pprof.WriteHeapProfile(mprof)
}
287

Matt Bell's avatar
Matt Bell committed
288 289 290 291 292 293 294 295
// 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...")
296
			os.Exit(0)
Matt Bell's avatar
Matt Bell committed
297 298 299
		}
	}()
}