nodestate.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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.SetState(n, Flags{}, Flags{mask: t.mask, setup: ns.setup}, 0)
  732. })
  733. node.timeouts = append(node.timeouts, t)
  734. if mask&ns.saveFlags != 0 {
  735. node.dirty = true
  736. }
  737. }
  738. // removeTimeout removes node state timeouts associated to the given state flag(s).
  739. // If a timeout was associated to multiple flags which are not all included in the
  740. // specified remove mask then only the included flags are de-associated and the timer
  741. // stays active.
  742. func (ns *NodeStateMachine) removeTimeouts(node *nodeInfo, mask bitMask) {
  743. for i := 0; i < len(node.timeouts); i++ {
  744. t := node.timeouts[i]
  745. match := t.mask & mask
  746. if match == 0 {
  747. continue
  748. }
  749. t.mask -= match
  750. if t.mask != 0 {
  751. continue
  752. }
  753. t.timer.Stop()
  754. node.timeouts[i] = node.timeouts[len(node.timeouts)-1]
  755. node.timeouts = node.timeouts[:len(node.timeouts)-1]
  756. i--
  757. if match&ns.saveFlags != 0 {
  758. node.dirty = true
  759. }
  760. }
  761. }
  762. // GetField retrieves the given field of the given node. Note that when used in a
  763. // subscription callback the result can be out of sync with the state change represented
  764. // by the callback parameters so extra safety checks might be necessary.
  765. func (ns *NodeStateMachine) GetField(n *enode.Node, field Field) interface{} {
  766. ns.lock.Lock()
  767. defer ns.lock.Unlock()
  768. ns.checkStarted()
  769. if ns.closed {
  770. return nil
  771. }
  772. if _, node := ns.updateEnode(n); node != nil {
  773. return node.fields[ns.fieldIndex(field)]
  774. }
  775. return nil
  776. }
  777. // GetState retrieves the current state of the given node. Note that when used in a
  778. // subscription callback the result can be out of sync with the state change represented
  779. // by the callback parameters so extra safety checks might be necessary.
  780. func (ns *NodeStateMachine) GetState(n *enode.Node) Flags {
  781. ns.lock.Lock()
  782. defer ns.lock.Unlock()
  783. ns.checkStarted()
  784. if ns.closed {
  785. return Flags{}
  786. }
  787. if _, node := ns.updateEnode(n); node != nil {
  788. return Flags{mask: node.state, setup: ns.setup}
  789. }
  790. return Flags{}
  791. }
  792. // SetField sets the given field of the given node and blocks until the operation is finished
  793. func (ns *NodeStateMachine) SetField(n *enode.Node, field Field, value interface{}) error {
  794. ns.lock.Lock()
  795. defer ns.lock.Unlock()
  796. if !ns.opStart() {
  797. return ErrClosed
  798. }
  799. err := ns.setField(n, field, value)
  800. ns.opFinish()
  801. return err
  802. }
  803. // SetFieldSub sets the given field of the given node without blocking (should be called
  804. // from a subscription/operation callback).
  805. func (ns *NodeStateMachine) SetFieldSub(n *enode.Node, field Field, value interface{}) error {
  806. ns.lock.Lock()
  807. defer ns.lock.Unlock()
  808. ns.opCheck()
  809. return ns.setField(n, field, value)
  810. }
  811. func (ns *NodeStateMachine) setField(n *enode.Node, field Field, value interface{}) error {
  812. ns.checkStarted()
  813. id, node := ns.updateEnode(n)
  814. if node == nil {
  815. if value == nil {
  816. return nil
  817. }
  818. node = ns.newNode(n)
  819. ns.nodes[id] = node
  820. }
  821. fieldIndex := ns.fieldIndex(field)
  822. f := ns.fields[fieldIndex]
  823. if value != nil && reflect.TypeOf(value) != f.ftype {
  824. log.Error("Invalid field type", "type", reflect.TypeOf(value), "required", f.ftype)
  825. return ErrInvalidField
  826. }
  827. oldValue := node.fields[fieldIndex]
  828. if value == oldValue {
  829. return nil
  830. }
  831. if oldValue != nil {
  832. node.fieldCount--
  833. }
  834. if value != nil {
  835. node.fieldCount++
  836. }
  837. node.fields[fieldIndex] = value
  838. if node.state == 0 && node.fieldCount == 0 {
  839. delete(ns.nodes, id)
  840. if node.db {
  841. ns.deleteNode(id)
  842. }
  843. } else {
  844. if f.encode != nil {
  845. node.dirty = true
  846. }
  847. }
  848. state := node.state
  849. callback := func() {
  850. for _, cb := range f.subs {
  851. cb(n, Flags{mask: state, setup: ns.setup}, oldValue, value)
  852. }
  853. }
  854. ns.opPending = append(ns.opPending, callback)
  855. return nil
  856. }
  857. // ForEach calls the callback for each node having all of the required and none of the
  858. // disabled flags set.
  859. // Note that this callback is not an operation callback but ForEach can be called from an
  860. // Operation callback or Operation can also be called from a ForEach callback if necessary.
  861. func (ns *NodeStateMachine) ForEach(requireFlags, disableFlags Flags, cb func(n *enode.Node, state Flags)) {
  862. ns.lock.Lock()
  863. ns.checkStarted()
  864. type callback struct {
  865. node *enode.Node
  866. state bitMask
  867. }
  868. require, disable := ns.stateMask(requireFlags), ns.stateMask(disableFlags)
  869. var callbacks []callback
  870. for _, node := range ns.nodes {
  871. if node.state&require == require && node.state&disable == 0 {
  872. callbacks = append(callbacks, callback{node.node, node.state & (require | disable)})
  873. }
  874. }
  875. ns.lock.Unlock()
  876. for _, c := range callbacks {
  877. cb(c.node, Flags{mask: c.state, setup: ns.setup})
  878. }
  879. }
  880. // GetNode returns the enode currently associated with the given ID
  881. func (ns *NodeStateMachine) GetNode(id enode.ID) *enode.Node {
  882. ns.lock.Lock()
  883. defer ns.lock.Unlock()
  884. ns.checkStarted()
  885. if node := ns.nodes[id]; node != nil {
  886. return node.node
  887. }
  888. return nil
  889. }
  890. // AddLogMetrics adds logging and/or metrics for nodes entering, exiting and currently
  891. // being in a given set specified by required and disabled state flags
  892. func (ns *NodeStateMachine) AddLogMetrics(requireFlags, disableFlags Flags, name string, inMeter, outMeter metrics.Meter, gauge metrics.Gauge) {
  893. var count int64
  894. ns.SubscribeState(requireFlags.Or(disableFlags), func(n *enode.Node, oldState, newState Flags) {
  895. oldMatch := oldState.HasAll(requireFlags) && oldState.HasNone(disableFlags)
  896. newMatch := newState.HasAll(requireFlags) && newState.HasNone(disableFlags)
  897. if newMatch == oldMatch {
  898. return
  899. }
  900. if newMatch {
  901. count++
  902. if name != "" {
  903. log.Debug("Node entered", "set", name, "id", n.ID(), "count", count)
  904. }
  905. if inMeter != nil {
  906. inMeter.Mark(1)
  907. }
  908. } else {
  909. count--
  910. if name != "" {
  911. log.Debug("Node left", "set", name, "id", n.ID(), "count", count)
  912. }
  913. if outMeter != nil {
  914. outMeter.Mark(1)
  915. }
  916. }
  917. if gauge != nil {
  918. gauge.Update(count)
  919. }
  920. })
  921. }