node.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. // Configure RPC servers.
  125. node.http = newHTTPServer(node.log, conf.HTTPTimeouts)
  126. node.ws = newHTTPServer(node.log, rpc.DefaultHTTPTimeouts)
  127. node.ipc = newIPCServer(node.log, conf.IPCEndpoint())
  128. return node, nil
  129. }
  130. // Start starts all registered lifecycles, RPC services and p2p networking.
  131. // Node can only be started once.
  132. func (n *Node) Start() error {
  133. n.startStopLock.Lock()
  134. defer n.startStopLock.Unlock()
  135. n.lock.Lock()
  136. switch n.state {
  137. case runningState:
  138. n.lock.Unlock()
  139. return ErrNodeRunning
  140. case closedState:
  141. n.lock.Unlock()
  142. return ErrNodeStopped
  143. }
  144. n.state = runningState
  145. // open networking and RPC endpoints
  146. err := n.openEndpoints()
  147. lifecycles := make([]Lifecycle, len(n.lifecycles))
  148. copy(lifecycles, n.lifecycles)
  149. n.lock.Unlock()
  150. // Check if endpoint startup failed.
  151. if err != nil {
  152. n.doClose(nil)
  153. return err
  154. }
  155. // Start all registered lifecycles.
  156. var started []Lifecycle
  157. for _, lifecycle := range lifecycles {
  158. if err = lifecycle.Start(); err != nil {
  159. break
  160. }
  161. started = append(started, lifecycle)
  162. }
  163. // Check if any lifecycle failed to start.
  164. if err != nil {
  165. n.stopServices(started)
  166. n.doClose(nil)
  167. }
  168. return err
  169. }
  170. // Close stops the Node and releases resources acquired in
  171. // Node constructor New.
  172. func (n *Node) Close() error {
  173. n.startStopLock.Lock()
  174. defer n.startStopLock.Unlock()
  175. n.lock.Lock()
  176. state := n.state
  177. n.lock.Unlock()
  178. switch state {
  179. case initializingState:
  180. // The node was never started.
  181. return n.doClose(nil)
  182. case runningState:
  183. // The node was started, release resources acquired by Start().
  184. var errs []error
  185. if err := n.stopServices(n.lifecycles); err != nil {
  186. errs = append(errs, err)
  187. }
  188. return n.doClose(errs)
  189. case closedState:
  190. return ErrNodeStopped
  191. default:
  192. panic(fmt.Sprintf("node is in unknown state %d", state))
  193. }
  194. }
  195. // doClose releases resources acquired by New(), collecting errors.
  196. func (n *Node) doClose(errs []error) error {
  197. // Close databases. This needs the lock because it needs to
  198. // synchronize with OpenDatabase*.
  199. n.lock.Lock()
  200. n.state = closedState
  201. errs = append(errs, n.closeDatabases()...)
  202. n.lock.Unlock()
  203. if err := n.accman.Close(); err != nil {
  204. errs = append(errs, err)
  205. }
  206. if n.ephemKeystore != "" {
  207. if err := os.RemoveAll(n.ephemKeystore); err != nil {
  208. errs = append(errs, err)
  209. }
  210. }
  211. // Release instance directory lock.
  212. n.closeDataDir()
  213. // Unblock n.Wait.
  214. close(n.stop)
  215. // Report any errors that might have occurred.
  216. switch len(errs) {
  217. case 0:
  218. return nil
  219. case 1:
  220. return errs[0]
  221. default:
  222. return fmt.Errorf("%v", errs)
  223. }
  224. }
  225. // openEndpoints starts all network and RPC endpoints.
  226. func (n *Node) openEndpoints() error {
  227. // start networking endpoints
  228. n.log.Info("Starting peer-to-peer node", "instance", n.server.Name)
  229. if err := n.server.Start(); err != nil {
  230. return convertFileLockError(err)
  231. }
  232. // start RPC endpoints
  233. err := n.startRPC()
  234. if err != nil {
  235. n.stopRPC()
  236. n.server.Stop()
  237. }
  238. return err
  239. }
  240. // containsLifecycle checks if 'lfs' contains 'l'.
  241. func containsLifecycle(lfs []Lifecycle, l Lifecycle) bool {
  242. for _, obj := range lfs {
  243. if obj == l {
  244. return true
  245. }
  246. }
  247. return false
  248. }
  249. // stopServices terminates running services, RPC and p2p networking.
  250. // It is the inverse of Start.
  251. func (n *Node) stopServices(running []Lifecycle) error {
  252. n.stopRPC()
  253. // Stop running lifecycles in reverse order.
  254. failure := &StopError{Services: make(map[reflect.Type]error)}
  255. for i := len(running) - 1; i >= 0; i-- {
  256. if err := running[i].Stop(); err != nil {
  257. failure.Services[reflect.TypeOf(running[i])] = err
  258. }
  259. }
  260. // Stop p2p networking.
  261. n.server.Stop()
  262. if len(failure.Services) > 0 {
  263. return failure
  264. }
  265. return nil
  266. }
  267. func (n *Node) openDataDir() error {
  268. if n.config.DataDir == "" {
  269. return nil // ephemeral
  270. }
  271. instdir := filepath.Join(n.config.DataDir, n.config.name())
  272. if err := os.MkdirAll(instdir, 0700); err != nil {
  273. return err
  274. }
  275. // Lock the instance directory to prevent concurrent use by another instance as well as
  276. // accidental use of the instance directory as a database.
  277. release, _, err := fileutil.Flock(filepath.Join(instdir, "LOCK"))
  278. if err != nil {
  279. return convertFileLockError(err)
  280. }
  281. n.dirLock = release
  282. return nil
  283. }
  284. func (n *Node) closeDataDir() {
  285. // Release instance directory lock.
  286. if n.dirLock != nil {
  287. if err := n.dirLock.Release(); err != nil {
  288. n.log.Error("Can't release datadir lock", "err", err)
  289. }
  290. n.dirLock = nil
  291. }
  292. }
  293. // configureRPC is a helper method to configure all the various RPC endpoints during node
  294. // startup. It's not meant to be called at any time afterwards as it makes certain
  295. // assumptions about the state of the node.
  296. func (n *Node) startRPC() error {
  297. if err := n.startInProc(); err != nil {
  298. return err
  299. }
  300. // Configure IPC.
  301. if n.ipc.endpoint != "" {
  302. if err := n.ipc.start(n.rpcAPIs); err != nil {
  303. return err
  304. }
  305. }
  306. // Configure HTTP.
  307. if n.config.HTTPHost != "" {
  308. config := httpConfig{
  309. CorsAllowedOrigins: n.config.HTTPCors,
  310. Vhosts: n.config.HTTPVirtualHosts,
  311. Modules: n.config.HTTPModules,
  312. }
  313. if err := n.http.setListenAddr(n.config.HTTPHost, n.config.HTTPPort); err != nil {
  314. return err
  315. }
  316. if err := n.http.enableRPC(n.rpcAPIs, config); err != nil {
  317. return err
  318. }
  319. }
  320. // Configure WebSocket.
  321. if n.config.WSHost != "" {
  322. server := n.wsServerForPort(n.config.WSPort)
  323. config := wsConfig{
  324. Modules: n.config.WSModules,
  325. Origins: n.config.WSOrigins,
  326. }
  327. if err := server.setListenAddr(n.config.WSHost, n.config.WSPort); err != nil {
  328. return err
  329. }
  330. if err := server.enableWS(n.rpcAPIs, config); err != nil {
  331. return err
  332. }
  333. }
  334. if err := n.http.start(); err != nil {
  335. return err
  336. }
  337. return n.ws.start()
  338. }
  339. func (n *Node) wsServerForPort(port int) *httpServer {
  340. if n.config.HTTPHost == "" || n.http.port == port {
  341. return n.http
  342. }
  343. return n.ws
  344. }
  345. func (n *Node) stopRPC() {
  346. n.http.stop()
  347. n.ws.stop()
  348. n.ipc.stop()
  349. n.stopInProc()
  350. }
  351. // startInProc registers all RPC APIs on the inproc server.
  352. func (n *Node) startInProc() error {
  353. for _, api := range n.rpcAPIs {
  354. if err := n.inprocHandler.RegisterName(api.Namespace, api.Service); err != nil {
  355. return err
  356. }
  357. }
  358. return nil
  359. }
  360. // stopInProc terminates the in-process RPC endpoint.
  361. func (n *Node) stopInProc() {
  362. n.inprocHandler.Stop()
  363. }
  364. // Wait blocks until the node is closed.
  365. func (n *Node) Wait() {
  366. <-n.stop
  367. }
  368. // RegisterLifecycle registers the given Lifecycle on the node.
  369. func (n *Node) RegisterLifecycle(lifecycle Lifecycle) {
  370. n.lock.Lock()
  371. defer n.lock.Unlock()
  372. if n.state != initializingState {
  373. panic("can't register lifecycle on running/stopped node")
  374. }
  375. if containsLifecycle(n.lifecycles, lifecycle) {
  376. panic(fmt.Sprintf("attempt to register lifecycle %T more than once", lifecycle))
  377. }
  378. n.lifecycles = append(n.lifecycles, lifecycle)
  379. }
  380. // RegisterProtocols adds backend's protocols to the node's p2p server.
  381. func (n *Node) RegisterProtocols(protocols []p2p.Protocol) {
  382. n.lock.Lock()
  383. defer n.lock.Unlock()
  384. if n.state != initializingState {
  385. panic("can't register protocols on running/stopped node")
  386. }
  387. n.server.Protocols = append(n.server.Protocols, protocols...)
  388. }
  389. // RegisterAPIs registers the APIs a service provides on the node.
  390. func (n *Node) RegisterAPIs(apis []rpc.API) {
  391. n.lock.Lock()
  392. defer n.lock.Unlock()
  393. if n.state != initializingState {
  394. panic("can't register APIs on running/stopped node")
  395. }
  396. n.rpcAPIs = append(n.rpcAPIs, apis...)
  397. }
  398. // RegisterHandler mounts a handler on the given path on the canonical HTTP server.
  399. //
  400. // The name of the handler is shown in a log message when the HTTP server starts
  401. // and should be a descriptive term for the service provided by the handler.
  402. func (n *Node) RegisterHandler(name, path string, handler http.Handler) {
  403. n.lock.Lock()
  404. defer n.lock.Unlock()
  405. if n.state != initializingState {
  406. panic("can't register HTTP handler on running/stopped node")
  407. }
  408. n.http.mux.Handle(path, handler)
  409. n.http.handlerNames[path] = name
  410. }
  411. // Attach creates an RPC client attached to an in-process API handler.
  412. func (n *Node) Attach() (*rpc.Client, error) {
  413. return rpc.DialInProc(n.inprocHandler), nil
  414. }
  415. // RPCHandler returns the in-process RPC request handler.
  416. func (n *Node) RPCHandler() (*rpc.Server, error) {
  417. n.lock.Lock()
  418. defer n.lock.Unlock()
  419. if n.state == closedState {
  420. return nil, ErrNodeStopped
  421. }
  422. return n.inprocHandler, nil
  423. }
  424. // Config returns the configuration of node.
  425. func (n *Node) Config() *Config {
  426. return n.config
  427. }
  428. // Server retrieves the currently running P2P network layer. This method is meant
  429. // only to inspect fields of the currently running server. Callers should not
  430. // start or stop the returned server.
  431. func (n *Node) Server() *p2p.Server {
  432. n.lock.Lock()
  433. defer n.lock.Unlock()
  434. return n.server
  435. }
  436. // DataDir retrieves the current datadir used by the protocol stack.
  437. // Deprecated: No files should be stored in this directory, use InstanceDir instead.
  438. func (n *Node) DataDir() string {
  439. return n.config.DataDir
  440. }
  441. // InstanceDir retrieves the instance directory used by the protocol stack.
  442. func (n *Node) InstanceDir() string {
  443. return n.config.instanceDir()
  444. }
  445. // AccountManager retrieves the account manager used by the protocol stack.
  446. func (n *Node) AccountManager() *accounts.Manager {
  447. return n.accman
  448. }
  449. // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
  450. func (n *Node) IPCEndpoint() string {
  451. return n.ipc.endpoint
  452. }
  453. // HTTPEndpoint returns the URL of the HTTP server.
  454. func (n *Node) HTTPEndpoint() string {
  455. return "http://" + n.http.listenAddr()
  456. }
  457. // WSEndpoint retrieves the current WS endpoint used by the protocol stack.
  458. func (n *Node) WSEndpoint() string {
  459. if n.http.wsAllowed() {
  460. return "ws://" + n.http.listenAddr()
  461. }
  462. return "ws://" + n.ws.listenAddr()
  463. }
  464. // EventMux retrieves the event multiplexer used by all the network services in
  465. // the current protocol stack.
  466. func (n *Node) EventMux() *event.TypeMux {
  467. return n.eventmux
  468. }
  469. // OpenDatabase opens an existing database with the given name (or creates one if no
  470. // previous can be found) from within the node's instance directory. If the node is
  471. // ephemeral, a memory database is returned.
  472. func (n *Node) OpenDatabase(name string, cache, handles int, namespace string) (ethdb.Database, error) {
  473. n.lock.Lock()
  474. defer n.lock.Unlock()
  475. if n.state == closedState {
  476. return nil, ErrNodeStopped
  477. }
  478. var db ethdb.Database
  479. var err error
  480. if n.config.DataDir == "" {
  481. db = rawdb.NewMemoryDatabase()
  482. } else {
  483. db, err = rawdb.NewLevelDBDatabase(n.ResolvePath(name), cache, handles, namespace)
  484. }
  485. if err == nil {
  486. db = n.wrapDatabase(db)
  487. }
  488. return db, err
  489. }
  490. // OpenDatabaseWithFreezer opens an existing database with the given name (or
  491. // creates one if no previous can be found) from within the node's data directory,
  492. // also attaching a chain freezer to it that moves ancient chain data from the
  493. // database to immutable append-only files. If the node is an ephemeral one, a
  494. // memory database is returned.
  495. func (n *Node) OpenDatabaseWithFreezer(name string, cache, handles int, freezer, namespace string) (ethdb.Database, error) {
  496. n.lock.Lock()
  497. defer n.lock.Unlock()
  498. if n.state == closedState {
  499. return nil, ErrNodeStopped
  500. }
  501. var db ethdb.Database
  502. var err error
  503. if n.config.DataDir == "" {
  504. db = rawdb.NewMemoryDatabase()
  505. } else {
  506. root := n.ResolvePath(name)
  507. switch {
  508. case freezer == "":
  509. freezer = filepath.Join(root, "ancient")
  510. case !filepath.IsAbs(freezer):
  511. freezer = n.ResolvePath(freezer)
  512. }
  513. db, err = rawdb.NewLevelDBDatabaseWithFreezer(root, cache, handles, freezer, namespace)
  514. }
  515. if err == nil {
  516. db = n.wrapDatabase(db)
  517. }
  518. return db, err
  519. }
  520. // ResolvePath returns the absolute path of a resource in the instance directory.
  521. func (n *Node) ResolvePath(x string) string {
  522. return n.config.ResolvePath(x)
  523. }
  524. // closeTrackingDB wraps the Close method of a database. When the database is closed by the
  525. // service, the wrapper removes it from the node's database map. This ensures that Node
  526. // won't auto-close the database if it is closed by the service that opened it.
  527. type closeTrackingDB struct {
  528. ethdb.Database
  529. n *Node
  530. }
  531. func (db *closeTrackingDB) Close() error {
  532. db.n.lock.Lock()
  533. delete(db.n.databases, db)
  534. db.n.lock.Unlock()
  535. return db.Database.Close()
  536. }
  537. // wrapDatabase ensures the database will be auto-closed when Node is closed.
  538. func (n *Node) wrapDatabase(db ethdb.Database) ethdb.Database {
  539. wrapper := &closeTrackingDB{db, n}
  540. n.databases[wrapper] = struct{}{}
  541. return wrapper
  542. }
  543. // closeDatabases closes all open databases.
  544. func (n *Node) closeDatabases() (errors []error) {
  545. for db := range n.databases {
  546. delete(n.databases, db)
  547. if err := db.Database.Close(); err != nil {
  548. errors = append(errors, err)
  549. }
  550. }
  551. return errors
  552. }