node.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. // Copyright 2015 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 node
  17. import (
  18. "errors"
  19. "fmt"
  20. "net/http"
  21. "os"
  22. "path/filepath"
  23. "reflect"
  24. "strings"
  25. "sync"
  26. "github.com/ethereum/go-ethereum/accounts"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/ethdb"
  29. "github.com/ethereum/go-ethereum/event"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/p2p"
  32. "github.com/ethereum/go-ethereum/rpc"
  33. "github.com/prometheus/tsdb/fileutil"
  34. )
  35. // Node is a container on which services can be registered.
  36. type Node struct {
  37. eventmux *event.TypeMux
  38. config *Config
  39. accman *accounts.Manager
  40. log log.Logger
  41. ephemKeystore string // if non-empty, the key directory that will be removed by Stop
  42. dirLock fileutil.Releaser // prevents concurrent use of instance directory
  43. stop chan struct{} // Channel to wait for termination notifications
  44. server *p2p.Server // Currently running P2P networking layer
  45. startStopLock sync.Mutex // Start/Stop are protected by an additional lock
  46. state int // Tracks state of node lifecycle
  47. lock sync.Mutex
  48. lifecycles []Lifecycle // All registered backends, services, and auxiliary services that have a lifecycle
  49. rpcAPIs []rpc.API // List of APIs currently provided by the node
  50. http *httpServer //
  51. ws *httpServer //
  52. ipc *ipcServer // Stores information about the ipc http server
  53. inprocHandler *rpc.Server // In-process RPC request handler to process the API requests
  54. databases map[*closeTrackingDB]struct{} // All open databases
  55. }
  56. const (
  57. initializingState = iota
  58. runningState
  59. closedState
  60. )
  61. // New creates a new P2P node, ready for protocol registration.
  62. func New(conf *Config) (*Node, error) {
  63. // Copy config and resolve the datadir so future changes to the current
  64. // working directory don't affect the node.
  65. confCopy := *conf
  66. conf = &confCopy
  67. if conf.DataDir != "" {
  68. absdatadir, err := filepath.Abs(conf.DataDir)
  69. if err != nil {
  70. return nil, err
  71. }
  72. conf.DataDir = absdatadir
  73. }
  74. if conf.Logger == nil {
  75. conf.Logger = log.New()
  76. }
  77. // Ensure that the instance name doesn't cause weird conflicts with
  78. // other files in the data directory.
  79. if strings.ContainsAny(conf.Name, `/\`) {
  80. return nil, errors.New(`Config.Name must not contain '/' or '\'`)
  81. }
  82. if conf.Name == datadirDefaultKeyStore {
  83. return nil, errors.New(`Config.Name cannot be "` + datadirDefaultKeyStore + `"`)
  84. }
  85. if strings.HasSuffix(conf.Name, ".ipc") {
  86. return nil, errors.New(`Config.Name cannot end in ".ipc"`)
  87. }
  88. node := &Node{
  89. config: conf,
  90. inprocHandler: rpc.NewServer(),
  91. eventmux: new(event.TypeMux),
  92. log: conf.Logger,
  93. stop: make(chan struct{}),
  94. server: &p2p.Server{Config: conf.P2P},
  95. databases: make(map[*closeTrackingDB]struct{}),
  96. }
  97. // Register built-in APIs.
  98. node.rpcAPIs = append(node.rpcAPIs, node.apis()...)
  99. // Acquire the instance directory lock.
  100. if err := node.openDataDir(); err != nil {
  101. return nil, err
  102. }
  103. // Ensure that the AccountManager method works before the node has started. We rely on
  104. // this in cmd/geth.
  105. am, ephemeralKeystore, err := makeAccountManager(conf)
  106. if err != nil {
  107. return nil, err
  108. }
  109. node.accman = am
  110. node.ephemKeystore = ephemeralKeystore
  111. // Initialize the p2p server. This creates the node key and discovery databases.
  112. node.server.Config.PrivateKey = node.config.NodeKey()
  113. node.server.Config.Name = node.config.NodeName()
  114. node.server.Config.Logger = node.log
  115. if node.server.Config.StaticNodes == nil {
  116. node.server.Config.StaticNodes = node.config.StaticNodes()
  117. }
  118. if node.server.Config.TrustedNodes == nil {
  119. node.server.Config.TrustedNodes = node.config.TrustedNodes()
  120. }
  121. if node.server.Config.NodeDatabase == "" {
  122. node.server.Config.NodeDatabase = node.config.NodeDB()
  123. }
  124. // Check HTTP/WS prefixes are valid.
  125. if err := validatePrefix("HTTP", conf.HTTPPathPrefix); err != nil {
  126. return nil, err
  127. }
  128. if err := validatePrefix("WebSocket", conf.WSPathPrefix); err != nil {
  129. return nil, err
  130. }
  131. // Configure RPC servers.
  132. node.http = newHTTPServer(node.log, conf.HTTPTimeouts)
  133. node.ws = newHTTPServer(node.log, rpc.DefaultHTTPTimeouts)
  134. node.ipc = newIPCServer(node.log, conf.IPCEndpoint())
  135. return node, nil
  136. }
  137. // Start starts all registered lifecycles, RPC services and p2p networking.
  138. // Node can only be started once.
  139. func (n *Node) Start() error {
  140. n.startStopLock.Lock()
  141. defer n.startStopLock.Unlock()
  142. n.lock.Lock()
  143. switch n.state {
  144. case runningState:
  145. n.lock.Unlock()
  146. return ErrNodeRunning
  147. case closedState:
  148. n.lock.Unlock()
  149. return ErrNodeStopped
  150. }
  151. n.state = runningState
  152. // open networking and RPC endpoints
  153. err := n.openEndpoints()
  154. lifecycles := make([]Lifecycle, len(n.lifecycles))
  155. copy(lifecycles, n.lifecycles)
  156. n.lock.Unlock()
  157. // Check if endpoint startup failed.
  158. if err != nil {
  159. n.doClose(nil)
  160. return err
  161. }
  162. // Start all registered lifecycles.
  163. var started []Lifecycle
  164. for _, lifecycle := range lifecycles {
  165. if err = lifecycle.Start(); err != nil {
  166. break
  167. }
  168. started = append(started, lifecycle)
  169. }
  170. // Check if any lifecycle failed to start.
  171. if err != nil {
  172. n.stopServices(started)
  173. n.doClose(nil)
  174. }
  175. return err
  176. }
  177. // Close stops the Node and releases resources acquired in
  178. // Node constructor New.
  179. func (n *Node) Close() error {
  180. n.startStopLock.Lock()
  181. defer n.startStopLock.Unlock()
  182. n.lock.Lock()
  183. state := n.state
  184. n.lock.Unlock()
  185. switch state {
  186. case initializingState:
  187. // The node was never started.
  188. return n.doClose(nil)
  189. case runningState:
  190. // The node was started, release resources acquired by Start().
  191. var errs []error
  192. if err := n.stopServices(n.lifecycles); err != nil {
  193. errs = append(errs, err)
  194. }
  195. return n.doClose(errs)
  196. case closedState:
  197. return ErrNodeStopped
  198. default:
  199. panic(fmt.Sprintf("node is in unknown state %d", state))
  200. }
  201. }
  202. // doClose releases resources acquired by New(), collecting errors.
  203. func (n *Node) doClose(errs []error) error {
  204. // Close databases. This needs the lock because it needs to
  205. // synchronize with OpenDatabase*.
  206. n.lock.Lock()
  207. n.state = closedState
  208. errs = append(errs, n.closeDatabases()...)
  209. n.lock.Unlock()
  210. if err := n.accman.Close(); err != nil {
  211. errs = append(errs, err)
  212. }
  213. if n.ephemKeystore != "" {
  214. if err := os.RemoveAll(n.ephemKeystore); err != nil {
  215. errs = append(errs, err)
  216. }
  217. }
  218. // Release instance directory lock.
  219. n.closeDataDir()
  220. // Unblock n.Wait.
  221. close(n.stop)
  222. // Report any errors that might have occurred.
  223. switch len(errs) {
  224. case 0:
  225. return nil
  226. case 1:
  227. return errs[0]
  228. default:
  229. return fmt.Errorf("%v", errs)
  230. }
  231. }
  232. // openEndpoints starts all network and RPC endpoints.
  233. func (n *Node) openEndpoints() error {
  234. // start networking endpoints
  235. n.log.Info("Starting peer-to-peer node", "instance", n.server.Name)
  236. if err := n.server.Start(); err != nil {
  237. return convertFileLockError(err)
  238. }
  239. // start RPC endpoints
  240. err := n.startRPC()
  241. if err != nil {
  242. n.stopRPC()
  243. n.server.Stop()
  244. }
  245. return err
  246. }
  247. // containsLifecycle checks if 'lfs' contains 'l'.
  248. func containsLifecycle(lfs []Lifecycle, l Lifecycle) bool {
  249. for _, obj := range lfs {
  250. if obj == l {
  251. return true
  252. }
  253. }
  254. return false
  255. }
  256. // stopServices terminates running services, RPC and p2p networking.
  257. // It is the inverse of Start.
  258. func (n *Node) stopServices(running []Lifecycle) error {
  259. n.stopRPC()
  260. // Stop running lifecycles in reverse order.
  261. failure := &StopError{Services: make(map[reflect.Type]error)}
  262. for i := len(running) - 1; i >= 0; i-- {
  263. if err := running[i].Stop(); err != nil {
  264. failure.Services[reflect.TypeOf(running[i])] = err
  265. }
  266. }
  267. // Stop p2p networking.
  268. n.server.Stop()
  269. if len(failure.Services) > 0 {
  270. return failure
  271. }
  272. return nil
  273. }
  274. func (n *Node) openDataDir() error {
  275. if n.config.DataDir == "" {
  276. return nil // ephemeral
  277. }
  278. instdir := filepath.Join(n.config.DataDir, n.config.name())
  279. if err := os.MkdirAll(instdir, 0700); err != nil {
  280. return err
  281. }
  282. // Lock the instance directory to prevent concurrent use by another instance as well as
  283. // accidental use of the instance directory as a database.
  284. release, _, err := fileutil.Flock(filepath.Join(instdir, "LOCK"))
  285. if err != nil {
  286. return convertFileLockError(err)
  287. }
  288. n.dirLock = release
  289. return nil
  290. }
  291. func (n *Node) closeDataDir() {
  292. // Release instance directory lock.
  293. if n.dirLock != nil {
  294. if err := n.dirLock.Release(); err != nil {
  295. n.log.Error("Can't release datadir lock", "err", err)
  296. }
  297. n.dirLock = nil
  298. }
  299. }
  300. // configureRPC is a helper method to configure all the various RPC endpoints during node
  301. // startup. It's not meant to be called at any time afterwards as it makes certain
  302. // assumptions about the state of the node.
  303. func (n *Node) startRPC() error {
  304. if err := n.startInProc(); err != nil {
  305. return err
  306. }
  307. // Configure IPC.
  308. if n.ipc.endpoint != "" {
  309. if err := n.ipc.start(n.rpcAPIs); err != nil {
  310. return err
  311. }
  312. }
  313. // Configure HTTP.
  314. if n.config.HTTPHost != "" {
  315. config := httpConfig{
  316. CorsAllowedOrigins: n.config.HTTPCors,
  317. Vhosts: n.config.HTTPVirtualHosts,
  318. Modules: n.config.HTTPModules,
  319. prefix: n.config.HTTPPathPrefix,
  320. }
  321. if err := n.http.setListenAddr(n.config.HTTPHost, n.config.HTTPPort); err != nil {
  322. return err
  323. }
  324. if err := n.http.enableRPC(n.rpcAPIs, config); err != nil {
  325. return err
  326. }
  327. }
  328. // Configure WebSocket.
  329. if n.config.WSHost != "" {
  330. server := n.wsServerForPort(n.config.WSPort)
  331. config := wsConfig{
  332. Modules: n.config.WSModules,
  333. Origins: n.config.WSOrigins,
  334. prefix: n.config.WSPathPrefix,
  335. }
  336. if err := server.setListenAddr(n.config.WSHost, n.config.WSPort); err != nil {
  337. return err
  338. }
  339. if err := server.enableWS(n.rpcAPIs, config); err != nil {
  340. return err
  341. }
  342. }
  343. if err := n.http.start(); err != nil {
  344. return err
  345. }
  346. return n.ws.start()
  347. }
  348. func (n *Node) wsServerForPort(port int) *httpServer {
  349. if n.config.HTTPHost == "" || n.http.port == port {
  350. return n.http
  351. }
  352. return n.ws
  353. }
  354. func (n *Node) stopRPC() {
  355. n.http.stop()
  356. n.ws.stop()
  357. n.ipc.stop()
  358. n.stopInProc()
  359. }
  360. // startInProc registers all RPC APIs on the inproc server.
  361. func (n *Node) startInProc() error {
  362. for _, api := range n.rpcAPIs {
  363. if err := n.inprocHandler.RegisterName(api.Namespace, api.Service); err != nil {
  364. return err
  365. }
  366. }
  367. return nil
  368. }
  369. // stopInProc terminates the in-process RPC endpoint.
  370. func (n *Node) stopInProc() {
  371. n.inprocHandler.Stop()
  372. }
  373. // Wait blocks until the node is closed.
  374. func (n *Node) Wait() {
  375. <-n.stop
  376. }
  377. // RegisterLifecycle registers the given Lifecycle on the node.
  378. func (n *Node) RegisterLifecycle(lifecycle Lifecycle) {
  379. n.lock.Lock()
  380. defer n.lock.Unlock()
  381. if n.state != initializingState {
  382. panic("can't register lifecycle on running/stopped node")
  383. }
  384. if containsLifecycle(n.lifecycles, lifecycle) {
  385. panic(fmt.Sprintf("attempt to register lifecycle %T more than once", lifecycle))
  386. }
  387. n.lifecycles = append(n.lifecycles, lifecycle)
  388. }
  389. // RegisterProtocols adds backend's protocols to the node's p2p server.
  390. func (n *Node) RegisterProtocols(protocols []p2p.Protocol) {
  391. n.lock.Lock()
  392. defer n.lock.Unlock()
  393. if n.state != initializingState {
  394. panic("can't register protocols on running/stopped node")
  395. }
  396. n.server.Protocols = append(n.server.Protocols, protocols...)
  397. }
  398. // RegisterAPIs registers the APIs a service provides on the node.
  399. func (n *Node) RegisterAPIs(apis []rpc.API) {
  400. n.lock.Lock()
  401. defer n.lock.Unlock()
  402. if n.state != initializingState {
  403. panic("can't register APIs on running/stopped node")
  404. }
  405. n.rpcAPIs = append(n.rpcAPIs, apis...)
  406. }
  407. // RegisterHandler mounts a handler on the given path on the canonical HTTP server.
  408. //
  409. // The name of the handler is shown in a log message when the HTTP server starts
  410. // and should be a descriptive term for the service provided by the handler.
  411. func (n *Node) RegisterHandler(name, path string, handler http.Handler) {
  412. n.lock.Lock()
  413. defer n.lock.Unlock()
  414. if n.state != initializingState {
  415. panic("can't register HTTP handler on running/stopped node")
  416. }
  417. n.http.mux.Handle(path, handler)
  418. n.http.handlerNames[path] = name
  419. }
  420. // Attach creates an RPC client attached to an in-process API handler.
  421. func (n *Node) Attach() (*rpc.Client, error) {
  422. return rpc.DialInProc(n.inprocHandler), nil
  423. }
  424. // RPCHandler returns the in-process RPC request handler.
  425. func (n *Node) RPCHandler() (*rpc.Server, error) {
  426. n.lock.Lock()
  427. defer n.lock.Unlock()
  428. if n.state == closedState {
  429. return nil, ErrNodeStopped
  430. }
  431. return n.inprocHandler, nil
  432. }
  433. // Config returns the configuration of node.
  434. func (n *Node) Config() *Config {
  435. return n.config
  436. }
  437. // Server retrieves the currently running P2P network layer. This method is meant
  438. // only to inspect fields of the currently running server. Callers should not
  439. // start or stop the returned server.
  440. func (n *Node) Server() *p2p.Server {
  441. n.lock.Lock()
  442. defer n.lock.Unlock()
  443. return n.server
  444. }
  445. // DataDir retrieves the current datadir used by the protocol stack.
  446. // Deprecated: No files should be stored in this directory, use InstanceDir instead.
  447. func (n *Node) DataDir() string {
  448. return n.config.DataDir
  449. }
  450. // InstanceDir retrieves the instance directory used by the protocol stack.
  451. func (n *Node) InstanceDir() string {
  452. return n.config.instanceDir()
  453. }
  454. // AccountManager retrieves the account manager used by the protocol stack.
  455. func (n *Node) AccountManager() *accounts.Manager {
  456. return n.accman
  457. }
  458. // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
  459. func (n *Node) IPCEndpoint() string {
  460. return n.ipc.endpoint
  461. }
  462. // HTTPEndpoint returns the URL of the HTTP server. Note that this URL does not
  463. // contain the JSON-RPC path prefix set by HTTPPathPrefix.
  464. func (n *Node) HTTPEndpoint() string {
  465. return "http://" + n.http.listenAddr()
  466. }
  467. // WSEndpoint returns the current JSON-RPC over WebSocket endpoint.
  468. func (n *Node) WSEndpoint() string {
  469. if n.http.wsAllowed() {
  470. return "ws://" + n.http.listenAddr() + n.http.wsConfig.prefix
  471. }
  472. return "ws://" + n.ws.listenAddr() + n.ws.wsConfig.prefix
  473. }
  474. // EventMux retrieves the event multiplexer used by all the network services in
  475. // the current protocol stack.
  476. func (n *Node) EventMux() *event.TypeMux {
  477. return n.eventmux
  478. }
  479. // OpenDatabase opens an existing database with the given name (or creates one if no
  480. // previous can be found) from within the node's instance directory. If the node is
  481. // ephemeral, a memory database is returned.
  482. func (n *Node) OpenDatabase(name string, cache, handles int, namespace string) (ethdb.Database, error) {
  483. n.lock.Lock()
  484. defer n.lock.Unlock()
  485. if n.state == closedState {
  486. return nil, ErrNodeStopped
  487. }
  488. var db ethdb.Database
  489. var err error
  490. if n.config.DataDir == "" {
  491. db = rawdb.NewMemoryDatabase()
  492. } else {
  493. db, err = rawdb.NewLevelDBDatabase(n.ResolvePath(name), cache, handles, namespace)
  494. }
  495. if err == nil {
  496. db = n.wrapDatabase(db)
  497. }
  498. return db, err
  499. }
  500. // OpenDatabaseWithFreezer opens an existing database with the given name (or
  501. // creates one if no previous can be found) from within the node's data directory,
  502. // also attaching a chain freezer to it that moves ancient chain data from the
  503. // database to immutable append-only files. If the node is an ephemeral one, a
  504. // memory database is returned.
  505. func (n *Node) OpenDatabaseWithFreezer(name string, cache, handles int, freezer, namespace string) (ethdb.Database, error) {
  506. n.lock.Lock()
  507. defer n.lock.Unlock()
  508. if n.state == closedState {
  509. return nil, ErrNodeStopped
  510. }
  511. var db ethdb.Database
  512. var err error
  513. if n.config.DataDir == "" {
  514. db = rawdb.NewMemoryDatabase()
  515. } else {
  516. root := n.ResolvePath(name)
  517. switch {
  518. case freezer == "":
  519. freezer = filepath.Join(root, "ancient")
  520. case !filepath.IsAbs(freezer):
  521. freezer = n.ResolvePath(freezer)
  522. }
  523. db, err = rawdb.NewLevelDBDatabaseWithFreezer(root, cache, handles, freezer, namespace)
  524. }
  525. if err == nil {
  526. db = n.wrapDatabase(db)
  527. }
  528. return db, err
  529. }
  530. // ResolvePath returns the absolute path of a resource in the instance directory.
  531. func (n *Node) ResolvePath(x string) string {
  532. return n.config.ResolvePath(x)
  533. }
  534. // closeTrackingDB wraps the Close method of a database. When the database is closed by the
  535. // service, the wrapper removes it from the node's database map. This ensures that Node
  536. // won't auto-close the database if it is closed by the service that opened it.
  537. type closeTrackingDB struct {
  538. ethdb.Database
  539. n *Node
  540. }
  541. func (db *closeTrackingDB) Close() error {
  542. db.n.lock.Lock()
  543. delete(db.n.databases, db)
  544. db.n.lock.Unlock()
  545. return db.Database.Close()
  546. }
  547. // wrapDatabase ensures the database will be auto-closed when Node is closed.
  548. func (n *Node) wrapDatabase(db ethdb.Database) ethdb.Database {
  549. wrapper := &closeTrackingDB{db, n}
  550. n.databases[wrapper] = struct{}{}
  551. return wrapper
  552. }
  553. // closeDatabases closes all open databases.
  554. func (n *Node) closeDatabases() (errors []error) {
  555. for db := range n.databases {
  556. delete(n.databases, db)
  557. if err := db.Database.Close(); err != nil {
  558. errors = append(errors, err)
  559. }
  560. }
  561. return errors
  562. }