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