node.go 18 KB

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