main.go 6.38 KB
Newer Older
1 2 3 4 5 6 7 8
package main

import (
	"fmt"
	"io"
	"os"
	"runtime/pprof"

9
	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-logging"
10 11 12
	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"

13 14 15 16 17 18 19 20 21 22 23 24 25
	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")

26 27
const heapProfile = "ipfs.mprof"

28 29
func main() {
	args := os.Args[1:]
30 31 32 33
	req, root := createRequest(args)
	handleOptions(req, root)
	res := callCommand(req, root)
	outputResponse(res)
34 35 36 37 38 39 40

	if u.Debug {
		err := writeHeapProfileToFile()
		if err != nil {
			log.Critical(err)
		}
	}
41
}
42

43
func createRequest(args []string) (cmds.Request, *cmds.Command) {
44 45 46 47 48 49 50 51 52
	req, root, cmd, path, err := cmdsCli.Parse(args, Root, commands.Root)

	var options cmds.Request
	if req != nil && root != nil {
		var err2 error
		options, err2 = getOptions(req, root)
		if err2 != nil {
			fmt.Println(err2)
			os.Exit(1)
53
		}
54 55
	}

56 57
	// handle parse error (which means the commandline input was wrong,
	// e.g. incorrect number of args, or nonexistent subcommand)
58
	if err != nil {
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
		// if the -help flag wasn't specified, show the error message
		if options != nil {
			opt, _ := options.Option("help")
			help, _ := opt.(bool)
			if !help {
				fmt.Println(err)
			}

		} else if path != nil && len(path) > 0 {
			// if a path was returned (user specified a valid subcommand), show the error message
			// (this means there was an option or argument error)
			fmt.Println(err)
		}

		// when generating help for the root command, we don't want the autogenerated subcommand text
		// (since we have better hand-made subcommand list in the root Help field)
		if cmd == nil {
			root = &*commands.Root
			root.Subcommands = nil
		}

		// generate the help text for the command the user was trying to call (or root)
		helpText, err := cmdsCli.HelpText("ipfs", root, path)
		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(helpText)
		}
87 88 89
		os.Exit(1)
	}

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
	configPath, err := getConfigRoot(options)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	conf, err := getConfig(configPath)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	ctx := req.Context()
	ctx.ConfigRoot = configPath
	ctx.Config = conf

	if _, found := options.Option("encoding"); !found {
107
		if req.Command().Marshallers != nil && req.Command().Marshallers[cmds.Text] != nil {
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
			req.SetOption("encoding", cmds.Text)
		} else {
			req.SetOption("encoding", cmds.JSON)
		}
	}

	return req, root
}

func handleOptions(req cmds.Request, root *cmds.Command) {
	options, err := getOptions(req, root)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

124 125
	if help, found := options.Option("help"); found {
		if helpBool, ok := help.(bool); helpBool && ok {
126 127 128 129 130 131
			helpText, err := cmdsCli.HelpText("ipfs", root, req.Path())
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println(helpText)
			}
132 133 134 135 136
			os.Exit(0)
		} else if !ok {
			fmt.Println("error: expected 'help' option to be a bool")
			os.Exit(1)
		}
137 138
	}

139 140 141 142
	if debug, found := options.Option("debug"); found {
		if debugBool, ok := debug.(bool); debugBool && ok {
			u.Debug = true

143 144
			u.SetAllLoggers(logging.DEBUG)

145 146 147 148 149 150 151 152 153 154
			// if debugging, setup profiling.
			if u.Debug {
				ofi, err := os.Create("cpu.prof")
				if err != nil {
					fmt.Println(err)
					return
				}
				pprof.StartCPUProfile(ofi)
				defer ofi.Close()
				defer pprof.StopCPUProfile()
155
			}
156 157 158
		} else if !ok {
			fmt.Println("error: expected 'debug' option to be a bool")
			os.Exit(1)
159 160
		}
	}
161
}
162

163
func callCommand(req cmds.Request, root *cmds.Command) cmds.Response {
164
	var res cmds.Response
165

166 167
	if root == Root {
		res = root.Call(req)
168 169

	} else {
170 171 172 173 174 175
		options, err := getOptions(req, root)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

176
		var found bool
177
		var local interface{}
178
		localBool := false
179
		if local, found = options.Option("local"); found {
180 181 182 183 184 185 186
			var ok bool
			localBool, ok = local.(bool)
			if !ok {
				fmt.Println("error: expected 'local' option to be a bool")
				os.Exit(1)
			}
		}
187

188
		if (!found || !localBool) && daemon.Locked(req.Context().ConfigRoot) {
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
			addr, err := ma.NewMultiaddr(req.Context().Config.Addresses.API)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			_, host, err := manet.DialArgs(addr)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			client := cmdsHttp.NewClient(host)

			res, err = client.Send(req)
204 205 206 207 208 209
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

		} else {
210
			node, err := core.NewIpfsNode(req.Context().Config, false)
211 212 213 214
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
215
			defer node.Close()
216
			req.Context().Node = node
217

218
			res = root.Call(req)
219 220 221
		}
	}

222 223 224 225
	return res
}

func outputResponse(res cmds.Response) {
226 227 228
	if res.Error() != nil {
		fmt.Println(res.Error().Error())

229
		if res.Request().Command().Help != "" && res.Error().Code == cmds.ErrClient {
230
			// TODO: convert from markdown to ANSI terminal format?
231
			fmt.Println(res.Request().Command().Help)
232 233 234 235 236
		}

		os.Exit(1)
	}

237
	out, err := res.Reader()
238 239
	if err != nil {
		fmt.Println(err.Error())
240
		return
241
	}
242 243

	io.Copy(os.Stdout, out)
244 245 246
}

func getOptions(req cmds.Request, root *cmds.Command) (cmds.Request, error) {
247
	tempReq := cmds.NewRequest(req.Path(), req.Options(), nil, nil)
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

	options, err := root.GetOptions(tempReq.Path())
	if err != nil {
		return nil, err
	}

	err = tempReq.ConvertOptions(options)
	if err != nil {
		return nil, err
	}

	return tempReq, nil
}

func getConfigRoot(req cmds.Request) (string, error) {
	if opt, found := req.Option("config"); found {
264 265 266 267 268
		if optStr, ok := opt.(string); ok {
			return optStr, nil
		} else {
			return "", fmt.Errorf("Expected 'config' option to be a string")
		}
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	}

	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)
}
286 287 288 289 290 291 292 293 294

func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
		log.Fatal(err)
	}
	defer mprof.Close()
	return pprof.WriteHeapProfile(mprof)
}