main.go 6.5 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 28 29
const (
	heapProfile = "ipfs.mprof"
	errorFormat = "ERROR: %v\n\n"
)
30

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

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

46
func createRequest(args []string) (cmds.Request, *cmds.Command) {
47 48 49 50 51 52 53 54 55
	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)
56
		}
57 58
	}

59 60
	// handle parse error (which means the commandline input was wrong,
	// e.g. incorrect number of args, or nonexistent subcommand)
61
	if err != nil {
62
		// if the -help flag wasn't specified, show the error message
63 64 65 66 67 68 69
		// or if a path was returned (user specified a valid subcommand), show the error message
		// (this means there was an option or argument error)
		if options != nil || path != nil && len(path) > 0 {
			help := false
			if options != nil {
				opt, _ := options.Option("help")
				help, _ = opt.(bool)
70 71
			}

72 73 74
			if !help {
				fmt.Printf(errorFormat, err)
			}
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
		}

		// 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)
		}
91 92 93
		os.Exit(1)
	}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
	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 {
111
		if req.Command().Marshallers != nil && req.Command().Marshallers[cmds.Text] != nil {
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
			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)
	}

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

143 144 145 146
	if debug, found := options.Option("debug"); found {
		if debugBool, ok := debug.(bool); debugBool && ok {
			u.Debug = true

147 148
			u.SetAllLoggers(logging.DEBUG)

149 150 151 152 153 154 155 156 157 158
			// 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()
159
			}
160 161 162
		} else if !ok {
			fmt.Println("error: expected 'debug' option to be a bool")
			os.Exit(1)
163 164
		}
	}
165
}
166

167
func callCommand(req cmds.Request, root *cmds.Command) cmds.Response {
168
	var res cmds.Response
169

170 171
	if root == Root {
		res = root.Call(req)
172 173

	} else {
174 175 176 177 178 179
		options, err := getOptions(req, root)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

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

192
		if (!found || !localBool) && daemon.Locked(req.Context().ConfigRoot) {
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
			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)
208 209 210 211 212 213
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

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

222
			res = root.Call(req)
223 224 225
		}
	}

226 227 228
	return res
}

229
func outputResponse(res cmds.Response, root *cmds.Command) {
230
	if res.Error() != nil {
231
		fmt.Printf(errorFormat, res.Error().Error())
232

233 234 235 236 237 238 239
		if res.Error().Code == cmds.ErrClient {
			helpText, err := cmdsCli.HelpText("ipfs", root, res.Request().Path())
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println(helpText)
			}
240 241 242 243 244
		}

		os.Exit(1)
	}

245
	out, err := res.Reader()
246 247
	if err != nil {
		fmt.Println(err.Error())
248
		return
249
	}
250 251

	io.Copy(os.Stdout, out)
252 253 254
}

func getOptions(req cmds.Request, root *cmds.Command) (cmds.Request, error) {
255
	tempReq := cmds.NewRequest(req.Path(), req.Options(), nil, nil)
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

	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 {
272 273 274 275 276
		if optStr, ok := opt.(string); ok {
			return optStr, nil
		} else {
			return "", fmt.Errorf("Expected 'config' option to be a string")
		}
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
	}

	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)
}
294 295 296 297 298 299 300 301 302

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