main.go 5.88 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 82
	res, err := callCommand(req, root)
	if err != nil {
		return err
	}
83 84
	outputResponse(res, root)

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

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

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

121
	configPath, err := getConfigRoot(req)
122
	if err != nil {
123
		return nil, nil, err
124 125 126 127
	}

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

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

142
	return req, root, nil
143 144
}

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

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
160
	return false, nil
161
}
162

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

166
	if root == Root { // TODO explain what it means when root == Root
167
		res = root.Call(req)
168 169

	} else {
170 171
		local, err := req.Option("local").Bool()
		if err != nil {
172
			return nil, err
173
		}
174

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

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

			client := cmdsHttp.NewClient(host)

			res, err = client.Send(req)
189
			if err != nil {
190
				return nil, err
191 192 193
			}

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

201
			res = root.Call(req)
202 203 204
		}
	}

205
	return res, nil
206 207
}

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

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

221
		exit(1)
222 223
	}

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

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

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

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

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

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

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

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

	os.Exit(code)
}