nodestate.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. // Copyright 2020 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 nodestate
  17. import (
  18. "errors"
  19. "reflect"
  20. "sync"
  21. "time"
  22. "unsafe"
  23. "github.com/ethereum/go-ethereum/common/mclock"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/metrics"
  27. "github.com/ethereum/go-ethereum/p2p/enode"
  28. "github.com/ethereum/go-ethereum/p2p/enr"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. )
  31. var (
  32. ErrInvalidField = errors.New("invalid field type")
  33. ErrClosed = errors.New("already closed")
  34. )
  35. type (
  36. // NodeStateMachine implements a network node-related event subscription system.
  37. // It can assign binary state flags and fields of arbitrary type to each node and allows
  38. // subscriptions to flag/field changes which can also modify further flags and fields,
  39. // potentially triggering further subscriptions. An operation includes an initial change
  40. // and all resulting subsequent changes and always ends in a consistent global state.
  41. // It is initiated by a "top level" SetState/SetField call that blocks (also blocking other
  42. // top-level functions) until the operation is finished. Callbacks making further changes
  43. // should use the non-blocking SetStateSub/SetFieldSub functions. The tree of events
  44. // resulting from the initial changes is traversed in a breadth-first order, ensuring for
  45. // each subscription callback that all other callbacks caused by the same change triggering
  46. // the current callback are processed before anything is triggered by the changes made in the
  47. // current callback. In practice this logic ensures that all subscriptions "see" events in
  48. // the logical order, callbacks are never called concurrently and "back and forth" effects
  49. // are also possible. The state machine design should ensure that infinite event cycles
  50. // cannot happen.
  51. // The caller can also add timeouts assigned to a certain node and a subset of state flags.
  52. // If the timeout elapses, the flags are reset. If all relevant flags are reset then the timer
  53. // is dropped. State flags with no timeout are persisted in the database if the flag
  54. // descriptor enables saving. If a node has no state flags set at any moment then it is discarded.
  55. // Note: in order to avoid mutex deadlocks the callbacks should never lock a mutex that
  56. // might be locked when the top level SetState/SetField functions are called. If a function
  57. // potentially performs state/field changes then it is recommended to mention this fact in the
  58. // function description, along with whether it should run inside an operation callback.
  59. NodeStateMachine struct {
  60. started, closed bool
  61. lock sync.Mutex
  62. clock mclock.Clock
  63. db ethdb.KeyValueStore
  64. dbNodeKey []byte
  65. nodes map[enode.ID]*nodeInfo
  66. offlineCallbackList []offlineCallback
  67. opFlag bool // an operation has started
  68. opWait *sync.Cond // signaled when the operation ends
  69. opPending []func() // pending callback list of the current operation
  70. // Registered state flags or fields. Modifications are allowed
  71. // only when the node state machine has not been started.
  72. setup *Setup
  73. fields []*fieldInfo
  74. saveFlags bitMask
  75. // Installed callbacks. Modifications are allowed only when the
  76. // node state machine has not been started.
  77. stateSubs []stateSub
  78. // Testing hooks, only for testing purposes.
  79. saveNodeHook func(*nodeInfo)
  80. }
  81. // Flags represents a set of flags from a certain setup
  82. Flags struct {
  83. mask bitMask
  84. setup *Setup
  85. }
  86. // Field represents a field from a certain setup
  87. Field struct {
  88. index int
  89. setup *Setup
  90. }
  91. // flagDefinition describes a node state flag. Each registered instance is automatically
  92. // mapped to a bit of the 64 bit node states.
  93. // If persistent is true then the node is saved when state machine is shutdown.
  94. flagDefinition struct {
  95. name string
  96. persistent bool
  97. }
  98. // fieldDefinition describes an optional node field of the given type. The contents
  99. // of the field are only retained for each node as long as at least one of the
  100. // state flags is set.
  101. fieldDefinition struct {
  102. name string
  103. ftype reflect.Type
  104. encode func(interface{}) ([]byte, error)
  105. decode func([]byte) (interface{}, error)
  106. }
  107. // stateSetup contains the list of flags and fields used by the application
  108. Setup struct {
  109. Version uint
  110. flags []flagDefinition
  111. fields []fieldDefinition
  112. }
  113. // bitMask describes a node state or state mask. It represents a subset
  114. // of node flags with each bit assigned to a flag index (LSB represents flag 0).
  115. bitMask uint64
  116. // StateCallback is a subscription callback which is called when one of the
  117. // state flags that is included in the subscription state mask is changed.
  118. // Note: oldState and newState are also masked with the subscription mask so only
  119. // the relevant bits are included.
  120. StateCallback func(n *enode.Node, oldState, newState Flags)
  121. // FieldCallback is a subscription callback which is called when the value of
  122. // a specific field is changed.
  123. FieldCallback func(n *enode.Node, state Flags, oldValue, newValue interface{})
  124. // nodeInfo contains node state, fields and state timeouts
  125. nodeInfo struct {
  126. node *enode.Node
  127. state bitMask
  128. timeouts []*nodeStateTimeout
  129. fields []interface{}
  130. fieldCount int
  131. db, dirty bool
  132. }
  133. nodeInfoEnc struct {
  134. Enr enr.Record
  135. Version uint
  136. State bitMask
  137. Fields [][]byte
  138. }
  139. stateSub struct {
  140. mask bitMask
  141. callback StateCallback
  142. }
  143. nodeStateTimeout struct {
  144. mask bitMask
  145. timer mclock.Timer
  146. }
  147. fieldInfo struct {
  148. fieldDefinition
  149. subs []FieldCallback
  150. }
  151. offlineCallback struct {
  152. node *nodeInfo
  153. state bitMask
  154. fields []interface{}
  155. }
  156. )
  157. // offlineState is a special state that is assumed to be set before a node is loaded from
  158. // the database and after it is shut down.
  159. const offlineState = bitMask(1)
  160. // NewFlag creates a new node state flag
  161. func (s *Setup) NewFlag(name string) Flags {
  162. if s.flags == nil {
  163. s.flags = []flagDefinition{{name: "offline"}}
  164. }
  165. f := Flags{mask: bitMask(1) << uint(len(s.flags)), setup: s}
  166. s.flags = append(s.flags, flagDefinition{name: name})
  167. return f
  168. }
  169. // NewPersistentFlag creates a new persistent node state flag
  170. func (s *Setup) NewPersistentFlag(name string) Flags {
  171. if s.flags == nil {
  172. s.flags = []flagDefinition{{name: "offline"}}
  173. }
  174. f := Flags{mask: bitMask(1) << uint(len(s.flags)), setup: s}
  175. s.flags = append(s.flags, flagDefinition{name: name, persistent: true})
  176. return f
  177. }
  178. // OfflineFlag returns the system-defined offline flag belonging to the given setup
  179. func (s *Setup) OfflineFlag() Flags {
  180. return Flags{mask: offlineState, setup: s}
  181. }
  182. // NewField creates a new node state field
  183. func (s *Setup) NewField(name string, ftype reflect.Type) Field {
  184. f := Field{index: len(s.fields), setup: s}
  185. s.fields = append(s.fields, fieldDefinition{
  186. name: name,
  187. ftype: ftype,
  188. })
  189. return f
  190. }
  191. // NewPersistentField creates a new persistent node field
  192. func (s *Setup) NewPersistentField(name string, ftype reflect.Type, encode func(interface{}) ([]byte, error), decode func([]byte) (interface{}, error)) Field {
  193. f := Field{index: len(s.fields), setup: s}
  194. s.fields = append(s.fields, fieldDefinition{
  195. name: name,
  196. ftype: ftype,
  197. encode: encode,
  198. decode: decode,
  199. })
  200. return f
  201. }
  202. // flagOp implements binary flag operations and also checks whether the operands belong to the same setup
  203. func flagOp(a, b Flags, trueIfA, trueIfB, trueIfBoth bool) Flags {
  204. if a.setup == nil {
  205. if a.mask != 0 {
  206. panic("Node state flags have no setup reference")
  207. }
  208. a.setup = b.setup
  209. }
  210. if b.setup == nil {
  211. if b.mask != 0 {
  212. panic("Node state flags have no setup reference")
  213. }
  214. b.setup = a.setup
  215. }
  216. if a.setup != b.setup {
  217. panic("Node state flags belong to a different setup")
  218. }
  219. res := Flags{setup: a.setup}
  220. if trueIfA {
  221. res.mask |= a.mask & ^b.mask
  222. }
  223. if trueIfB {
  224. res.mask |= b.mask & ^a.mask
  225. }
  226. if trueIfBoth {
  227. res.mask |= a.mask & b.mask
  228. }
  229. return res
  230. }
  231. // And returns the set of flags present in both a and b
  232. func (a Flags) And(b Flags) Flags { return flagOp(a, b, false, false, true) }
  233. // AndNot returns the set of flags present in a but not in b
  234. func (a Flags) AndNot(b Flags) Flags { return flagOp(a, b, true, false, false) }
  235. // Or returns the set of flags present in either a or b
  236. func (a Flags) Or(b Flags) Flags { return flagOp(a, b, true, true, true) }
  237. // Xor returns the set of flags present in either a or b but not both
  238. func (a Flags) Xor(b Flags) Flags { return flagOp(a, b, true, true, false) }
  239. // HasAll returns true if b is a subset of a
  240. func (a Flags) HasAll(b Flags) bool { return flagOp(a, b, false, true, false).mask == 0 }
  241. // HasNone returns true if a and b have no shared flags
  242. func (a Flags) HasNone(b Flags) bool { return flagOp(a, b, false, false, true).mask == 0 }
  243. // Equals returns true if a and b have the same flags set
  244. func (a Flags) Equals(b Flags) bool { return flagOp(a, b, true, true, false).mask == 0 }
  245. // IsEmpty returns true if a has no flags set
  246. func (a Flags) IsEmpty() bool { return a.mask == 0 }
  247. // MergeFlags merges multiple sets of state flags
  248. func MergeFlags(list ...Flags) Flags {
  249. if len(list) == 0 {
  250. return Flags{}
  251. }
  252. res := list[0]
  253. for i := 1; i < len(list); i++ {
  254. res = res.Or(list[i])
  255. }
  256. return res
  257. }
  258. // String returns a list of the names of the flags specified in the bit mask
  259. func (f Flags) String() string {
  260. if f.mask == 0 {
  261. return "[]"
  262. }
  263. s := "["
  264. comma := false
  265. for index, flag := range f.setup.flags {
  266. if f.mask&(bitMask(1)<<uint(index)) != 0 {
  267. if comma {
  268. s = s + ", "
  269. }
  270. s = s + flag.name
  271. comma = true
  272. }
  273. }
  274. s = s + "]"
  275. return s
  276. }
  277. // NewNodeStateMachine creates a new node state machine.
  278. // If db is not nil then the node states, fields and active timeouts are persisted.
  279. // Persistence can be enabled or disabled for each state flag and field.
  280. func NewNodeStateMachine(db ethdb.KeyValueStore, dbKey []byte, clock mclock.Clock, setup *Setup) *NodeStateMachine {
  281. if setup.flags == nil {
  282. panic("No state flags defined")
  283. }
  284. if len(setup.flags) > 8*int(unsafe.Sizeof(bitMask(0))) {
  285. panic("Too many node state flags")
  286. }
  287. ns := &NodeStateMachine{
  288. db: db,
  289. dbNodeKey: dbKey,
  290. clock: clock,
  291. setup: setup,
  292. nodes: make(map[enode.ID]*nodeInfo),
  293. fields: make([]*fieldInfo, len(setup.fields)),
  294. }
  295. ns.opWait = sync.NewCond(&ns.lock)
  296. stateNameMap := make(map[string]int)
  297. for index, flag := range setup.flags {
  298. if _, ok := stateNameMap[flag.name]; ok {
  299. panic("Node state flag name collision: " + flag.name)
  300. }
  301. stateNameMap[flag.name] = index
  302. if flag.persistent {
  303. ns.saveFlags |= bitMask(1) << uint(index)
  304. }
  305. }
  306. fieldNameMap := make(map[string]int)
  307. for index, field := range setup.fields {
  308. if _, ok := fieldNameMap[field.name]; ok {
  309. panic("Node field name collision: " + field.name)
  310. }
  311. ns.fields[index] = &fieldInfo{fieldDefinition: field}
  312. fieldNameMap[field.name] = index
  313. }
  314. return ns
  315. }
  316. // stateMask checks whether the set of flags belongs to the same setup and returns its internal bit mask
  317. func (ns *NodeStateMachine) stateMask(flags Flags) bitMask {
  318. if flags.setup != ns.setup && flags.mask != 0 {
  319. panic("Node state flags belong to a different setup")
  320. }
  321. return flags.mask
  322. }
  323. // fieldIndex checks whether the field belongs to the same setup and returns its internal index
  324. func (ns *NodeStateMachine) fieldIndex(field Field) int {
  325. if field.setup != ns.setup {
  326. panic("Node field belongs to a different setup")
  327. }
  328. return field.index
  329. }
  330. // SubscribeState adds a node state subscription. The callback is called while the state
  331. // machine mutex is not held and it is allowed to make further state updates using the
  332. // non-blocking SetStateSub/SetFieldSub functions. All callbacks of an operation are running
  333. // from the thread/goroutine of the initial caller and parallel operations are not permitted.
  334. // Therefore the callback is never called concurrently. It is the responsibility of the
  335. // implemented state logic to avoid deadlocks and to reach a stable state in a finite amount
  336. // of steps.
  337. // State subscriptions should be installed before loading the node database or making the
  338. // first state update.
  339. func (ns *NodeStateMachine) SubscribeState(flags Flags, callback StateCallback) {
  340. ns.lock.Lock()
  341. defer ns.lock.Unlock()
  342. if ns.started {
  343. panic("state machine already started")
  344. }
  345. ns.stateSubs = append(ns.stateSubs, stateSub{ns.stateMask(flags), callback})
  346. }
  347. // SubscribeField adds a node field subscription. Same rules apply as for SubscribeState.
  348. func (ns *NodeStateMachine) SubscribeField(field Field, callback FieldCallback) {
  349. ns.lock.Lock()
  350. defer ns.lock.Unlock()
  351. if ns.started {
  352. panic("state machine already started")
  353. }
  354. f := ns.fields[ns.fieldIndex(field)]
  355. f.subs = append(f.subs, callback)
  356. }
  357. // newNode creates a new nodeInfo
  358. func (ns *NodeStateMachine) newNode(n *enode.Node) *nodeInfo {
  359. return &nodeInfo{node: n, fields: make([]interface{}, len(ns.fields))}
  360. }
  361. // checkStarted checks whether the state machine has already been started and panics otherwise.
  362. func (ns *NodeStateMachine) checkStarted() {
  363. if !ns.started {
  364. panic("state machine not started yet")
  365. }
  366. }
  367. // Start starts the state machine, enabling state and field operations and disabling
  368. // further subscriptions.
  369. func (ns *NodeStateMachine) Start() {
  370. ns.lock.Lock()
  371. if ns.started {
  372. panic("state machine already started")
  373. }
  374. ns.started = true
  375. if ns.db != nil {
  376. ns.loadFromDb()
  377. }
  378. ns.opStart()
  379. ns.offlineCallbacks(true)
  380. ns.opFinish()
  381. ns.lock.Unlock()
  382. }
  383. // Stop stops the state machine and saves its state if a database was supplied
  384. func (ns *NodeStateMachine) Stop() {
  385. ns.lock.Lock()
  386. defer ns.lock.Unlock()
  387. ns.checkStarted()
  388. if !ns.opStart() {
  389. panic("already closed")
  390. }
  391. for _, node := range ns.nodes {
  392. fields := make([]interface{}, len(node.fields))
  393. copy(fields, node.fields)
  394. ns.offlineCallbackList = append(ns.offlineCallbackList, offlineCallback{node, node.state, fields})
  395. }
  396. if ns.db != nil {
  397. ns.saveToDb()
  398. }
  399. ns.offlineCallbacks(false)
  400. ns.closed = true
  401. ns.opFinish()
  402. }
  403. // loadFromDb loads persisted node states from the database
  404. func (ns *NodeStateMachine) loadFromDb() {
  405. it := ns.db.NewIterator(ns.dbNodeKey, nil)
  406. for it.Next() {
  407. var id enode.ID
  408. if len(it.Key()) != len(ns.dbNodeKey)+len(id) {
  409. log.Error("Node state db entry with invalid length", "found", len(it.Key()), "expected", len(ns.dbNodeKey)+len(id))
  410. continue
  411. }
  412. copy(id[:], it.Key()[len(ns.dbNodeKey):])
  413. ns.decodeNode(id, it.Value())
  414. }
  415. }
  416. type dummyIdentity enode.ID
  417. func (id dummyIdentity) Verify(r *enr.Record, sig []byte) error { return nil }
  418. func (id dummyIdentity) NodeAddr(r *enr.Record) []byte { return id[:] }
  419. // decodeNode decodes a node database entry and adds it to the node set if successful
  420. func (ns *NodeStateMachine) decodeNode(id enode.ID, data []byte) {
  421. var enc nodeInfoEnc
  422. if err := rlp.DecodeBytes(data, &enc); err != nil {
  423. log.Error("Failed to decode node info", "id", id, "error", err)
  424. return
  425. }
  426. n, _ := enode.New(dummyIdentity(id), &enc.Enr)
  427. node := ns.newNode(n)
  428. node.db = true
  429. if enc.Version != ns.setup.Version {
  430. log.Debug("Removing stored node with unknown version", "current", ns.setup.Version, "stored", enc.Version)
  431. ns.deleteNode(id)
  432. return
  433. }
  434. if len(enc.Fields) > len(ns.setup.fields) {
  435. log.Error("Invalid node field count", "id", id, "stored", len(enc.Fields))
  436. return
  437. }
  438. // Resolve persisted node fields
  439. for i, encField := range enc.Fields {
  440. if len(encField) == 0 {
  441. continue
  442. }
  443. if decode := ns.fields[i].decode; decode != nil {
  444. if field, err := decode(encField); err == nil {
  445. node.fields[i] = field
  446. node.fieldCount++
  447. } else {
  448. log.Error("Failed to decode node field", "id", id, "field name", ns.fields[i].name, "error", err)
  449. return
  450. }
  451. } else {
  452. log.Error("Cannot decode node field", "id", id, "field name", ns.fields[i].name)
  453. return
  454. }
  455. }
  456. // It's a compatible node record, add it to set.
  457. ns.nodes[id] = node
  458. node.state = enc.State
  459. fields := make([]interface{}, len(node.fields))
  460. copy(fields, node.fields)
  461. ns.offlineCallbackList = append(ns.offlineCallbackList, offlineCallback{node, node.state, fields})
  462. log.Debug("Loaded node state", "id", id, "state", Flags{mask: enc.State, setup: ns.setup})
  463. }
  464. // saveNode saves the given node info to the database
  465. func (ns *NodeStateMachine) saveNode(id enode.ID, node *nodeInfo) error {
  466. if ns.db == nil {
  467. return nil
  468. }
  469. storedState := node.state & ns.saveFlags
  470. for _, t := range node.timeouts {
  471. storedState &= ^t.mask
  472. }
  473. enc := nodeInfoEnc{
  474. Enr: *node.node.Record(),
  475. Version: ns.setup.Version,
  476. State: storedState,
  477. Fields: make([][]byte, len(ns.fields)),
  478. }
  479. log.Debug("Saved node state", "id", id, "state", Flags{mask: enc.State, setup: ns.setup})
  480. lastIndex := -1
  481. for i, f := range node.fields {
  482. if f == nil {
  483. continue
  484. }
  485. encode := ns.fields[i].encode
  486. if encode == nil {
  487. continue
  488. }
  489. blob, err := encode(f)
  490. if err != nil {
  491. return err
  492. }
  493. enc.Fields[i] = blob
  494. lastIndex = i
  495. }
  496. if storedState == 0 && lastIndex == -1 {
  497. if node.db {
  498. node.db = false
  499. ns.deleteNode(id)
  500. }
  501. node.dirty = false
  502. return nil
  503. }
  504. enc.Fields = enc.Fields[:lastIndex+1]
  505. data, err := rlp.EncodeToBytes(&enc)
  506. if err != nil {
  507. return err
  508. }
  509. if err := ns.db.Put(append(ns.dbNodeKey, id[:]...), data); err != nil {
  510. return err
  511. }
  512. node.dirty, node.db = false, true
  513. if ns.saveNodeHook != nil {
  514. ns.saveNodeHook(node)
  515. }
  516. return nil
  517. }
  518. // deleteNode removes a node info from the database
  519. func (ns *NodeStateMachine) deleteNode(id enode.ID) {
  520. ns.db.Delete(append(ns.dbNodeKey, id[:]...))
  521. }
  522. // saveToDb saves the persistent flags and fields of all nodes that have been changed
  523. func (ns *NodeStateMachine) saveToDb() {
  524. for id, node := range ns.nodes {
  525. if node.dirty {
  526. err := ns.saveNode(id, node)
  527. if err != nil {
  528. log.Error("Failed to save node", "id", id, "error", err)
  529. }
  530. }
  531. }
  532. }
  533. // updateEnode updates the enode entry belonging to the given node if it already exists
  534. func (ns *NodeStateMachine) updateEnode(n *enode.Node) (enode.ID, *nodeInfo) {
  535. id := n.ID()
  536. node := ns.nodes[id]
  537. if node != nil && n.Seq() > node.node.Seq() {
  538. node.node = n
  539. node.dirty = true
  540. }
  541. return id, node
  542. }
  543. // Persist saves the persistent state and fields of the given node immediately
  544. func (ns *NodeStateMachine) Persist(n *enode.Node) error {
  545. ns.lock.Lock()
  546. defer ns.lock.Unlock()
  547. ns.checkStarted()
  548. if id, node := ns.updateEnode(n); node != nil && node.dirty {
  549. err := ns.saveNode(id, node)
  550. if err != nil {
  551. log.Error("Failed to save node", "id", id, "error", err)
  552. }
  553. return err
  554. }
  555. return nil
  556. }
  557. // SetState updates the given node state flags and blocks until the operation is finished.
  558. // If a flag with a timeout is set again, the operation removes or replaces the existing timeout.
  559. func (ns *NodeStateMachine) SetState(n *enode.Node, setFlags, resetFlags Flags, timeout time.Duration) error {
  560. ns.lock.Lock()
  561. defer ns.lock.Unlock()
  562. if !ns.opStart() {
  563. return ErrClosed
  564. }
  565. ns.setState(n, setFlags, resetFlags, timeout)
  566. ns.opFinish()
  567. return nil
  568. }
  569. // SetStateSub updates the given node state flags without blocking (should be called
  570. // from a subscription/operation callback).
  571. func (ns *NodeStateMachine) SetStateSub(n *enode.Node, setFlags, resetFlags Flags, timeout time.Duration) {
  572. ns.lock.Lock()
  573. defer ns.lock.Unlock()
  574. ns.opCheck()
  575. ns.setState(n, setFlags, resetFlags, timeout)
  576. }
  577. func (ns *NodeStateMachine) setState(n *enode.Node, setFlags, resetFlags Flags, timeout time.Duration) {
  578. ns.checkStarted()
  579. set, reset := ns.stateMask(setFlags), ns.stateMask(resetFlags)
  580. id, node := ns.updateEnode(n)
  581. if node == nil {
  582. if set == 0 {
  583. return
  584. }
  585. node = ns.newNode(n)
  586. ns.nodes[id] = node
  587. }
  588. oldState := node.state
  589. newState := (node.state & (^reset)) | set
  590. changed := oldState ^ newState
  591. node.state = newState
  592. // Remove the timeout callbacks for all reset and set flags,
  593. // even they are not existent(it's noop).
  594. ns.removeTimeouts(node, set|reset)
  595. // Register the timeout callback if required
  596. if timeout != 0 && set != 0 {
  597. ns.addTimeout(n, set, timeout)
  598. }
  599. if newState == oldState {
  600. return
  601. }
  602. if newState == 0 && node.fieldCount == 0 {
  603. delete(ns.nodes, id)
  604. if node.db {
  605. ns.deleteNode(id)
  606. }
  607. } else {
  608. if changed&ns.saveFlags != 0 {
  609. node.dirty = true
  610. }
  611. }
  612. callback := func() {
  613. for _, sub := range ns.stateSubs {
  614. if changed&sub.mask != 0 {
  615. sub.callback(n, Flags{mask: oldState & sub.mask, setup: ns.setup}, Flags{mask: newState & sub.mask, setup: ns.setup})
  616. }
  617. }
  618. }
  619. ns.opPending = append(ns.opPending, callback)
  620. }
  621. // opCheck checks whether an operation is active
  622. func (ns *NodeStateMachine) opCheck() {
  623. if !ns.opFlag {
  624. panic("Operation has not started")
  625. }
  626. }
  627. // opStart waits until other operations are finished and starts a new one
  628. func (ns *NodeStateMachine) opStart() bool {
  629. for ns.opFlag {
  630. ns.opWait.Wait()
  631. }
  632. if ns.closed {
  633. return false
  634. }
  635. ns.opFlag = true
  636. return true
  637. }
  638. // opFinish finishes the current operation by running all pending callbacks.
  639. // Callbacks resulting from a state/field change performed in a previous callback are always
  640. // put at the end of the pending list and therefore processed after all callbacks resulting
  641. // from the previous state/field change.
  642. func (ns *NodeStateMachine) opFinish() {
  643. for len(ns.opPending) != 0 {
  644. list := ns.opPending
  645. ns.lock.Unlock()
  646. for _, cb := range list {
  647. cb()
  648. }
  649. ns.lock.Lock()
  650. ns.opPending = ns.opPending[len(list):]
  651. }
  652. ns.opPending = nil
  653. ns.opFlag = false
  654. ns.opWait.Broadcast()
  655. }
  656. // Operation calls the given function as an operation callback. This allows the caller
  657. // to start an operation with multiple initial changes. The same rules apply as for
  658. // subscription callbacks.
  659. func (ns *NodeStateMachine) Operation(fn func()) error {
  660. ns.lock.Lock()
  661. started := ns.opStart()
  662. ns.lock.Unlock()
  663. if !started {
  664. return ErrClosed
  665. }
  666. fn()
  667. ns.lock.Lock()
  668. ns.opFinish()
  669. ns.lock.Unlock()
  670. return nil
  671. }
  672. // offlineCallbacks calls state update callbacks at startup or shutdown
  673. func (ns *NodeStateMachine) offlineCallbacks(start bool) {
  674. for _, cb := range ns.offlineCallbackList {
  675. cb := cb
  676. callback := func() {
  677. for _, sub := range ns.stateSubs {
  678. offState := offlineState & sub.mask
  679. onState := cb.state & sub.mask
  680. if offState == onState {
  681. continue
  682. }
  683. if start {
  684. sub.callback(cb.node.node, Flags{mask: offState, setup: ns.setup}, Flags{mask: onState, setup: ns.setup})
  685. } else {
  686. sub.callback(cb.node.node, Flags{mask: onState, setup: ns.setup}, Flags{mask: offState, setup: ns.setup})
  687. }
  688. }
  689. for i, f := range cb.fields {
  690. if f == nil || ns.fields[i].subs == nil {
  691. continue
  692. }
  693. for _, fsub := range ns.fields[i].subs {
  694. if start {
  695. fsub(cb.node.node, Flags{mask: offlineState, setup: ns.setup}, nil, f)
  696. } else {
  697. fsub(cb.node.node, Flags{mask: offlineState, setup: ns.setup}, f, nil)
  698. }
  699. }
  700. }
  701. }
  702. ns.opPending = append(ns.opPending, callback)
  703. }
  704. ns.offlineCallbackList = nil
  705. }
  706. // AddTimeout adds a node state timeout associated to the given state flag(s).
  707. // After the specified time interval, the relevant states will be reset.
  708. func (ns *NodeStateMachine) AddTimeout(n *enode.Node, flags Flags, timeout time.Duration) error {
  709. ns.lock.Lock()
  710. defer ns.lock.Unlock()
  711. ns.checkStarted()
  712. if ns.closed {
  713. return ErrClosed
  714. }
  715. ns.addTimeout(n, ns.stateMask(flags), timeout)
  716. return nil
  717. }
  718. // addTimeout adds a node state timeout associated to the given state flag(s).
  719. func (ns *NodeStateMachine) addTimeout(n *enode.Node, mask bitMask, timeout time.Duration) {
  720. _, node := ns.updateEnode(n)
  721. if node == nil {
  722. return
  723. }
  724. mask &= node.state
  725. if mask == 0 {
  726. return
  727. }
  728. ns.removeTimeouts(node, mask)
  729. t := &nodeStateTimeout{mask: mask}
  730. t.timer = ns.clock.AfterFunc(timeout, func() {
  731. ns.lock.Lock()
  732. defer ns.lock.Unlock()
  733. if !ns.opStart() {
  734. return
  735. }
  736. ns.setState(n, Flags{}, Flags{mask: t.mask, setup: ns.setup}, 0)
  737. ns.opFinish()
  738. })
  739. node.timeouts = append(node.timeouts, t)
  740. if mask&ns.saveFlags != 0 {
  741. node.dirty = true
  742. }
  743. }
  744. // removeTimeout removes node state timeouts associated to the given state flag(s).
  745. // If a timeout was associated to multiple flags which are not all included in the
  746. // specified remove mask then only the included flags are de-associated and the timer
  747. // stays active.
  748. func (ns *NodeStateMachine) removeTimeouts(node *nodeInfo, mask bitMask) {
  749. for i := 0; i < len(node.timeouts); i++ {
  750. t := node.timeouts[i]
  751. match := t.mask & mask
  752. if match == 0 {
  753. continue
  754. }
  755. t.mask -= match
  756. if t.mask != 0 {
  757. continue
  758. }
  759. t.timer.Stop()
  760. node.timeouts[i] = node.timeouts[len(node.timeouts)-1]
  761. node.timeouts = node.timeouts[:len(node.timeouts)-1]
  762. i--
  763. if match&ns.saveFlags != 0 {
  764. node.dirty = true
  765. }
  766. }
  767. }
  768. // GetField retrieves the given field of the given node. Note that when used in a
  769. // subscription callback the result can be out of sync with the state change represented
  770. // by the callback parameters so extra safety checks might be necessary.
  771. func (ns *NodeStateMachine) GetField(n *enode.Node, field Field) interface{} {
  772. ns.lock.Lock()
  773. defer ns.lock.Unlock()
  774. ns.checkStarted()
  775. if ns.closed {
  776. return nil
  777. }
  778. if _, node := ns.updateEnode(n); node != nil {
  779. return node.fields[ns.fieldIndex(field)]
  780. }
  781. return nil
  782. }
  783. // GetState retrieves the current state of the given node. Note that when used in a
  784. // subscription callback the result can be out of sync with the state change represented
  785. // by the callback parameters so extra safety checks might be necessary.
  786. func (ns *NodeStateMachine) GetState(n *enode.Node) Flags {
  787. ns.lock.Lock()
  788. defer ns.lock.Unlock()
  789. ns.checkStarted()
  790. if ns.closed {
  791. return Flags{}
  792. }
  793. if _, node := ns.updateEnode(n); node != nil {
  794. return Flags{mask: node.state, setup: ns.setup}
  795. }
  796. return Flags{}
  797. }
  798. // SetField sets the given field of the given node and blocks until the operation is finished
  799. func (ns *NodeStateMachine) SetField(n *enode.Node, field Field, value interface{}) error {
  800. ns.lock.Lock()
  801. defer ns.lock.Unlock()
  802. if !ns.opStart() {
  803. return ErrClosed
  804. }
  805. err := ns.setField(n, field, value)
  806. ns.opFinish()
  807. return err
  808. }
  809. // SetFieldSub sets the given field of the given node without blocking (should be called
  810. // from a subscription/operation callback).
  811. func (ns *NodeStateMachine) SetFieldSub(n *enode.Node, field Field, value interface{}) error {
  812. ns.lock.Lock()
  813. defer ns.lock.Unlock()
  814. ns.opCheck()
  815. return ns.setField(n, field, value)
  816. }
  817. func (ns *NodeStateMachine) setField(n *enode.Node, field Field, value interface{}) error {
  818. ns.checkStarted()
  819. id, node := ns.updateEnode(n)
  820. if node == nil {
  821. if value == nil {
  822. return nil
  823. }
  824. node = ns.newNode(n)
  825. ns.nodes[id] = node
  826. }
  827. fieldIndex := ns.fieldIndex(field)
  828. f := ns.fields[fieldIndex]
  829. if value != nil && reflect.TypeOf(value) != f.ftype {
  830. log.Error("Invalid field type", "type", reflect.TypeOf(value), "required", f.ftype)
  831. return ErrInvalidField
  832. }
  833. oldValue := node.fields[fieldIndex]
  834. if value == oldValue {
  835. return nil
  836. }
  837. if oldValue != nil {
  838. node.fieldCount--
  839. }
  840. if value != nil {
  841. node.fieldCount++
  842. }
  843. node.fields[fieldIndex] = value
  844. if node.state == 0 && node.fieldCount == 0 {
  845. delete(ns.nodes, id)
  846. if node.db {
  847. ns.deleteNode(id)
  848. }
  849. } else {
  850. if f.encode != nil {
  851. node.dirty = true
  852. }
  853. }
  854. state := node.state
  855. callback := func() {
  856. for _, cb := range f.subs {
  857. cb(n, Flags{mask: state, setup: ns.setup}, oldValue, value)
  858. }
  859. }
  860. ns.opPending = append(ns.opPending, callback)
  861. return nil
  862. }
  863. // ForEach calls the callback for each node having all of the required and none of the
  864. // disabled flags set.
  865. // Note that this callback is not an operation callback but ForEach can be called from an
  866. // Operation callback or Operation can also be called from a ForEach callback if necessary.
  867. func (ns *NodeStateMachine) ForEach(requireFlags, disableFlags Flags, cb func(n *enode.Node, state Flags)) {
  868. ns.lock.Lock()
  869. ns.checkStarted()
  870. type callback struct {
  871. node *enode.Node
  872. state bitMask
  873. }
  874. require, disable := ns.stateMask(requireFlags), ns.stateMask(disableFlags)
  875. var callbacks []callback
  876. for _, node := range ns.nodes {
  877. if node.state&require == require && node.state&disable == 0 {
  878. callbacks = append(callbacks, callback{node.node, node.state & (require | disable)})
  879. }
  880. }
  881. ns.lock.Unlock()
  882. for _, c := range callbacks {
  883. cb(c.node, Flags{mask: c.state, setup: ns.setup})
  884. }
  885. }
  886. // GetNode returns the enode currently associated with the given ID
  887. func (ns *NodeStateMachine) GetNode(id enode.ID) *enode.Node {
  888. ns.lock.Lock()
  889. defer ns.lock.Unlock()
  890. ns.checkStarted()
  891. if node := ns.nodes[id]; node != nil {
  892. return node.node
  893. }
  894. return nil
  895. }
  896. // AddLogMetrics adds logging and/or metrics for nodes entering, exiting and currently
  897. // being in a given set specified by required and disabled state flags
  898. func (ns *NodeStateMachine) AddLogMetrics(requireFlags, disableFlags Flags, name string, inMeter, outMeter metrics.Meter, gauge metrics.Gauge) {
  899. var count int64
  900. ns.SubscribeState(requireFlags.Or(disableFlags), func(n *enode.Node, oldState, newState Flags) {
  901. oldMatch := oldState.HasAll(requireFlags) && oldState.HasNone(disableFlags)
  902. newMatch := newState.HasAll(requireFlags) && newState.HasNone(disableFlags)
  903. if newMatch == oldMatch {
  904. return
  905. }
  906. if newMatch {
  907. count++
  908. if name != "" {
  909. log.Debug("Node entered", "set", name, "id", n.ID(), "count", count)
  910. }
  911. if inMeter != nil {
  912. inMeter.Mark(1)
  913. }
  914. } else {
  915. count--
  916. if name != "" {
  917. log.Debug("Node left", "set", name, "id", n.ID(), "count", count)
  918. }
  919. if outMeter != nil {
  920. outMeter.Mark(1)
  921. }
  922. }
  923. if gauge != nil {
  924. gauge.Update(count)
  925. }
  926. })
  927. }