exec.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. "bufio"
  19. "context"
  20. "crypto/ecdsa"
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "net"
  26. "os"
  27. "os/exec"
  28. "os/signal"
  29. "path/filepath"
  30. "strings"
  31. "sync"
  32. "syscall"
  33. "time"
  34. "github.com/docker/docker/pkg/reexec"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/node"
  37. "github.com/ethereum/go-ethereum/p2p"
  38. "github.com/ethereum/go-ethereum/p2p/discover"
  39. "github.com/ethereum/go-ethereum/rpc"
  40. "golang.org/x/net/websocket"
  41. )
  42. // ExecAdapter is a NodeAdapter which runs simulation nodes by executing the
  43. // current binary as a child process.
  44. //
  45. // An init hook is used so that the child process executes the node services
  46. // (rather than whataver the main() function would normally do), see the
  47. // execP2PNode function for more information.
  48. type ExecAdapter struct {
  49. // BaseDir is the directory under which the data directories for each
  50. // simulation node are created.
  51. BaseDir string
  52. nodes map[discover.NodeID]*ExecNode
  53. }
  54. // NewExecAdapter returns an ExecAdapter which stores node data in
  55. // subdirectories of the given base directory
  56. func NewExecAdapter(baseDir string) *ExecAdapter {
  57. return &ExecAdapter{
  58. BaseDir: baseDir,
  59. nodes: make(map[discover.NodeID]*ExecNode),
  60. }
  61. }
  62. // Name returns the name of the adapter for logging purposes
  63. func (e *ExecAdapter) Name() string {
  64. return "exec-adapter"
  65. }
  66. // NewNode returns a new ExecNode using the given config
  67. func (e *ExecAdapter) NewNode(config *NodeConfig) (Node, error) {
  68. if len(config.Services) == 0 {
  69. return nil, errors.New("node must have at least one service")
  70. }
  71. for _, service := range config.Services {
  72. if _, exists := serviceFuncs[service]; !exists {
  73. return nil, fmt.Errorf("unknown node service %q", service)
  74. }
  75. }
  76. // create the node directory using the first 12 characters of the ID
  77. // as Unix socket paths cannot be longer than 256 characters
  78. dir := filepath.Join(e.BaseDir, config.ID.String()[:12])
  79. if err := os.Mkdir(dir, 0755); err != nil {
  80. return nil, fmt.Errorf("error creating node directory: %s", err)
  81. }
  82. // generate the config
  83. conf := &execNodeConfig{
  84. Stack: node.DefaultConfig,
  85. Node: config,
  86. }
  87. conf.Stack.DataDir = filepath.Join(dir, "data")
  88. conf.Stack.WSHost = "127.0.0.1"
  89. conf.Stack.WSPort = 0
  90. conf.Stack.WSOrigins = []string{"*"}
  91. conf.Stack.WSExposeAll = true
  92. conf.Stack.P2P.EnableMsgEvents = false
  93. conf.Stack.P2P.NoDiscovery = true
  94. conf.Stack.P2P.NAT = nil
  95. conf.Stack.NoUSB = true
  96. // listen on a localhost port, which we set when we
  97. // initialise NodeConfig (usually a random port)
  98. conf.Stack.P2P.ListenAddr = fmt.Sprintf(":%d", config.Port)
  99. node := &ExecNode{
  100. ID: config.ID,
  101. Dir: dir,
  102. Config: conf,
  103. adapter: e,
  104. }
  105. node.newCmd = node.execCommand
  106. e.nodes[node.ID] = node
  107. return node, nil
  108. }
  109. // ExecNode starts a simulation node by exec'ing the current binary and
  110. // running the configured services
  111. type ExecNode struct {
  112. ID discover.NodeID
  113. Dir string
  114. Config *execNodeConfig
  115. Cmd *exec.Cmd
  116. Info *p2p.NodeInfo
  117. adapter *ExecAdapter
  118. client *rpc.Client
  119. wsAddr string
  120. newCmd func() *exec.Cmd
  121. key *ecdsa.PrivateKey
  122. }
  123. // Addr returns the node's enode URL
  124. func (n *ExecNode) Addr() []byte {
  125. if n.Info == nil {
  126. return nil
  127. }
  128. return []byte(n.Info.Enode)
  129. }
  130. // Client returns an rpc.Client which can be used to communicate with the
  131. // underlying services (it is set once the node has started)
  132. func (n *ExecNode) Client() (*rpc.Client, error) {
  133. return n.client, nil
  134. }
  135. // Start exec's the node passing the ID and service as command line arguments
  136. // and the node config encoded as JSON in the _P2P_NODE_CONFIG environment
  137. // variable
  138. func (n *ExecNode) Start(snapshots map[string][]byte) (err error) {
  139. if n.Cmd != nil {
  140. return errors.New("already started")
  141. }
  142. defer func() {
  143. if err != nil {
  144. log.Error("node failed to start", "err", err)
  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. // use a pipe for stderr so we can both copy the node's stderr to
  160. // os.Stderr and read the WebSocket address from the logs
  161. stderrR, stderrW := io.Pipe()
  162. stderr := io.MultiWriter(os.Stderr, stderrW)
  163. // start the node
  164. cmd := n.newCmd()
  165. cmd.Stdout = os.Stdout
  166. cmd.Stderr = stderr
  167. cmd.Env = append(os.Environ(), fmt.Sprintf("_P2P_NODE_CONFIG=%s", confData))
  168. if err := cmd.Start(); err != nil {
  169. return fmt.Errorf("error starting node: %s", err)
  170. }
  171. n.Cmd = cmd
  172. // read the WebSocket address from the stderr logs
  173. var wsAddr string
  174. wsAddrC := make(chan string)
  175. go func() {
  176. s := bufio.NewScanner(stderrR)
  177. for s.Scan() {
  178. if strings.Contains(s.Text(), "WebSocket endpoint opened") {
  179. wsAddrC <- wsAddrPattern.FindString(s.Text())
  180. }
  181. }
  182. }()
  183. select {
  184. case wsAddr = <-wsAddrC:
  185. if wsAddr == "" {
  186. return errors.New("failed to read WebSocket address from stderr")
  187. }
  188. case <-time.After(10 * time.Second):
  189. return errors.New("timed out waiting for WebSocket address on stderr")
  190. }
  191. // create the RPC client and load the node info
  192. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  193. defer cancel()
  194. client, err := rpc.DialWebsocket(ctx, wsAddr, "")
  195. if err != nil {
  196. return fmt.Errorf("error dialing rpc websocket: %s", err)
  197. }
  198. var info p2p.NodeInfo
  199. if err := client.CallContext(ctx, &info, "admin_nodeInfo"); err != nil {
  200. return fmt.Errorf("error getting node info: %s", err)
  201. }
  202. n.client = client
  203. n.wsAddr = wsAddr
  204. n.Info = &info
  205. return nil
  206. }
  207. // execCommand returns a command which runs the node locally by exec'ing
  208. // the current binary but setting argv[0] to "p2p-node" so that the child
  209. // runs execP2PNode
  210. func (n *ExecNode) execCommand() *exec.Cmd {
  211. return &exec.Cmd{
  212. Path: reexec.Self(),
  213. Args: []string{"p2p-node", strings.Join(n.Config.Node.Services, ","), n.ID.String()},
  214. }
  215. }
  216. // Stop stops the node by first sending SIGTERM and then SIGKILL if the node
  217. // doesn't stop within 5s
  218. func (n *ExecNode) Stop() error {
  219. if n.Cmd == nil {
  220. return nil
  221. }
  222. defer func() {
  223. n.Cmd = nil
  224. }()
  225. if n.client != nil {
  226. n.client.Close()
  227. n.client = nil
  228. n.wsAddr = ""
  229. n.Info = nil
  230. }
  231. if err := n.Cmd.Process.Signal(syscall.SIGTERM); err != nil {
  232. return n.Cmd.Process.Kill()
  233. }
  234. waitErr := make(chan error)
  235. go func() {
  236. waitErr <- n.Cmd.Wait()
  237. }()
  238. select {
  239. case err := <-waitErr:
  240. return err
  241. case <-time.After(5 * time.Second):
  242. return n.Cmd.Process.Kill()
  243. }
  244. }
  245. // NodeInfo returns information about the node
  246. func (n *ExecNode) NodeInfo() *p2p.NodeInfo {
  247. info := &p2p.NodeInfo{
  248. ID: n.ID.String(),
  249. }
  250. if n.client != nil {
  251. n.client.Call(&info, "admin_nodeInfo")
  252. }
  253. return info
  254. }
  255. // ServeRPC serves RPC requests over the given connection by dialling the
  256. // node's WebSocket address and joining the two connections
  257. func (n *ExecNode) ServeRPC(clientConn net.Conn) error {
  258. conn, err := websocket.Dial(n.wsAddr, "", "http://localhost")
  259. if err != nil {
  260. return err
  261. }
  262. var wg sync.WaitGroup
  263. wg.Add(2)
  264. join := func(src, dst net.Conn) {
  265. defer wg.Done()
  266. io.Copy(dst, src)
  267. // close the write end of the destination connection
  268. if cw, ok := dst.(interface {
  269. CloseWrite() error
  270. }); ok {
  271. cw.CloseWrite()
  272. } else {
  273. dst.Close()
  274. }
  275. }
  276. go join(conn, clientConn)
  277. go join(clientConn, conn)
  278. wg.Wait()
  279. return nil
  280. }
  281. // Snapshots creates snapshots of the services by calling the
  282. // simulation_snapshot RPC method
  283. func (n *ExecNode) Snapshots() (map[string][]byte, error) {
  284. if n.client == nil {
  285. return nil, errors.New("RPC not started")
  286. }
  287. var snapshots map[string][]byte
  288. return snapshots, n.client.Call(&snapshots, "simulation_snapshot")
  289. }
  290. func init() {
  291. // register a reexec function to start a devp2p node when the current
  292. // binary is executed as "p2p-node"
  293. reexec.Register("p2p-node", execP2PNode)
  294. }
  295. // execNodeConfig is used to serialize the node configuration so it can be
  296. // passed to the child process as a JSON encoded environment variable
  297. type execNodeConfig struct {
  298. Stack node.Config `json:"stack"`
  299. Node *NodeConfig `json:"node"`
  300. Snapshots map[string][]byte `json:"snapshots,omitempty"`
  301. PeerAddrs map[string]string `json:"peer_addrs,omitempty"`
  302. }
  303. // ExternalIP gets an external IP address so that Enode URL is usable
  304. func ExternalIP() net.IP {
  305. addrs, err := net.InterfaceAddrs()
  306. if err != nil {
  307. log.Crit("error getting IP address", "err", err)
  308. }
  309. for _, addr := range addrs {
  310. if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() && !ip.IP.IsLinkLocalUnicast() {
  311. return ip.IP
  312. }
  313. }
  314. log.Warn("unable to determine explicit IP address, falling back to loopback")
  315. return net.IP{127, 0, 0, 1}
  316. }
  317. // execP2PNode starts a devp2p node when the current binary is executed with
  318. // argv[0] being "p2p-node", reading the service / ID from argv[1] / argv[2]
  319. // and the node config from the _P2P_NODE_CONFIG environment variable
  320. func execP2PNode() {
  321. glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.LogfmtFormat()))
  322. glogger.Verbosity(log.LvlInfo)
  323. log.Root().SetHandler(glogger)
  324. // read the services from argv
  325. serviceNames := strings.Split(os.Args[1], ",")
  326. // decode the config
  327. confEnv := os.Getenv("_P2P_NODE_CONFIG")
  328. if confEnv == "" {
  329. log.Crit("missing _P2P_NODE_CONFIG")
  330. }
  331. var conf execNodeConfig
  332. if err := json.Unmarshal([]byte(confEnv), &conf); err != nil {
  333. log.Crit("error decoding _P2P_NODE_CONFIG", "err", err)
  334. }
  335. conf.Stack.P2P.PrivateKey = conf.Node.PrivateKey
  336. conf.Stack.Logger = log.New("node.id", conf.Node.ID.String())
  337. if strings.HasPrefix(conf.Stack.P2P.ListenAddr, ":") {
  338. conf.Stack.P2P.ListenAddr = ExternalIP().String() + conf.Stack.P2P.ListenAddr
  339. }
  340. if conf.Stack.WSHost == "0.0.0.0" {
  341. conf.Stack.WSHost = ExternalIP().String()
  342. }
  343. // initialize the devp2p stack
  344. stack, err := node.New(&conf.Stack)
  345. if err != nil {
  346. log.Crit("error creating node stack", "err", err)
  347. }
  348. // register the services, collecting them into a map so we can wrap
  349. // them in a snapshot service
  350. services := make(map[string]node.Service, len(serviceNames))
  351. for _, name := range serviceNames {
  352. serviceFunc, exists := serviceFuncs[name]
  353. if !exists {
  354. log.Crit("unknown node service", "name", name)
  355. }
  356. constructor := func(nodeCtx *node.ServiceContext) (node.Service, error) {
  357. ctx := &ServiceContext{
  358. RPCDialer: &wsRPCDialer{addrs: conf.PeerAddrs},
  359. NodeContext: nodeCtx,
  360. Config: conf.Node,
  361. }
  362. if conf.Snapshots != nil {
  363. ctx.Snapshot = conf.Snapshots[name]
  364. }
  365. service, err := serviceFunc(ctx)
  366. if err != nil {
  367. return nil, err
  368. }
  369. services[name] = service
  370. return service, nil
  371. }
  372. if err := stack.Register(constructor); err != nil {
  373. log.Crit("error starting service", "name", name, "err", err)
  374. }
  375. }
  376. // register the snapshot service
  377. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  378. return &snapshotService{services}, nil
  379. }); err != nil {
  380. log.Crit("error starting snapshot service", "err", err)
  381. }
  382. // start the stack
  383. if err := stack.Start(); err != nil {
  384. log.Crit("error stating node stack", "err", err)
  385. }
  386. // stop the stack if we get a SIGTERM signal
  387. go func() {
  388. sigc := make(chan os.Signal, 1)
  389. signal.Notify(sigc, syscall.SIGTERM)
  390. defer signal.Stop(sigc)
  391. <-sigc
  392. log.Info("Received SIGTERM, shutting down...")
  393. stack.Stop()
  394. }()
  395. // wait for the stack to exit
  396. stack.Wait()
  397. }
  398. // snapshotService is a node.Service which wraps a list of services and
  399. // exposes an API to generate a snapshot of those services
  400. type snapshotService struct {
  401. services map[string]node.Service
  402. }
  403. func (s *snapshotService) APIs() []rpc.API {
  404. return []rpc.API{{
  405. Namespace: "simulation",
  406. Version: "1.0",
  407. Service: SnapshotAPI{s.services},
  408. }}
  409. }
  410. func (s *snapshotService) Protocols() []p2p.Protocol {
  411. return nil
  412. }
  413. func (s *snapshotService) Start(*p2p.Server) error {
  414. return nil
  415. }
  416. func (s *snapshotService) Stop() error {
  417. return nil
  418. }
  419. // SnapshotAPI provides an RPC method to create snapshots of services
  420. type SnapshotAPI struct {
  421. services map[string]node.Service
  422. }
  423. func (api SnapshotAPI) Snapshot() (map[string][]byte, error) {
  424. snapshots := make(map[string][]byte)
  425. for name, service := range api.services {
  426. if s, ok := service.(interface {
  427. Snapshot() ([]byte, error)
  428. }); ok {
  429. snap, err := s.Snapshot()
  430. if err != nil {
  431. return nil, err
  432. }
  433. snapshots[name] = snap
  434. }
  435. }
  436. return snapshots, nil
  437. }
  438. type wsRPCDialer struct {
  439. addrs map[string]string
  440. }
  441. // DialRPC implements the RPCDialer interface by creating a WebSocket RPC
  442. // client of the given node
  443. func (w *wsRPCDialer) DialRPC(id discover.NodeID) (*rpc.Client, error) {
  444. addr, ok := w.addrs[id.String()]
  445. if !ok {
  446. return nil, fmt.Errorf("unknown node: %s", id)
  447. }
  448. return rpc.DialWebsocket(context.Background(), addr, "http://localhost")
  449. }