cluster.go 20 KB

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