network.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. // Copyright 2017 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 simulations
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/json"
  21. "fmt"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/event"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/p2p"
  27. "github.com/ethereum/go-ethereum/p2p/discover"
  28. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  29. )
  30. var dialBanTimeout = 200 * time.Millisecond
  31. // NetworkConfig defines configuration options for starting a Network
  32. type NetworkConfig struct {
  33. ID string `json:"id"`
  34. DefaultService string `json:"default_service,omitempty"`
  35. }
  36. // Network models a p2p simulation network which consists of a collection of
  37. // simulated nodes and the connections which exist between them.
  38. //
  39. // The Network has a single NodeAdapter which is responsible for actually
  40. // starting nodes and connecting them together.
  41. //
  42. // The Network emits events when nodes are started and stopped, when they are
  43. // connected and disconnected, and also when messages are sent between nodes.
  44. type Network struct {
  45. NetworkConfig
  46. Nodes []*Node `json:"nodes"`
  47. nodeMap map[discover.NodeID]int
  48. Conns []*Conn `json:"conns"`
  49. connMap map[string]int
  50. nodeAdapter adapters.NodeAdapter
  51. events event.Feed
  52. lock sync.RWMutex
  53. quitc chan struct{}
  54. }
  55. // NewNetwork returns a Network which uses the given NodeAdapter and NetworkConfig
  56. func NewNetwork(nodeAdapter adapters.NodeAdapter, conf *NetworkConfig) *Network {
  57. return &Network{
  58. NetworkConfig: *conf,
  59. nodeAdapter: nodeAdapter,
  60. nodeMap: make(map[discover.NodeID]int),
  61. connMap: make(map[string]int),
  62. quitc: make(chan struct{}),
  63. }
  64. }
  65. // Events returns the output event feed of the Network.
  66. func (self *Network) Events() *event.Feed {
  67. return &self.events
  68. }
  69. // NewNode adds a new node to the network with a random ID
  70. func (self *Network) NewNode() (*Node, error) {
  71. conf := adapters.RandomNodeConfig()
  72. conf.Services = []string{self.DefaultService}
  73. return self.NewNodeWithConfig(conf)
  74. }
  75. // NewNodeWithConfig adds a new node to the network with the given config,
  76. // returning an error if a node with the same ID or name already exists
  77. func (self *Network) NewNodeWithConfig(conf *adapters.NodeConfig) (*Node, error) {
  78. self.lock.Lock()
  79. defer self.lock.Unlock()
  80. // create a random ID and PrivateKey if not set
  81. if conf.ID == (discover.NodeID{}) {
  82. c := adapters.RandomNodeConfig()
  83. conf.ID = c.ID
  84. conf.PrivateKey = c.PrivateKey
  85. }
  86. id := conf.ID
  87. if conf.Reachable == nil {
  88. conf.Reachable = func(otherID discover.NodeID) bool {
  89. _, err := self.InitConn(conf.ID, otherID)
  90. return err == nil
  91. }
  92. }
  93. // assign a name to the node if not set
  94. if conf.Name == "" {
  95. conf.Name = fmt.Sprintf("node%02d", len(self.Nodes)+1)
  96. }
  97. // check the node doesn't already exist
  98. if node := self.getNode(id); node != nil {
  99. return nil, fmt.Errorf("node with ID %q already exists", id)
  100. }
  101. if node := self.getNodeByName(conf.Name); node != nil {
  102. return nil, fmt.Errorf("node with name %q already exists", conf.Name)
  103. }
  104. // if no services are configured, use the default service
  105. if len(conf.Services) == 0 {
  106. conf.Services = []string{self.DefaultService}
  107. }
  108. // use the NodeAdapter to create the node
  109. adapterNode, err := self.nodeAdapter.NewNode(conf)
  110. if err != nil {
  111. return nil, err
  112. }
  113. node := &Node{
  114. Node: adapterNode,
  115. Config: conf,
  116. }
  117. log.Trace(fmt.Sprintf("node %v created", id))
  118. self.nodeMap[id] = len(self.Nodes)
  119. self.Nodes = append(self.Nodes, node)
  120. // emit a "control" event
  121. self.events.Send(ControlEvent(node))
  122. return node, nil
  123. }
  124. // Config returns the network configuration
  125. func (self *Network) Config() *NetworkConfig {
  126. return &self.NetworkConfig
  127. }
  128. // StartAll starts all nodes in the network
  129. func (self *Network) StartAll() error {
  130. for _, node := range self.Nodes {
  131. if node.Up {
  132. continue
  133. }
  134. if err := self.Start(node.ID()); err != nil {
  135. return err
  136. }
  137. }
  138. return nil
  139. }
  140. // StopAll stops all nodes in the network
  141. func (self *Network) StopAll() error {
  142. for _, node := range self.Nodes {
  143. if !node.Up {
  144. continue
  145. }
  146. if err := self.Stop(node.ID()); err != nil {
  147. return err
  148. }
  149. }
  150. return nil
  151. }
  152. // Start starts the node with the given ID
  153. func (self *Network) Start(id discover.NodeID) error {
  154. return self.startWithSnapshots(id, nil)
  155. }
  156. // startWithSnapshots starts the node with the given ID using the give
  157. // snapshots
  158. func (self *Network) startWithSnapshots(id discover.NodeID, snapshots map[string][]byte) error {
  159. node := self.GetNode(id)
  160. if node == nil {
  161. return fmt.Errorf("node %v does not exist", id)
  162. }
  163. if node.Up {
  164. return fmt.Errorf("node %v already up", id)
  165. }
  166. log.Trace(fmt.Sprintf("starting node %v: %v using %v", id, node.Up, self.nodeAdapter.Name()))
  167. if err := node.Start(snapshots); err != nil {
  168. log.Warn(fmt.Sprintf("start up failed: %v", err))
  169. return err
  170. }
  171. node.Up = true
  172. log.Info(fmt.Sprintf("started node %v: %v", id, node.Up))
  173. self.events.Send(NewEvent(node))
  174. // subscribe to peer events
  175. client, err := node.Client()
  176. if err != nil {
  177. return fmt.Errorf("error getting rpc client for node %v: %s", id, err)
  178. }
  179. events := make(chan *p2p.PeerEvent)
  180. sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents")
  181. if err != nil {
  182. return fmt.Errorf("error getting peer events for node %v: %s", id, err)
  183. }
  184. go self.watchPeerEvents(id, events, sub)
  185. return nil
  186. }
  187. // watchPeerEvents reads peer events from the given channel and emits
  188. // corresponding network events
  189. func (self *Network) watchPeerEvents(id discover.NodeID, events chan *p2p.PeerEvent, sub event.Subscription) {
  190. defer func() {
  191. sub.Unsubscribe()
  192. // assume the node is now down
  193. self.lock.Lock()
  194. node := self.getNode(id)
  195. node.Up = false
  196. self.lock.Unlock()
  197. self.events.Send(NewEvent(node))
  198. }()
  199. for {
  200. select {
  201. case event, ok := <-events:
  202. if !ok {
  203. return
  204. }
  205. peer := event.Peer
  206. switch event.Type {
  207. case p2p.PeerEventTypeAdd:
  208. self.DidConnect(id, peer)
  209. case p2p.PeerEventTypeDrop:
  210. self.DidDisconnect(id, peer)
  211. case p2p.PeerEventTypeMsgSend:
  212. self.DidSend(id, peer, event.Protocol, *event.MsgCode)
  213. case p2p.PeerEventTypeMsgRecv:
  214. self.DidReceive(peer, id, event.Protocol, *event.MsgCode)
  215. }
  216. case err := <-sub.Err():
  217. if err != nil {
  218. log.Error(fmt.Sprintf("error getting peer events for node %v", id), "err", err)
  219. }
  220. return
  221. }
  222. }
  223. }
  224. // Stop stops the node with the given ID
  225. func (self *Network) Stop(id discover.NodeID) error {
  226. node := self.GetNode(id)
  227. if node == nil {
  228. return fmt.Errorf("node %v does not exist", id)
  229. }
  230. if !node.Up {
  231. return fmt.Errorf("node %v already down", id)
  232. }
  233. if err := node.Stop(); err != nil {
  234. return err
  235. }
  236. node.Up = false
  237. log.Info(fmt.Sprintf("stop node %v: %v", id, node.Up))
  238. self.events.Send(ControlEvent(node))
  239. return nil
  240. }
  241. // Connect connects two nodes together by calling the "admin_addPeer" RPC
  242. // method on the "one" node so that it connects to the "other" node
  243. func (self *Network) Connect(oneID, otherID discover.NodeID) error {
  244. log.Debug(fmt.Sprintf("connecting %s to %s", oneID, otherID))
  245. conn, err := self.InitConn(oneID, otherID)
  246. if err != nil {
  247. return err
  248. }
  249. client, err := conn.one.Client()
  250. if err != nil {
  251. return err
  252. }
  253. self.events.Send(ControlEvent(conn))
  254. return client.Call(nil, "admin_addPeer", string(conn.other.Addr()))
  255. }
  256. // Disconnect disconnects two nodes by calling the "admin_removePeer" RPC
  257. // method on the "one" node so that it disconnects from the "other" node
  258. func (self *Network) Disconnect(oneID, otherID discover.NodeID) error {
  259. conn := self.GetConn(oneID, otherID)
  260. if conn == nil {
  261. return fmt.Errorf("connection between %v and %v does not exist", oneID, otherID)
  262. }
  263. if !conn.Up {
  264. return fmt.Errorf("%v and %v already disconnected", oneID, otherID)
  265. }
  266. client, err := conn.one.Client()
  267. if err != nil {
  268. return err
  269. }
  270. self.events.Send(ControlEvent(conn))
  271. return client.Call(nil, "admin_removePeer", string(conn.other.Addr()))
  272. }
  273. // DidConnect tracks the fact that the "one" node connected to the "other" node
  274. func (self *Network) DidConnect(one, other discover.NodeID) error {
  275. conn, err := self.GetOrCreateConn(one, other)
  276. if err != nil {
  277. return fmt.Errorf("connection between %v and %v does not exist", one, other)
  278. }
  279. if conn.Up {
  280. return fmt.Errorf("%v and %v already connected", one, other)
  281. }
  282. conn.Up = true
  283. self.events.Send(NewEvent(conn))
  284. return nil
  285. }
  286. // DidDisconnect tracks the fact that the "one" node disconnected from the
  287. // "other" node
  288. func (self *Network) DidDisconnect(one, other discover.NodeID) error {
  289. conn := self.GetConn(one, other)
  290. if conn == nil {
  291. return fmt.Errorf("connection between %v and %v does not exist", one, other)
  292. }
  293. if !conn.Up {
  294. return fmt.Errorf("%v and %v already disconnected", one, other)
  295. }
  296. conn.Up = false
  297. conn.initiated = time.Now().Add(-dialBanTimeout)
  298. self.events.Send(NewEvent(conn))
  299. return nil
  300. }
  301. // DidSend tracks the fact that "sender" sent a message to "receiver"
  302. func (self *Network) DidSend(sender, receiver discover.NodeID, proto string, code uint64) error {
  303. msg := &Msg{
  304. One: sender,
  305. Other: receiver,
  306. Protocol: proto,
  307. Code: code,
  308. Received: false,
  309. }
  310. self.events.Send(NewEvent(msg))
  311. return nil
  312. }
  313. // DidReceive tracks the fact that "receiver" received a message from "sender"
  314. func (self *Network) DidReceive(sender, receiver discover.NodeID, proto string, code uint64) error {
  315. msg := &Msg{
  316. One: sender,
  317. Other: receiver,
  318. Protocol: proto,
  319. Code: code,
  320. Received: true,
  321. }
  322. self.events.Send(NewEvent(msg))
  323. return nil
  324. }
  325. // GetNode gets the node with the given ID, returning nil if the node does not
  326. // exist
  327. func (self *Network) GetNode(id discover.NodeID) *Node {
  328. self.lock.Lock()
  329. defer self.lock.Unlock()
  330. return self.getNode(id)
  331. }
  332. // GetNode gets the node with the given name, returning nil if the node does
  333. // not exist
  334. func (self *Network) GetNodeByName(name string) *Node {
  335. self.lock.Lock()
  336. defer self.lock.Unlock()
  337. return self.getNodeByName(name)
  338. }
  339. func (self *Network) getNode(id discover.NodeID) *Node {
  340. i, found := self.nodeMap[id]
  341. if !found {
  342. return nil
  343. }
  344. return self.Nodes[i]
  345. }
  346. func (self *Network) getNodeByName(name string) *Node {
  347. for _, node := range self.Nodes {
  348. if node.Config.Name == name {
  349. return node
  350. }
  351. }
  352. return nil
  353. }
  354. // GetNodes returns the existing nodes
  355. func (self *Network) GetNodes() (nodes []*Node) {
  356. self.lock.Lock()
  357. defer self.lock.Unlock()
  358. for _, node := range self.Nodes {
  359. nodes = append(nodes, node)
  360. }
  361. return nodes
  362. }
  363. // GetConn returns the connection which exists between "one" and "other"
  364. // regardless of which node initiated the connection
  365. func (self *Network) GetConn(oneID, otherID discover.NodeID) *Conn {
  366. self.lock.Lock()
  367. defer self.lock.Unlock()
  368. return self.getConn(oneID, otherID)
  369. }
  370. // GetOrCreateConn is like GetConn but creates the connection if it doesn't
  371. // already exist
  372. func (self *Network) GetOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) {
  373. self.lock.Lock()
  374. defer self.lock.Unlock()
  375. return self.getOrCreateConn(oneID, otherID)
  376. }
  377. func (self *Network) getOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) {
  378. if conn := self.getConn(oneID, otherID); conn != nil {
  379. return conn, nil
  380. }
  381. one := self.getNode(oneID)
  382. if one == nil {
  383. return nil, fmt.Errorf("node %v does not exist", oneID)
  384. }
  385. other := self.getNode(otherID)
  386. if other == nil {
  387. return nil, fmt.Errorf("node %v does not exist", otherID)
  388. }
  389. conn := &Conn{
  390. One: oneID,
  391. Other: otherID,
  392. one: one,
  393. other: other,
  394. }
  395. label := ConnLabel(oneID, otherID)
  396. self.connMap[label] = len(self.Conns)
  397. self.Conns = append(self.Conns, conn)
  398. return conn, nil
  399. }
  400. func (self *Network) getConn(oneID, otherID discover.NodeID) *Conn {
  401. label := ConnLabel(oneID, otherID)
  402. i, found := self.connMap[label]
  403. if !found {
  404. return nil
  405. }
  406. return self.Conns[i]
  407. }
  408. // InitConn(one, other) retrieves the connectiton model for the connection between
  409. // peers one and other, or creates a new one if it does not exist
  410. // the order of nodes does not matter, i.e., Conn(i,j) == Conn(j, i)
  411. // it checks if the connection is already up, and if the nodes are running
  412. // NOTE:
  413. // it also checks whether there has been recent attempt to connect the peers
  414. // this is cheating as the simulation is used as an oracle and know about
  415. // remote peers attempt to connect to a node which will then not initiate the connection
  416. func (self *Network) InitConn(oneID, otherID discover.NodeID) (*Conn, error) {
  417. self.lock.Lock()
  418. defer self.lock.Unlock()
  419. if oneID == otherID {
  420. return nil, fmt.Errorf("refusing to connect to self %v", oneID)
  421. }
  422. conn, err := self.getOrCreateConn(oneID, otherID)
  423. if err != nil {
  424. return nil, err
  425. }
  426. if time.Now().Sub(conn.initiated) < dialBanTimeout {
  427. return nil, fmt.Errorf("connection between %v and %v recently attempted", oneID, otherID)
  428. }
  429. if conn.Up {
  430. return nil, fmt.Errorf("%v and %v already connected", oneID, otherID)
  431. }
  432. err = conn.nodesUp()
  433. if err != nil {
  434. return nil, fmt.Errorf("nodes not up: %v", err)
  435. }
  436. conn.initiated = time.Now()
  437. return conn, nil
  438. }
  439. // Shutdown stops all nodes in the network and closes the quit channel
  440. func (self *Network) Shutdown() {
  441. for _, node := range self.Nodes {
  442. log.Debug(fmt.Sprintf("stopping node %s", node.ID().TerminalString()))
  443. if err := node.Stop(); err != nil {
  444. log.Warn(fmt.Sprintf("error stopping node %s", node.ID().TerminalString()), "err", err)
  445. }
  446. }
  447. close(self.quitc)
  448. }
  449. // Node is a wrapper around adapters.Node which is used to track the status
  450. // of a node in the network
  451. type Node struct {
  452. adapters.Node `json:"-"`
  453. // Config if the config used to created the node
  454. Config *adapters.NodeConfig `json:"config"`
  455. // Up tracks whether or not the node is running
  456. Up bool `json:"up"`
  457. }
  458. // ID returns the ID of the node
  459. func (self *Node) ID() discover.NodeID {
  460. return self.Config.ID
  461. }
  462. // String returns a log-friendly string
  463. func (self *Node) String() string {
  464. return fmt.Sprintf("Node %v", self.ID().TerminalString())
  465. }
  466. // NodeInfo returns information about the node
  467. func (self *Node) NodeInfo() *p2p.NodeInfo {
  468. // avoid a panic if the node is not started yet
  469. if self.Node == nil {
  470. return nil
  471. }
  472. info := self.Node.NodeInfo()
  473. info.Name = self.Config.Name
  474. return info
  475. }
  476. // MarshalJSON implements the json.Marshaler interface so that the encoded
  477. // JSON includes the NodeInfo
  478. func (self *Node) MarshalJSON() ([]byte, error) {
  479. return json.Marshal(struct {
  480. Info *p2p.NodeInfo `json:"info,omitempty"`
  481. Config *adapters.NodeConfig `json:"config,omitempty"`
  482. Up bool `json:"up"`
  483. }{
  484. Info: self.NodeInfo(),
  485. Config: self.Config,
  486. Up: self.Up,
  487. })
  488. }
  489. // Conn represents a connection between two nodes in the network
  490. type Conn struct {
  491. // One is the node which initiated the connection
  492. One discover.NodeID `json:"one"`
  493. // Other is the node which the connection was made to
  494. Other discover.NodeID `json:"other"`
  495. // Up tracks whether or not the connection is active
  496. Up bool `json:"up"`
  497. // Registers when the connection was grabbed to dial
  498. initiated time.Time
  499. one *Node
  500. other *Node
  501. }
  502. // nodesUp returns whether both nodes are currently up
  503. func (self *Conn) nodesUp() error {
  504. if !self.one.Up {
  505. return fmt.Errorf("one %v is not up", self.One)
  506. }
  507. if !self.other.Up {
  508. return fmt.Errorf("other %v is not up", self.Other)
  509. }
  510. return nil
  511. }
  512. // String returns a log-friendly string
  513. func (self *Conn) String() string {
  514. return fmt.Sprintf("Conn %v->%v", self.One.TerminalString(), self.Other.TerminalString())
  515. }
  516. // Msg represents a p2p message sent between two nodes in the network
  517. type Msg struct {
  518. One discover.NodeID `json:"one"`
  519. Other discover.NodeID `json:"other"`
  520. Protocol string `json:"protocol"`
  521. Code uint64 `json:"code"`
  522. Received bool `json:"received"`
  523. }
  524. // String returns a log-friendly string
  525. func (self *Msg) String() string {
  526. return fmt.Sprintf("Msg(%d) %v->%v", self.Code, self.One.TerminalString(), self.Other.TerminalString())
  527. }
  528. // ConnLabel generates a deterministic string which represents a connection
  529. // between two nodes, used to compare if two connections are between the same
  530. // nodes
  531. func ConnLabel(source, target discover.NodeID) string {
  532. var first, second discover.NodeID
  533. if bytes.Compare(source.Bytes(), target.Bytes()) > 0 {
  534. first = target
  535. second = source
  536. } else {
  537. first = source
  538. second = target
  539. }
  540. return fmt.Sprintf("%v-%v", first, second)
  541. }
  542. // Snapshot represents the state of a network at a single point in time and can
  543. // be used to restore the state of a network
  544. type Snapshot struct {
  545. Nodes []NodeSnapshot `json:"nodes,omitempty"`
  546. Conns []Conn `json:"conns,omitempty"`
  547. }
  548. // NodeSnapshot represents the state of a node in the network
  549. type NodeSnapshot struct {
  550. Node Node `json:"node,omitempty"`
  551. // Snapshots is arbitrary data gathered from calling node.Snapshots()
  552. Snapshots map[string][]byte `json:"snapshots,omitempty"`
  553. }
  554. // Snapshot creates a network snapshot
  555. func (self *Network) Snapshot() (*Snapshot, error) {
  556. self.lock.Lock()
  557. defer self.lock.Unlock()
  558. snap := &Snapshot{
  559. Nodes: make([]NodeSnapshot, len(self.Nodes)),
  560. Conns: make([]Conn, len(self.Conns)),
  561. }
  562. for i, node := range self.Nodes {
  563. snap.Nodes[i] = NodeSnapshot{Node: *node}
  564. if !node.Up {
  565. continue
  566. }
  567. snapshots, err := node.Snapshots()
  568. if err != nil {
  569. return nil, err
  570. }
  571. snap.Nodes[i].Snapshots = snapshots
  572. }
  573. for i, conn := range self.Conns {
  574. snap.Conns[i] = *conn
  575. }
  576. return snap, nil
  577. }
  578. // Load loads a network snapshot
  579. func (self *Network) Load(snap *Snapshot) error {
  580. for _, n := range snap.Nodes {
  581. if _, err := self.NewNodeWithConfig(n.Node.Config); err != nil {
  582. return err
  583. }
  584. if !n.Node.Up {
  585. continue
  586. }
  587. if err := self.startWithSnapshots(n.Node.Config.ID, n.Snapshots); err != nil {
  588. return err
  589. }
  590. }
  591. for _, conn := range snap.Conns {
  592. if err := self.Connect(conn.One, conn.Other); err != nil {
  593. return err
  594. }
  595. }
  596. return nil
  597. }
  598. // Subscribe reads control events from a channel and executes them
  599. func (self *Network) Subscribe(events chan *Event) {
  600. for {
  601. select {
  602. case event, ok := <-events:
  603. if !ok {
  604. return
  605. }
  606. if event.Control {
  607. self.executeControlEvent(event)
  608. }
  609. case <-self.quitc:
  610. return
  611. }
  612. }
  613. }
  614. func (self *Network) executeControlEvent(event *Event) {
  615. log.Trace("execute control event", "type", event.Type, "event", event)
  616. switch event.Type {
  617. case EventTypeNode:
  618. if err := self.executeNodeEvent(event); err != nil {
  619. log.Error("error executing node event", "event", event, "err", err)
  620. }
  621. case EventTypeConn:
  622. if err := self.executeConnEvent(event); err != nil {
  623. log.Error("error executing conn event", "event", event, "err", err)
  624. }
  625. case EventTypeMsg:
  626. log.Warn("ignoring control msg event")
  627. }
  628. }
  629. func (self *Network) executeNodeEvent(e *Event) error {
  630. if !e.Node.Up {
  631. return self.Stop(e.Node.ID())
  632. }
  633. if _, err := self.NewNodeWithConfig(e.Node.Config); err != nil {
  634. return err
  635. }
  636. return self.Start(e.Node.ID())
  637. }
  638. func (self *Network) executeConnEvent(e *Event) error {
  639. if e.Conn.Up {
  640. return self.Connect(e.Conn.One, e.Conn.Other)
  641. } else {
  642. return self.Disconnect(e.Conn.One, e.Conn.Other)
  643. }
  644. }