main.go 6.03 KB
Newer Older
1 2 3 4 5 6
package main

import (
	"fmt"
	"io"
	"os"
Matt Bell's avatar
Matt Bell committed
7
	"os/signal"
8 9
	"runtime/pprof"

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

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

27 28 29 30
const (
	heapProfile = "ipfs.mprof"
	errorFormat = "ERROR: %v\n\n"
)
31

32 33
var ofi io.WriteCloser

34
func main() {
Matt Bell's avatar
Matt Bell committed
35 36
	handleInterrupt()

37
	args := os.Args[1:]
38 39
	req, root := createRequest(args)
	handleOptions(req, root)
40

41
	// if debugging, setup profiling.
42
	if u.Debug {
43 44
		var err error
		ofi, err = os.Create("cpu.prof")
45
		if err != nil {
46 47
			fmt.Println(err)
			return
48
		}
49 50

		pprof.StartCPUProfile(ofi)
51
	}
52 53 54 55 56

	res := callCommand(req, root)
	outputResponse(res, root)

	exit(0)
57
}
58

59
func createRequest(args []string) (cmds.Request, *cmds.Command) {
60 61 62 63
	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)
64
	if err != nil {
65
		// if the -help flag wasn't specified, show the error message
66 67
		// or if a path was returned (user specified a valid subcommand), show the error message
		// (this means there was an option or argument error)
68
		if path != nil && len(path) > 0 {
69
			help := false
70 71
			opt, _ := req.Option("help")
			help, _ = opt.(bool)
72

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

		// 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)
		}
92
		exit(1)
93 94
	}

95
	configPath, err := getConfigRoot(req)
96 97
	if err != nil {
		fmt.Println(err)
98
		exit(1)
99 100 101 102 103
	}

	conf, err := getConfig(configPath)
	if err != nil {
		fmt.Println(err)
104
		exit(1)
105 106 107 108 109 110
	}

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

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

	return req, root
}

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

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

142
			u.SetAllLoggers(logging.DEBUG)
143 144
		} else if !ok {
			fmt.Println("error: expected 'debug' option to be a bool")
145
			exit(1)
146 147
		}
	}
148
}
149

150
func callCommand(req cmds.Request, root *cmds.Command) cmds.Response {
151
	var res cmds.Response
152

153 154
	if root == Root {
		res = root.Call(req)
155 156

	} else {
157
		var found bool
158
		var local interface{}
159
		localBool := false
160
		if local, found = req.Option("local"); found {
161 162 163 164
			var ok bool
			localBool, ok = local.(bool)
			if !ok {
				fmt.Println("error: expected 'local' option to be a bool")
165
				exit(1)
166 167
			}
		}
168

169
		if (!found || !localBool) && daemon.Locked(req.Context().ConfigRoot) {
170 171 172
			addr, err := ma.NewMultiaddr(req.Context().Config.Addresses.API)
			if err != nil {
				fmt.Println(err)
173
				exit(1)
174 175 176 177 178
			}

			_, host, err := manet.DialArgs(addr)
			if err != nil {
				fmt.Println(err)
179
				exit(1)
180 181 182 183 184
			}

			client := cmdsHttp.NewClient(host)

			res, err = client.Send(req)
185 186
			if err != nil {
				fmt.Println(err)
187
				exit(1)
188 189 190
			}

		} else {
191
			node, err := core.NewIpfsNode(req.Context().Config, false)
192 193
			if err != nil {
				fmt.Println(err)
194
				exit(1)
195
			}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
196
			defer node.Close()
197
			req.Context().Node = node
198

199
			res = root.Call(req)
200 201 202
		}
	}

203 204 205
	return res
}

206
func outputResponse(res cmds.Response, root *cmds.Command) {
207
	if res.Error() != nil {
208
		fmt.Printf(errorFormat, res.Error().Error())
209

210 211 212 213 214 215 216
		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)
			}
217 218
		}

219
		exit(1)
220 221
	}

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

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

func getConfigRoot(req cmds.Request) (string, error) {
	if opt, found := req.Option("config"); found {
233 234 235 236 237
		if optStr, ok := opt.(string); ok {
			return optStr, nil
		} else {
			return "", fmt.Errorf("Expected 'config' option to be a string")
		}
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
	}

	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)
}
255 256 257 258 259 260 261 262 263

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

Matt Bell's avatar
Matt Bell committed
265 266 267 268 269 270 271 272 273 274 275 276 277
// 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...")
			exit(0)
		}
	}()
}

278 279 280 281 282 283 284 285 286 287 288 289 290
func exit(code int) {
	if u.Debug {
		pprof.StopCPUProfile()
		ofi.Close()

		err := writeHeapProfileToFile()
		if err != nil {
			log.Critical(err)
		}
	}

	os.Exit(code)
}