exec.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package adapters
  17. import (
  18. "bytes"
  19. "context"
  20. "crypto/ecdsa"
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "net"
  26. "net/http"
  27. "os"
  28. "os/exec"
  29. "os/signal"
  30. "path/filepath"
  31. "strings"
  32. "sync"
  33. "syscall"
  34. "time"
  35. "github.com/docker/docker/pkg/reexec"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/node"
  38. "github.com/ethereum/go-ethereum/p2p"
  39. "github.com/ethereum/go-ethereum/p2p/enode"
  40. "github.com/ethereum/go-ethereum/rpc"
  41. "golang.org/x/net/websocket"
  42. )
  43. func init() {
  44. // Register a reexec function to start a simulation node when the current binary is
  45. // executed as "p2p-node" (rather than whatever the main() function would normally do).
  46. reexec.Register("p2p-node", execP2PNode)
  47. }
  48. // ExecAdapter is a NodeAdapter which runs simulation nodes by executing the current binary
  49. // as a child process.
  50. type ExecAdapter struct {
  51. // BaseDir is the directory under which the data directories for each
  52. // simulation node are created.
  53. BaseDir string
  54. nodes map[enode.ID]*ExecNode
  55. }
  56. // NewExecAdapter returns an ExecAdapter which stores node data in
  57. // subdirectories of the given base directory
  58. func NewExecAdapter(baseDir string) *ExecAdapter {
  59. return &ExecAdapter{
  60. BaseDir: baseDir,
  61. nodes: make(map[enode.ID]*ExecNode),
  62. }
  63. }
  64. // Name returns the name of the adapter for logging purposes
  65. func (e *ExecAdapter) Name() string {
  66. return "exec-adapter"
  67. }
  68. // NewNode returns a new ExecNode using the given config
  69. func (e *ExecAdapter) NewNode(config *NodeConfig) (Node, error) {
  70. if len(config.Services) == 0 {
  71. return nil, errors.New("node must have at least one service")
  72. }
  73. for _, service := range config.Services {
  74. if _, exists := serviceFuncs[service]; !exists {
  75. return nil, fmt.Errorf("unknown node service %q", service)
  76. }
  77. }
  78. // create the node directory using the first 12 characters of the ID
  79. // as Unix socket paths cannot be longer than 256 characters
  80. dir := filepath.Join(e.BaseDir, config.ID.String()[:12])
  81. if err := os.Mkdir(dir, 0755); err != nil {
  82. return nil, fmt.Errorf("error creating node directory: %s", err)
  83. }
  84. // generate the config
  85. conf := &execNodeConfig{
  86. Stack: node.DefaultConfig,
  87. Node: config,
  88. }
  89. conf.Stack.DataDir = filepath.Join(dir, "data")
  90. conf.Stack.WSHost = "127.0.0.1"
  91. conf.Stack.WSPort = 0
  92. conf.Stack.WSOrigins = []string{"*"}
  93. conf.Stack.WSExposeAll = true
  94. conf.Stack.P2P.EnableMsgEvents = false
  95. conf.Stack.P2P.NoDiscovery = true
  96. conf.Stack.P2P.NAT = nil
  97. conf.Stack.NoUSB = true
  98. // listen on a localhost port, which we set when we
  99. // initialise NodeConfig (usually a random port)
  100. conf.Stack.P2P.ListenAddr = fmt.Sprintf(":%d", config.Port)
  101. node := &ExecNode{
  102. ID: config.ID,
  103. Dir: dir,
  104. Config: conf,
  105. adapter: e,
  106. }
  107. node.newCmd = node.execCommand
  108. e.nodes[node.ID] = node
  109. return node, nil
  110. }
  111. // ExecNode starts a simulation node by exec'ing the current binary and
  112. // running the configured services
  113. type ExecNode struct {
  114. ID enode.ID
  115. Dir string
  116. Config *execNodeConfig
  117. Cmd *exec.Cmd
  118. Info *p2p.NodeInfo
  119. adapter *ExecAdapter
  120. client *rpc.Client
  121. wsAddr string
  122. newCmd func() *exec.Cmd
  123. key *ecdsa.PrivateKey
  124. }
  125. // Addr returns the node's enode URL
  126. func (n *ExecNode) Addr() []byte {
  127. if n.Info == nil {
  128. return nil
  129. }
  130. return []byte(n.Info.Enode)
  131. }
  132. // Client returns an rpc.Client which can be used to communicate with the
  133. // underlying services (it is set once the node has started)
  134. func (n *ExecNode) Client() (*rpc.Client, error) {
  135. return n.client, nil
  136. }
  137. // Start exec's the node passing the ID and service as command line arguments
  138. // and the node config encoded as JSON in an environment variable.
  139. func (n *ExecNode) Start(snapshots map[string][]byte) (err error) {
  140. if n.Cmd != nil {
  141. return errors.New("already started")
  142. }
  143. defer func() {
  144. if err != nil {
  145. n.Stop()
  146. }
  147. }()
  148. // encode a copy of the config containing the snapshot
  149. confCopy := *n.Config
  150. confCopy.Snapshots = snapshots
  151. confCopy.PeerAddrs = make(map[string]string)
  152. for id, node := range n.adapter.nodes {
  153. confCopy.PeerAddrs[id.String()] = node.wsAddr
  154. }
  155. confData, err := json.Marshal(confCopy)
  156. if err != nil {
  157. return fmt.Errorf("error generating node config: %s", err)
  158. }
  159. // start the one-shot server that waits for startup information
  160. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  161. defer cancel()
  162. statusURL, statusC := n.waitForStartupJSON(ctx)
  163. // start the node
  164. cmd := n.newCmd()
  165. cmd.Stdout = os.Stdout
  166. cmd.Stderr = os.Stderr
  167. cmd.Env = append(os.Environ(),
  168. envStatusURL+"="+statusURL,
  169. envNodeConfig+"="+string(confData),
  170. )
  171. if err := cmd.Start(); err != nil {
  172. return fmt.Errorf("error starting node: %s", err)
  173. }
  174. n.Cmd = cmd
  175. // read the WebSocket address from the stderr logs
  176. status := <-statusC
  177. if status.Err != "" {
  178. return errors.New(status.Err)
  179. }
  180. client, err := rpc.DialWebsocket(ctx, status.WSEndpoint, "http://localhost")
  181. if err != nil {
  182. return fmt.Errorf("can't connect to RPC server: %v", err)
  183. }
  184. // node ready :)
  185. n.client = client
  186. n.wsAddr = status.WSEndpoint
  187. n.Info = status.NodeInfo
  188. return nil
  189. }
  190. // waitForStartupJSON runs a one-shot HTTP server to receive a startup report.
  191. func (n *ExecNode) waitForStartupJSON(ctx context.Context) (string, chan nodeStartupJSON) {
  192. var (
  193. ch = make(chan nodeStartupJSON, 1)
  194. quitOnce sync.Once
  195. srv http.Server
  196. )
  197. l, err := net.Listen("tcp", "127.0.0.1:0")
  198. if err != nil {
  199. ch <- nodeStartupJSON{Err: err.Error()}
  200. return "", ch
  201. }
  202. quit := func(status nodeStartupJSON) {
  203. quitOnce.Do(func() {
  204. l.Close()
  205. ch <- status
  206. })
  207. }
  208. srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  209. var status nodeStartupJSON
  210. if err := json.NewDecoder(r.Body).Decode(&status); err != nil {
  211. status.Err = fmt.Sprintf("can't decode startup report: %v", err)
  212. }
  213. quit(status)
  214. })
  215. // Run the HTTP server, but don't wait forever and shut it down
  216. // if the context is canceled.
  217. go srv.Serve(l)
  218. go func() {
  219. <-ctx.Done()
  220. quit(nodeStartupJSON{Err: "didn't get startup report"})
  221. }()
  222. url := "http://" + l.Addr().String()
  223. return url, ch
  224. }
  225. // execCommand returns a command which runs the node locally by exec'ing
  226. // the current binary but setting argv[0] to "p2p-node" so that the child
  227. // runs execP2PNode
  228. func (n *ExecNode) execCommand() *exec.Cmd {
  229. return &exec.Cmd{
  230. Path: reexec.Self(),
  231. Args: []string{"p2p-node", strings.Join(n.Config.Node.Services, ","), n.ID.String()},
  232. }
  233. }
  234. // Stop stops the node by first sending SIGTERM and then SIGKILL if the node
  235. // doesn't stop within 5s
  236. func (n *ExecNode) Stop() error {
  237. if n.Cmd == nil {
  238. return nil
  239. }
  240. defer func() {
  241. n.Cmd = nil
  242. }()
  243. if n.client != nil {
  244. n.client.Close()
  245. n.client = nil
  246. n.wsAddr = ""
  247. n.Info = nil
  248. }
  249. if err := n.Cmd.Process.Signal(syscall.SIGTERM); err != nil {
  250. return n.Cmd.Process.Kill()
  251. }
  252. waitErr := make(chan error)
  253. go func() {
  254. waitErr <- n.Cmd.Wait()
  255. }()
  256. select {
  257. case err := <-waitErr:
  258. return err
  259. case <-time.After(5 * time.Second):
  260. return n.Cmd.Process.Kill()
  261. }
  262. }
  263. // NodeInfo returns information about the node
  264. func (n *ExecNode) NodeInfo() *p2p.NodeInfo {
  265. info := &p2p.NodeInfo{
  266. ID: n.ID.String(),
  267. }
  268. if n.client != nil {
  269. n.client.Call(&info, "admin_nodeInfo")
  270. }
  271. return info
  272. }
  273. // ServeRPC serves RPC requests over the given connection by dialling the
  274. // node's WebSocket address and joining the two connections
  275. func (n *ExecNode) ServeRPC(clientConn net.Conn) error {
  276. conn, err := websocket.Dial(n.wsAddr, "", "http://localhost")
  277. if err != nil {
  278. return err
  279. }
  280. var wg sync.WaitGroup
  281. wg.Add(2)
  282. join := func(src, dst net.Conn) {
  283. defer wg.Done()
  284. io.Copy(dst, src)
  285. // close the write end of the destination connection
  286. if cw, ok := dst.(interface {
  287. CloseWrite() error
  288. }); ok {
  289. cw.CloseWrite()
  290. } else {
  291. dst.Close()
  292. }
  293. }
  294. go join(conn, clientConn)
  295. go join(clientConn, conn)
  296. wg.Wait()
  297. return nil
  298. }
  299. // Snapshots creates snapshots of the services by calling the
  300. // simulation_snapshot RPC method
  301. func (n *ExecNode) Snapshots() (map[string][]byte, error) {
  302. if n.client == nil {
  303. return nil, errors.New("RPC not started")
  304. }
  305. var snapshots map[string][]byte
  306. return snapshots, n.client.Call(&snapshots, "simulation_snapshot")
  307. }
  308. // execNodeConfig is used to serialize the node configuration so it can be
  309. // passed to the child process as a JSON encoded environment variable
  310. type execNodeConfig struct {
  311. Stack node.Config `json:"stack"`
  312. Node *NodeConfig `json:"node"`
  313. Snapshots map[string][]byte `json:"snapshots,omitempty"`
  314. PeerAddrs map[string]string `json:"peer_addrs,omitempty"`
  315. }
  316. // execP2PNode starts a simulation node when the current binary is executed with
  317. // argv[0] being "p2p-node", reading the service / ID from argv[1] / argv[2]
  318. // and the node config from an environment variable.
  319. func execP2PNode() {
  320. glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.LogfmtFormat()))
  321. glogger.Verbosity(log.LvlInfo)
  322. log.Root().SetHandler(glogger)
  323. statusURL := os.Getenv(envStatusURL)
  324. if statusURL == "" {
  325. log.Crit("missing " + envStatusURL)
  326. }
  327. // Start the node and gather startup report.
  328. var status nodeStartupJSON
  329. stack, stackErr := startExecNodeStack()
  330. if stackErr != nil {
  331. status.Err = stackErr.Error()
  332. } else {
  333. status.WSEndpoint = "ws://" + stack.WSEndpoint()
  334. status.NodeInfo = stack.Server().NodeInfo()
  335. }
  336. // Send status to the host.
  337. statusJSON, _ := json.Marshal(status)
  338. if _, err := http.Post(statusURL, "application/json", bytes.NewReader(statusJSON)); err != nil {
  339. log.Crit("Can't post startup info", "url", statusURL, "err", err)
  340. }
  341. if stackErr != nil {
  342. os.Exit(1)
  343. }
  344. // Stop the stack if we get a SIGTERM signal.
  345. go func() {
  346. sigc := make(chan os.Signal, 1)
  347. signal.Notify(sigc, syscall.SIGTERM)
  348. defer signal.Stop(sigc)
  349. <-sigc
  350. log.Info("Received SIGTERM, shutting down...")
  351. stack.Stop()
  352. }()
  353. stack.Wait() // Wait for the stack to exit.
  354. }
  355. func startExecNodeStack() (*node.Node, error) {
  356. // read the services from argv
  357. serviceNames := strings.Split(os.Args[1], ",")
  358. // decode the config
  359. confEnv := os.Getenv(envNodeConfig)
  360. if confEnv == "" {
  361. return nil, fmt.Errorf("missing " + envNodeConfig)
  362. }
  363. var conf execNodeConfig
  364. if err := json.Unmarshal([]byte(confEnv), &conf); err != nil {
  365. return nil, fmt.Errorf("error decoding %s: %v", envNodeConfig, err)
  366. }
  367. conf.Stack.P2P.PrivateKey = conf.Node.PrivateKey
  368. conf.Stack.Logger = log.New("node.id", conf.Node.ID.String())
  369. // initialize the devp2p stack
  370. stack, err := node.New(&conf.Stack)
  371. if err != nil {
  372. return nil, fmt.Errorf("error creating node stack: %v", err)
  373. }
  374. // register the services, collecting them into a map so we can wrap
  375. // them in a snapshot service
  376. services := make(map[string]node.Service, len(serviceNames))
  377. for _, name := range serviceNames {
  378. serviceFunc, exists := serviceFuncs[name]
  379. if !exists {
  380. return nil, fmt.Errorf("unknown node service %q", err)
  381. }
  382. constructor := func(nodeCtx *node.ServiceContext) (node.Service, error) {
  383. ctx := &ServiceContext{
  384. RPCDialer: &wsRPCDialer{addrs: conf.PeerAddrs},
  385. NodeContext: nodeCtx,
  386. Config: conf.Node,
  387. }
  388. if conf.Snapshots != nil {
  389. ctx.Snapshot = conf.Snapshots[name]
  390. }
  391. service, err := serviceFunc(ctx)
  392. if err != nil {
  393. return nil, err
  394. }
  395. services[name] = service
  396. return service, nil
  397. }
  398. if err := stack.Register(constructor); err != nil {
  399. return stack, fmt.Errorf("error registering service %q: %v", name, err)
  400. }
  401. }
  402. // register the snapshot service
  403. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  404. return &snapshotService{services}, nil
  405. })
  406. if err != nil {
  407. return stack, fmt.Errorf("error starting snapshot service: %v", err)
  408. }
  409. // start the stack
  410. if err = stack.Start(); err != nil {
  411. err = fmt.Errorf("error starting stack: %v", err)
  412. }
  413. return stack, err
  414. }
  415. const (
  416. envStatusURL = "_P2P_STATUS_URL"
  417. envNodeConfig = "_P2P_NODE_CONFIG"
  418. )
  419. // nodeStartupJSON is sent to the simulation host after startup.
  420. type nodeStartupJSON struct {
  421. Err string
  422. WSEndpoint string
  423. NodeInfo *p2p.NodeInfo
  424. }
  425. // snapshotService is a node.Service which wraps a list of services and
  426. // exposes an API to generate a snapshot of those services
  427. type snapshotService struct {
  428. services map[string]node.Service
  429. }
  430. func (s *snapshotService) APIs() []rpc.API {
  431. return []rpc.API{{
  432. Namespace: "simulation",
  433. Version: "1.0",
  434. Service: SnapshotAPI{s.services},
  435. }}
  436. }
  437. func (s *snapshotService) Protocols() []p2p.Protocol {
  438. return nil
  439. }
  440. func (s *snapshotService) Start(*p2p.Server) error {
  441. return nil
  442. }
  443. func (s *snapshotService) Stop() error {
  444. return nil
  445. }
  446. // SnapshotAPI provides an RPC method to create snapshots of services
  447. type SnapshotAPI struct {
  448. services map[string]node.Service
  449. }
  450. func (api SnapshotAPI) Snapshot() (map[string][]byte, error) {
  451. snapshots := make(map[string][]byte)
  452. for name, service := range api.services {
  453. if s, ok := service.(interface {
  454. Snapshot() ([]byte, error)
  455. }); ok {
  456. snap, err := s.Snapshot()
  457. if err != nil {
  458. return nil, err
  459. }
  460. snapshots[name] = snap
  461. }
  462. }
  463. return snapshots, nil
  464. }
  465. type wsRPCDialer struct {
  466. addrs map[string]string
  467. }
  468. // DialRPC implements the RPCDialer interface by creating a WebSocket RPC
  469. // client of the given node
  470. func (w *wsRPCDialer) DialRPC(id enode.ID) (*rpc.Client, error) {
  471. addr, ok := w.addrs[id.String()]
  472. if !ok {
  473. return nil, fmt.Errorf("unknown node: %s", id)
  474. }
  475. return rpc.DialWebsocket(context.Background(), addr, "http://localhost")
  476. }