node.go 19 KB

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