main.go 5.85 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() {
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 debugging, setup profiling.
61
	if u.Debug {
62 63
		var err error
		ofi, err = os.Create("cpu.prof")
64
		if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
65
			return err
66
		}
67 68

		pprof.StartCPUProfile(ofi)
69
	}
70

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

79 80 81
	res := callCommand(req, root)
	outputResponse(res, root)

Brian Tiger Chow's avatar
Brian Tiger Chow committed
82
	return nil
83
}
84

85
func createRequest(args []string) (cmds.Request, *cmds.Command, error) {
86 87 88 89
	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)
90
	if err != nil {
91
		// if the -help flag wasn't specified, show the error message
92 93
		// or if a path was returned (user specified a valid subcommand), show the error message
		// (this means there was an option or argument error)
94
		if path != nil && len(path) > 0 {
95
			help, _ := req.Option("help").Bool()
96 97 98
			if !help {
				fmt.Printf(errorFormat, err)
			}
99 100 101 102 103 104 105 106 107 108
		}

		// 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)
109 110 111
		helpText, htErr := cmdsCli.HelpText("ipfs", root, path)
		if htErr != nil {
			fmt.Println(htErr)
112 113 114
		} else {
			fmt.Println(helpText)
		}
115
		return nil, nil, err
116 117
	}

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

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

131
	if !req.Option("encoding").Found() {
132
		if req.Command().Marshallers != nil && req.Command().Marshallers[cmds.Text] != nil {
133 134 135 136 137 138
			req.SetOption("encoding", cmds.Text)
		} else {
			req.SetOption("encoding", cmds.JSON)
		}
	}

139
	return req, root, nil
140 141
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
142
func handleHelpOption(req cmds.Request, root *cmds.Command) (helpTextDisplayed bool, err error) {
143
	help, err := req.Option("help").Bool()
144
	if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
145
		return false, err
146 147 148
	}

	if help {
149 150
		helpText, err := cmdsCli.HelpText("ipfs", root, req.Path())
		if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
151
			return false, err
152
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
153 154
		fmt.Println(helpText)
		return true, nil
155 156
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
157
	return false, nil
158
}
159

160
func callCommand(req cmds.Request, root *cmds.Command) cmds.Response {
161
	var res cmds.Response
162

163 164
	if root == Root {
		res = root.Call(req)
165 166

	} else {
167 168 169 170
		local, err := req.Option("local").Bool()
		if err != nil {
			fmt.Println(err)
			exit(1)
171
		}
172

173
		if (!req.Option("local").Found() || !local) && daemon.Locked(req.Context().ConfigRoot) {
174 175 176
			addr, err := ma.NewMultiaddr(req.Context().Config.Addresses.API)
			if err != nil {
				fmt.Println(err)
177
				exit(1)
178 179 180 181 182
			}

			_, host, err := manet.DialArgs(addr)
			if err != nil {
				fmt.Println(err)
183
				exit(1)
184 185 186 187 188
			}

			client := cmdsHttp.NewClient(host)

			res, err = client.Send(req)
189 190
			if err != nil {
				fmt.Println(err)
191
				exit(1)
192 193 194
			}

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

203
			res = root.Call(req)
204 205 206
		}
	}

207 208 209
	return res
}

210
func outputResponse(res cmds.Response, root *cmds.Command) {
211
	if res.Error() != nil {
212
		fmt.Printf(errorFormat, res.Error().Error())
213

214 215 216 217 218 219 220
		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)
			}
221 222
		}

223
		exit(1)
224 225
	}

226
	out, err := res.Reader()
227 228
	if err != nil {
		fmt.Println(err.Error())
229
		return
230
	}
231 232

	io.Copy(os.Stdout, out)
233 234 235
}

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

	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)
}
259 260 261 262 263 264 265 266 267

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

Matt Bell's avatar
Matt Bell committed
269 270 271 272 273 274 275 276 277 278 279 280 281
// 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)
		}
	}()
}

282 283 284 285 286 287 288 289 290 291 292 293 294
func exit(code int) {
	if u.Debug {
		pprof.StopCPUProfile()
		ofi.Close()

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

	os.Exit(code)
}