cluster.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. package networkdb
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "fmt"
  8. "log"
  9. "math/big"
  10. rnd "math/rand"
  11. "net"
  12. "strings"
  13. "time"
  14. "github.com/hashicorp/memberlist"
  15. "github.com/sirupsen/logrus"
  16. )
  17. const (
  18. reapPeriod = 5 * time.Second
  19. rejoinClusterDuration = 10 * time.Second
  20. rejoinInterval = 60 * time.Second
  21. retryInterval = 1 * time.Second
  22. nodeReapInterval = 24 * time.Hour
  23. nodeReapPeriod = 2 * time.Hour
  24. )
  25. type logWriter struct{}
  26. func (l *logWriter) Write(p []byte) (int, error) {
  27. str := string(p)
  28. str = strings.TrimSuffix(str, "\n")
  29. switch {
  30. case strings.HasPrefix(str, "[WARN] "):
  31. str = strings.TrimPrefix(str, "[WARN] ")
  32. logrus.Warn(str)
  33. case strings.HasPrefix(str, "[DEBUG] "):
  34. str = strings.TrimPrefix(str, "[DEBUG] ")
  35. logrus.Debug(str)
  36. case strings.HasPrefix(str, "[INFO] "):
  37. str = strings.TrimPrefix(str, "[INFO] ")
  38. logrus.Info(str)
  39. case strings.HasPrefix(str, "[ERR] "):
  40. str = strings.TrimPrefix(str, "[ERR] ")
  41. logrus.Warn(str)
  42. }
  43. return len(p), nil
  44. }
  45. // SetKey adds a new key to the key ring
  46. func (nDB *NetworkDB) SetKey(key []byte) {
  47. logrus.Debugf("Adding key %s", hex.EncodeToString(key)[0:5])
  48. nDB.Lock()
  49. defer nDB.Unlock()
  50. for _, dbKey := range nDB.config.Keys {
  51. if bytes.Equal(key, dbKey) {
  52. return
  53. }
  54. }
  55. nDB.config.Keys = append(nDB.config.Keys, key)
  56. if nDB.keyring != nil {
  57. nDB.keyring.AddKey(key)
  58. }
  59. }
  60. // SetPrimaryKey sets the given key as the primary key. This should have
  61. // been added apriori through SetKey
  62. func (nDB *NetworkDB) SetPrimaryKey(key []byte) {
  63. logrus.Debugf("Primary Key %s", hex.EncodeToString(key)[0:5])
  64. nDB.RLock()
  65. defer nDB.RUnlock()
  66. for _, dbKey := range nDB.config.Keys {
  67. if bytes.Equal(key, dbKey) {
  68. if nDB.keyring != nil {
  69. nDB.keyring.UseKey(dbKey)
  70. }
  71. break
  72. }
  73. }
  74. }
  75. // RemoveKey removes a key from the key ring. The key being removed
  76. // can't be the primary key
  77. func (nDB *NetworkDB) RemoveKey(key []byte) {
  78. logrus.Debugf("Remove Key %s", hex.EncodeToString(key)[0:5])
  79. nDB.Lock()
  80. defer nDB.Unlock()
  81. for i, dbKey := range nDB.config.Keys {
  82. if bytes.Equal(key, dbKey) {
  83. nDB.config.Keys = append(nDB.config.Keys[:i], nDB.config.Keys[i+1:]...)
  84. if nDB.keyring != nil {
  85. nDB.keyring.RemoveKey(dbKey)
  86. }
  87. break
  88. }
  89. }
  90. }
  91. func (nDB *NetworkDB) clusterInit() error {
  92. nDB.lastStatsTimestamp = time.Now()
  93. nDB.lastHealthTimestamp = nDB.lastStatsTimestamp
  94. config := memberlist.DefaultLANConfig()
  95. config.Name = nDB.config.NodeID
  96. config.BindAddr = nDB.config.BindAddr
  97. config.AdvertiseAddr = nDB.config.AdvertiseAddr
  98. config.UDPBufferSize = nDB.config.PacketBufferSize
  99. if nDB.config.BindPort != 0 {
  100. config.BindPort = nDB.config.BindPort
  101. }
  102. config.ProtocolVersion = memberlist.ProtocolVersion2Compatible
  103. config.Delegate = &delegate{nDB: nDB}
  104. config.Events = &eventDelegate{nDB: nDB}
  105. // custom logger that does not add time or date, so they are not
  106. // duplicated by logrus
  107. config.Logger = log.New(&logWriter{}, "", 0)
  108. var err error
  109. if len(nDB.config.Keys) > 0 {
  110. for i, key := range nDB.config.Keys {
  111. logrus.Debugf("Encryption key %d: %s", i+1, hex.EncodeToString(key)[0:5])
  112. }
  113. nDB.keyring, err = memberlist.NewKeyring(nDB.config.Keys, nDB.config.Keys[0])
  114. if err != nil {
  115. return err
  116. }
  117. config.Keyring = nDB.keyring
  118. }
  119. nDB.networkBroadcasts = &memberlist.TransmitLimitedQueue{
  120. NumNodes: func() int {
  121. nDB.RLock()
  122. num := len(nDB.nodes)
  123. nDB.RUnlock()
  124. return num
  125. },
  126. RetransmitMult: config.RetransmitMult,
  127. }
  128. nDB.nodeBroadcasts = &memberlist.TransmitLimitedQueue{
  129. NumNodes: func() int {
  130. nDB.RLock()
  131. num := len(nDB.nodes)
  132. nDB.RUnlock()
  133. return num
  134. },
  135. RetransmitMult: config.RetransmitMult,
  136. }
  137. mlist, err := memberlist.Create(config)
  138. if err != nil {
  139. return fmt.Errorf("failed to create memberlist: %v", err)
  140. }
  141. nDB.ctx, nDB.cancelCtx = context.WithCancel(context.Background())
  142. nDB.memberlist = mlist
  143. for _, trigger := range []struct {
  144. interval time.Duration
  145. fn func()
  146. }{
  147. {reapPeriod, nDB.reapState},
  148. {config.GossipInterval, nDB.gossip},
  149. {config.PushPullInterval, nDB.bulkSyncTables},
  150. {retryInterval, nDB.reconnectNode},
  151. {nodeReapPeriod, nDB.reapDeadNode},
  152. {rejoinInterval, nDB.rejoinClusterBootStrap},
  153. } {
  154. t := time.NewTicker(trigger.interval)
  155. go nDB.triggerFunc(trigger.interval, t.C, trigger.fn)
  156. nDB.tickers = append(nDB.tickers, t)
  157. }
  158. return nil
  159. }
  160. func (nDB *NetworkDB) retryJoin(ctx context.Context, members []string) {
  161. t := time.NewTicker(retryInterval)
  162. defer t.Stop()
  163. for {
  164. select {
  165. case <-t.C:
  166. if _, err := nDB.memberlist.Join(members); err != nil {
  167. logrus.Errorf("Failed to join memberlist %s on retry: %v", members, err)
  168. continue
  169. }
  170. if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil {
  171. logrus.Errorf("failed to send node join on retry: %v", err)
  172. continue
  173. }
  174. return
  175. case <-ctx.Done():
  176. return
  177. }
  178. }
  179. }
  180. func (nDB *NetworkDB) clusterJoin(members []string) error {
  181. mlist := nDB.memberlist
  182. if _, err := mlist.Join(members); err != nil {
  183. // In case of failure, we no longer need to explicitly call retryJoin.
  184. // rejoinClusterBootStrap, which runs every minute, will retryJoin for 10sec
  185. return fmt.Errorf("could not join node to memberlist: %v", err)
  186. }
  187. if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil {
  188. return fmt.Errorf("failed to send node join: %v", err)
  189. }
  190. return nil
  191. }
  192. func (nDB *NetworkDB) clusterLeave() error {
  193. mlist := nDB.memberlist
  194. if err := nDB.sendNodeEvent(NodeEventTypeLeave); err != nil {
  195. logrus.Errorf("failed to send node leave: %v", err)
  196. }
  197. if err := mlist.Leave(time.Second); err != nil {
  198. return err
  199. }
  200. // cancel the context
  201. nDB.cancelCtx()
  202. for _, t := range nDB.tickers {
  203. t.Stop()
  204. }
  205. return mlist.Shutdown()
  206. }
  207. func (nDB *NetworkDB) triggerFunc(stagger time.Duration, C <-chan time.Time, f func()) {
  208. // Use a random stagger to avoid syncronizing
  209. randStagger := time.Duration(uint64(rnd.Int63()) % uint64(stagger))
  210. select {
  211. case <-time.After(randStagger):
  212. case <-nDB.ctx.Done():
  213. return
  214. }
  215. for {
  216. select {
  217. case <-C:
  218. f()
  219. case <-nDB.ctx.Done():
  220. return
  221. }
  222. }
  223. }
  224. func (nDB *NetworkDB) reapDeadNode() {
  225. nDB.Lock()
  226. defer nDB.Unlock()
  227. for _, nodeMap := range []map[string]*node{
  228. nDB.failedNodes,
  229. nDB.leftNodes,
  230. } {
  231. for id, n := range nodeMap {
  232. if n.reapTime > nodeReapPeriod {
  233. n.reapTime -= nodeReapPeriod
  234. continue
  235. }
  236. logrus.Debugf("Garbage collect node %v", n.Name)
  237. delete(nodeMap, id)
  238. }
  239. }
  240. }
  241. // rejoinClusterBootStrap is called periodically to check if all bootStrap nodes are active in the cluster,
  242. // if not, call the cluster join to merge 2 separate clusters that are formed when all managers
  243. // stopped/started at the same time
  244. func (nDB *NetworkDB) rejoinClusterBootStrap() {
  245. nDB.RLock()
  246. if len(nDB.bootStrapIP) == 0 {
  247. nDB.RUnlock()
  248. return
  249. }
  250. myself, _ := nDB.nodes[nDB.config.NodeID]
  251. bootStrapIPs := make([]string, 0, len(nDB.bootStrapIP))
  252. for _, bootIP := range nDB.bootStrapIP {
  253. // botostrap IPs are usually IP:port from the Join
  254. var bootstrapIP net.IP
  255. ipStr, _, err := net.SplitHostPort(bootIP)
  256. if err != nil {
  257. // try to parse it as an IP with port
  258. // Note this seems to be the case for swarm that do not specify any port
  259. ipStr = bootIP
  260. }
  261. bootstrapIP = net.ParseIP(ipStr)
  262. if bootstrapIP != nil {
  263. for _, node := range nDB.nodes {
  264. if node.Addr.Equal(bootstrapIP) && !node.Addr.Equal(myself.Addr) {
  265. // One of the bootstrap nodes (and not myself) is part of the cluster, return
  266. nDB.RUnlock()
  267. return
  268. }
  269. }
  270. bootStrapIPs = append(bootStrapIPs, bootIP)
  271. }
  272. }
  273. nDB.RUnlock()
  274. if len(bootStrapIPs) == 0 {
  275. // this will also avoid to call the Join with an empty list erasing the current bootstrap ip list
  276. logrus.Debug("rejoinClusterBootStrap did not find any valid IP")
  277. return
  278. }
  279. // None of the bootStrap nodes are in the cluster, call memberlist join
  280. logrus.Debugf("rejoinClusterBootStrap, calling cluster join with bootStrap %v", bootStrapIPs)
  281. ctx, cancel := context.WithTimeout(nDB.ctx, rejoinClusterDuration)
  282. defer cancel()
  283. nDB.retryJoin(ctx, bootStrapIPs)
  284. }
  285. func (nDB *NetworkDB) reconnectNode() {
  286. nDB.RLock()
  287. if len(nDB.failedNodes) == 0 {
  288. nDB.RUnlock()
  289. return
  290. }
  291. nodes := make([]*node, 0, len(nDB.failedNodes))
  292. for _, n := range nDB.failedNodes {
  293. nodes = append(nodes, n)
  294. }
  295. nDB.RUnlock()
  296. node := nodes[randomOffset(len(nodes))]
  297. addr := net.UDPAddr{IP: node.Addr, Port: int(node.Port)}
  298. if _, err := nDB.memberlist.Join([]string{addr.String()}); err != nil {
  299. return
  300. }
  301. if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil {
  302. return
  303. }
  304. logrus.Debugf("Initiating bulk sync with node %s after reconnect", node.Name)
  305. nDB.bulkSync([]string{node.Name}, true)
  306. }
  307. // For timing the entry deletion in the repaer APIs that doesn't use monotonic clock
  308. // source (time.Now, Sub etc.) should be avoided. Hence we use reapTime in every
  309. // entry which is set initially to reapInterval and decremented by reapPeriod every time
  310. // the reaper runs. NOTE nDB.reapTableEntries updates the reapTime with a readlock. This
  311. // is safe as long as no other concurrent path touches the reapTime field.
  312. func (nDB *NetworkDB) reapState() {
  313. // The reapTableEntries leverage the presence of the network so garbage collect entries first
  314. nDB.reapTableEntries()
  315. nDB.reapNetworks()
  316. }
  317. func (nDB *NetworkDB) reapNetworks() {
  318. nDB.Lock()
  319. for _, nn := range nDB.networks {
  320. for id, n := range nn {
  321. if n.leaving {
  322. if n.reapTime <= 0 {
  323. delete(nn, id)
  324. continue
  325. }
  326. n.reapTime -= reapPeriod
  327. }
  328. }
  329. }
  330. nDB.Unlock()
  331. }
  332. func (nDB *NetworkDB) reapTableEntries() {
  333. var nodeNetworks []string
  334. // This is best effort, if the list of network changes will be picked up in the next cycle
  335. nDB.RLock()
  336. for nid := range nDB.networks[nDB.config.NodeID] {
  337. nodeNetworks = append(nodeNetworks, nid)
  338. }
  339. nDB.RUnlock()
  340. cycleStart := time.Now()
  341. // In order to avoid blocking the database for a long time, apply the garbage collection logic by network
  342. // The lock is taken at the beginning of the cycle and the deletion is inline
  343. for _, nid := range nodeNetworks {
  344. nDB.Lock()
  345. nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid), func(path string, v interface{}) bool {
  346. // timeCompensation compensate in case the lock took some time to be released
  347. timeCompensation := time.Since(cycleStart)
  348. entry, ok := v.(*entry)
  349. if !ok || !entry.deleting {
  350. return false
  351. }
  352. // In this check we are adding an extra 1 second to guarantee that when the number is truncated to int32 to fit the packet
  353. // for the tableEvent the number is always strictly > 1 and never 0
  354. if entry.reapTime > reapPeriod+timeCompensation+time.Second {
  355. entry.reapTime -= reapPeriod + timeCompensation
  356. return false
  357. }
  358. params := strings.Split(path[1:], "/")
  359. nid := params[0]
  360. tname := params[1]
  361. key := params[2]
  362. okTable, okNetwork := nDB.deleteEntry(nid, tname, key)
  363. if !okTable {
  364. logrus.Errorf("Table tree delete failed, entry with key:%s does not exists in the table:%s network:%s", key, tname, nid)
  365. }
  366. if !okNetwork {
  367. logrus.Errorf("Network tree delete failed, entry with key:%s does not exists in the network:%s table:%s", key, nid, tname)
  368. }
  369. return false
  370. })
  371. nDB.Unlock()
  372. }
  373. }
  374. func (nDB *NetworkDB) gossip() {
  375. networkNodes := make(map[string][]string)
  376. nDB.RLock()
  377. thisNodeNetworks := nDB.networks[nDB.config.NodeID]
  378. for nid := range thisNodeNetworks {
  379. networkNodes[nid] = nDB.networkNodes[nid]
  380. }
  381. printStats := time.Since(nDB.lastStatsTimestamp) >= nDB.config.StatsPrintPeriod
  382. printHealth := time.Since(nDB.lastHealthTimestamp) >= nDB.config.HealthPrintPeriod
  383. nDB.RUnlock()
  384. if printHealth {
  385. healthScore := nDB.memberlist.GetHealthScore()
  386. if healthScore != 0 {
  387. logrus.Warnf("NetworkDB stats %v(%v) - healthscore:%d (connectivity issues)", nDB.config.Hostname, nDB.config.NodeID, healthScore)
  388. }
  389. nDB.lastHealthTimestamp = time.Now()
  390. }
  391. for nid, nodes := range networkNodes {
  392. mNodes := nDB.mRandomNodes(3, nodes)
  393. bytesAvail := nDB.config.PacketBufferSize - compoundHeaderOverhead
  394. nDB.RLock()
  395. network, ok := thisNodeNetworks[nid]
  396. nDB.RUnlock()
  397. if !ok || network == nil {
  398. // It is normal for the network to be removed
  399. // between the time we collect the network
  400. // attachments of this node and processing
  401. // them here.
  402. continue
  403. }
  404. broadcastQ := network.tableBroadcasts
  405. if broadcastQ == nil {
  406. logrus.Errorf("Invalid broadcastQ encountered while gossiping for network %s", nid)
  407. continue
  408. }
  409. msgs := broadcastQ.GetBroadcasts(compoundOverhead, bytesAvail)
  410. // Collect stats and print the queue info, note this code is here also to have a view of the queues empty
  411. network.qMessagesSent += len(msgs)
  412. if printStats {
  413. logrus.Infof("NetworkDB stats %v(%v) - netID:%s leaving:%t netPeers:%d entries:%d Queue qLen:%d netMsg/s:%d",
  414. nDB.config.Hostname, nDB.config.NodeID,
  415. nid, network.leaving, broadcastQ.NumNodes(), network.entriesNumber, broadcastQ.NumQueued(),
  416. network.qMessagesSent/int((nDB.config.StatsPrintPeriod/time.Second)))
  417. network.qMessagesSent = 0
  418. }
  419. if len(msgs) == 0 {
  420. continue
  421. }
  422. // Create a compound message
  423. compound := makeCompoundMessage(msgs)
  424. for _, node := range mNodes {
  425. nDB.RLock()
  426. mnode := nDB.nodes[node]
  427. nDB.RUnlock()
  428. if mnode == nil {
  429. break
  430. }
  431. // Send the compound message
  432. if err := nDB.memberlist.SendBestEffort(&mnode.Node, compound); err != nil {
  433. logrus.Errorf("Failed to send gossip to %s: %s", mnode.Addr, err)
  434. }
  435. }
  436. }
  437. // Reset the stats
  438. if printStats {
  439. nDB.lastStatsTimestamp = time.Now()
  440. }
  441. }
  442. func (nDB *NetworkDB) bulkSyncTables() {
  443. var networks []string
  444. nDB.RLock()
  445. for nid, network := range nDB.networks[nDB.config.NodeID] {
  446. if network.leaving {
  447. continue
  448. }
  449. networks = append(networks, nid)
  450. }
  451. nDB.RUnlock()
  452. for {
  453. if len(networks) == 0 {
  454. break
  455. }
  456. nid := networks[0]
  457. networks = networks[1:]
  458. nDB.RLock()
  459. nodes := nDB.networkNodes[nid]
  460. nDB.RUnlock()
  461. // No peer nodes on this network. Move on.
  462. if len(nodes) == 0 {
  463. continue
  464. }
  465. completed, err := nDB.bulkSync(nodes, false)
  466. if err != nil {
  467. logrus.Errorf("periodic bulk sync failure for network %s: %v", nid, err)
  468. continue
  469. }
  470. // Remove all the networks for which we have
  471. // successfully completed bulk sync in this iteration.
  472. updatedNetworks := make([]string, 0, len(networks))
  473. for _, nid := range networks {
  474. var found bool
  475. for _, completedNid := range completed {
  476. if nid == completedNid {
  477. found = true
  478. break
  479. }
  480. }
  481. if !found {
  482. updatedNetworks = append(updatedNetworks, nid)
  483. }
  484. }
  485. networks = updatedNetworks
  486. }
  487. }
  488. func (nDB *NetworkDB) bulkSync(nodes []string, all bool) ([]string, error) {
  489. if !all {
  490. // Get 2 random nodes. 2nd node will be tried if the bulk sync to
  491. // 1st node fails.
  492. nodes = nDB.mRandomNodes(2, nodes)
  493. }
  494. if len(nodes) == 0 {
  495. return nil, nil
  496. }
  497. var err error
  498. var networks []string
  499. for _, node := range nodes {
  500. if node == nDB.config.NodeID {
  501. continue
  502. }
  503. logrus.Debugf("%v(%v): Initiating bulk sync with node %v", nDB.config.Hostname, nDB.config.NodeID, node)
  504. networks = nDB.findCommonNetworks(node)
  505. err = nDB.bulkSyncNode(networks, node, true)
  506. // if its periodic bulksync stop after the first successful sync
  507. if !all && err == nil {
  508. break
  509. }
  510. if err != nil {
  511. err = fmt.Errorf("bulk sync to node %s failed: %v", node, err)
  512. logrus.Warn(err.Error())
  513. }
  514. }
  515. if err != nil {
  516. return nil, err
  517. }
  518. return networks, nil
  519. }
  520. // Bulk sync all the table entries belonging to a set of networks to a
  521. // single peer node. It can be unsolicited or can be in response to an
  522. // unsolicited bulk sync
  523. func (nDB *NetworkDB) bulkSyncNode(networks []string, node string, unsolicited bool) error {
  524. var msgs [][]byte
  525. var unsolMsg string
  526. if unsolicited {
  527. unsolMsg = "unsolicited"
  528. }
  529. logrus.Debugf("%v(%v): Initiating %s bulk sync for networks %v with node %s",
  530. nDB.config.Hostname, nDB.config.NodeID, unsolMsg, networks, node)
  531. nDB.RLock()
  532. mnode := nDB.nodes[node]
  533. if mnode == nil {
  534. nDB.RUnlock()
  535. return nil
  536. }
  537. for _, nid := range networks {
  538. nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid), func(path string, v interface{}) bool {
  539. entry, ok := v.(*entry)
  540. if !ok {
  541. return false
  542. }
  543. eType := TableEventTypeCreate
  544. if entry.deleting {
  545. eType = TableEventTypeDelete
  546. }
  547. params := strings.Split(path[1:], "/")
  548. tEvent := TableEvent{
  549. Type: eType,
  550. LTime: entry.ltime,
  551. NodeName: entry.node,
  552. NetworkID: nid,
  553. TableName: params[1],
  554. Key: params[2],
  555. Value: entry.value,
  556. // The duration in second is a float that below would be truncated
  557. ResidualReapTime: int32(entry.reapTime.Seconds()),
  558. }
  559. msg, err := encodeMessage(MessageTypeTableEvent, &tEvent)
  560. if err != nil {
  561. logrus.Errorf("Encode failure during bulk sync: %#v", tEvent)
  562. return false
  563. }
  564. msgs = append(msgs, msg)
  565. return false
  566. })
  567. }
  568. nDB.RUnlock()
  569. // Create a compound message
  570. compound := makeCompoundMessage(msgs)
  571. bsm := BulkSyncMessage{
  572. LTime: nDB.tableClock.Time(),
  573. Unsolicited: unsolicited,
  574. NodeName: nDB.config.NodeID,
  575. Networks: networks,
  576. Payload: compound,
  577. }
  578. buf, err := encodeMessage(MessageTypeBulkSync, &bsm)
  579. if err != nil {
  580. return fmt.Errorf("failed to encode bulk sync message: %v", err)
  581. }
  582. nDB.Lock()
  583. ch := make(chan struct{})
  584. nDB.bulkSyncAckTbl[node] = ch
  585. nDB.Unlock()
  586. err = nDB.memberlist.SendReliable(&mnode.Node, buf)
  587. if err != nil {
  588. nDB.Lock()
  589. delete(nDB.bulkSyncAckTbl, node)
  590. nDB.Unlock()
  591. return fmt.Errorf("failed to send a TCP message during bulk sync: %v", err)
  592. }
  593. // Wait on a response only if it is unsolicited.
  594. if unsolicited {
  595. startTime := time.Now()
  596. t := time.NewTimer(30 * time.Second)
  597. select {
  598. case <-t.C:
  599. logrus.Errorf("Bulk sync to node %s timed out", node)
  600. case <-ch:
  601. logrus.Debugf("%v(%v): Bulk sync to node %s took %s", nDB.config.Hostname, nDB.config.NodeID, node, time.Since(startTime))
  602. }
  603. t.Stop()
  604. }
  605. return nil
  606. }
  607. // Returns a random offset between 0 and n
  608. func randomOffset(n int) int {
  609. if n == 0 {
  610. return 0
  611. }
  612. val, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
  613. if err != nil {
  614. logrus.Errorf("Failed to get a random offset: %v", err)
  615. return 0
  616. }
  617. return int(val.Int64())
  618. }
  619. // mRandomNodes is used to select up to m random nodes. It is possible
  620. // that less than m nodes are returned.
  621. func (nDB *NetworkDB) mRandomNodes(m int, nodes []string) []string {
  622. n := len(nodes)
  623. mNodes := make([]string, 0, m)
  624. OUTER:
  625. // Probe up to 3*n times, with large n this is not necessary
  626. // since k << n, but with small n we want search to be
  627. // exhaustive
  628. for i := 0; i < 3*n && len(mNodes) < m; i++ {
  629. // Get random node
  630. idx := randomOffset(n)
  631. node := nodes[idx]
  632. if node == nDB.config.NodeID {
  633. continue
  634. }
  635. // Check if we have this node already
  636. for j := 0; j < len(mNodes); j++ {
  637. if node == mNodes[j] {
  638. continue OUTER
  639. }
  640. }
  641. // Append the node
  642. mNodes = append(mNodes, node)
  643. }
  644. return mNodes
  645. }