peer_server.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math/rand"
  6. "net/http"
  7. "net/url"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/coreos/etcd/third_party/github.com/goraft/raft"
  13. "github.com/coreos/etcd/third_party/github.com/gorilla/mux"
  14. "github.com/coreos/etcd/discovery"
  15. etcdErr "github.com/coreos/etcd/error"
  16. "github.com/coreos/etcd/log"
  17. "github.com/coreos/etcd/metrics"
  18. "github.com/coreos/etcd/pkg/btrfs"
  19. "github.com/coreos/etcd/store"
  20. )
  21. const (
  22. // MaxHeartbeatTimeoutBackoff is the maximum number of seconds before we warn
  23. // the user again about a peer not accepting heartbeats.
  24. MaxHeartbeatTimeoutBackoff = 15 * time.Second
  25. // ThresholdMonitorTimeout is the time between log notifications that the
  26. // Raft heartbeat is too close to the election timeout.
  27. ThresholdMonitorTimeout = 5 * time.Second
  28. // ActiveMonitorTimeout is the time between checks on the active size of
  29. // the cluster. If the active size is bigger than the actual size then
  30. // etcd attempts to demote to bring it to the correct number.
  31. ActiveMonitorTimeout = 1 * time.Second
  32. // PeerActivityMonitorTimeout is the time between checks for dead nodes in
  33. // the cluster.
  34. PeerActivityMonitorTimeout = 1 * time.Second
  35. // The location of cluster config in key space.
  36. ClusterConfigKey = "/_etcd/config"
  37. )
  38. type PeerServerConfig struct {
  39. Name string
  40. Scheme string
  41. URL string
  42. SnapshotCount int
  43. RetryTimes int
  44. RetryInterval float64
  45. }
  46. type PeerServer struct {
  47. Config PeerServerConfig
  48. client *Client
  49. raftServer raft.Server
  50. server *Server
  51. followersStats *raftFollowersStats
  52. serverStats *raftServerStats
  53. registry *Registry
  54. store store.Store
  55. snapConf *snapshotConf
  56. joinIndex uint64
  57. isNewCluster bool
  58. removedInLog bool
  59. removeNotify chan bool
  60. started bool
  61. closeChan chan bool
  62. routineGroup sync.WaitGroup
  63. timeoutThresholdChan chan interface{}
  64. logBackoffs map[string]*logBackoff
  65. metrics *metrics.Bucket
  66. sync.Mutex
  67. }
  68. type logBackoff struct {
  69. next time.Time
  70. backoff time.Duration
  71. count int
  72. }
  73. // TODO: find a good policy to do snapshot
  74. type snapshotConf struct {
  75. // Etcd will check if snapshot is need every checkingInterval
  76. checkingInterval time.Duration
  77. // The index when the last snapshot happened
  78. lastIndex uint64
  79. // If the incremental number of index since the last snapshot
  80. // exceeds the snapshot Threshold, etcd will do a snapshot
  81. snapshotThr uint64
  82. }
  83. func NewPeerServer(psConfig PeerServerConfig, client *Client, registry *Registry, store store.Store, mb *metrics.Bucket, followersStats *raftFollowersStats, serverStats *raftServerStats) *PeerServer {
  84. s := &PeerServer{
  85. Config: psConfig,
  86. client: client,
  87. registry: registry,
  88. store: store,
  89. followersStats: followersStats,
  90. serverStats: serverStats,
  91. timeoutThresholdChan: make(chan interface{}, 1),
  92. logBackoffs: make(map[string]*logBackoff),
  93. metrics: mb,
  94. }
  95. return s
  96. }
  97. func (s *PeerServer) SetRaftServer(raftServer raft.Server, snapshot bool) {
  98. s.snapConf = &snapshotConf{
  99. checkingInterval: time.Second * 3,
  100. // this is not accurate, we will update raft to provide an api
  101. lastIndex: raftServer.CommitIndex(),
  102. snapshotThr: uint64(s.Config.SnapshotCount),
  103. }
  104. raftServer.AddEventListener(raft.StateChangeEventType, s.raftEventLogger)
  105. raftServer.AddEventListener(raft.LeaderChangeEventType, s.raftEventLogger)
  106. raftServer.AddEventListener(raft.TermChangeEventType, s.raftEventLogger)
  107. raftServer.AddEventListener(raft.AddPeerEventType, s.raftEventLogger)
  108. raftServer.AddEventListener(raft.RemovePeerEventType, s.raftEventLogger)
  109. raftServer.AddEventListener(raft.HeartbeatIntervalEventType, s.raftEventLogger)
  110. raftServer.AddEventListener(raft.ElectionTimeoutThresholdEventType, s.raftEventLogger)
  111. raftServer.AddEventListener(raft.HeartbeatEventType, s.recordMetricEvent)
  112. raftServer.AddEventListener(raft.RemovedEventType, s.removedEvent)
  113. s.raftServer = raftServer
  114. s.removedInLog = false
  115. // LoadSnapshot
  116. if snapshot {
  117. err := s.raftServer.LoadSnapshot()
  118. if err == nil {
  119. log.Debugf("%s finished load snapshot", s.Config.Name)
  120. } else {
  121. log.Debug(err)
  122. }
  123. }
  124. s.raftServer.Init()
  125. // Set NOCOW for data directory in btrfs
  126. if btrfs.IsBtrfs(s.raftServer.LogPath()) {
  127. if err := btrfs.SetNOCOWFile(s.raftServer.LogPath()); err != nil {
  128. log.Warnf("Failed setting NOCOW: %v", err)
  129. }
  130. }
  131. }
  132. func (s *PeerServer) SetRegistry(registry *Registry) {
  133. s.registry = registry
  134. }
  135. func (s *PeerServer) SetStore(store store.Store) {
  136. s.store = store
  137. }
  138. // Try all possible ways to find clusters to join
  139. // Include log data in -data-dir, -discovery and -peers
  140. //
  141. // Peer discovery follows this order:
  142. // 1. previous peers in -data-dir
  143. // 2. -discovery
  144. // 3. -peers
  145. func (s *PeerServer) FindCluster(discoverURL string, peers []string) (toStart bool, possiblePeers []string, err error) {
  146. name := s.Config.Name
  147. isNewNode := s.raftServer.IsLogEmpty()
  148. // Try its best to find possible peers, and connect with them.
  149. if !isNewNode {
  150. // It is not allowed to join the cluster with existing peer address
  151. // This prevents old node joining with different name by mistake.
  152. if !s.checkPeerAddressNonconflict() {
  153. err = fmt.Errorf("%v is not allowed to join the cluster with existing URL %v", s.Config.Name, s.Config.URL)
  154. return
  155. }
  156. // Take old nodes into account.
  157. possiblePeers = s.getKnownPeers()
  158. // Discover registered peers.
  159. // TODO(yichengq): It may mess up discoverURL if this is
  160. // set wrong by mistake. This may need to refactor discovery
  161. // module. Fix it later.
  162. if discoverURL != "" {
  163. discoverPeers, _ := s.handleDiscovery(discoverURL)
  164. possiblePeers = append(possiblePeers, discoverPeers...)
  165. }
  166. possiblePeers = append(possiblePeers, peers...)
  167. possiblePeers = s.removeSelfFromList(possiblePeers)
  168. if s.removedInLog {
  169. return
  170. }
  171. // If there is possible peer list, use it to find cluster.
  172. if len(possiblePeers) > 0 {
  173. // TODO(yichengq): joinCluster may fail if there's no leader for
  174. // current cluster. It should wait if the cluster is under
  175. // leader election, or the node with changed IP cannot join
  176. // the cluster then.
  177. if rejected, ierr := s.startAsFollower(possiblePeers, 1); rejected {
  178. log.Debugf("%s should work as standby for the cluster %v: %v", name, possiblePeers, ierr)
  179. return
  180. } else if ierr != nil {
  181. log.Warnf("%s cannot connect to previous cluster %v: %v", name, possiblePeers, ierr)
  182. } else {
  183. log.Debugf("%s joins to the previous cluster %v", name, possiblePeers)
  184. toStart = true
  185. return
  186. }
  187. }
  188. // TODO(yichengq): Think about the action that should be done
  189. // if it cannot connect any of the previous known node.
  190. log.Debugf("%s is restarting the cluster %v", name, possiblePeers)
  191. s.SetJoinIndex(s.raftServer.CommitIndex())
  192. toStart = true
  193. return
  194. }
  195. // Attempt cluster discovery
  196. if discoverURL != "" {
  197. discoverPeers, discoverErr := s.handleDiscovery(discoverURL)
  198. // It is not registered in discover url
  199. if discoverErr != nil {
  200. log.Warnf("%s failed to connect discovery service[%v]: %v", name, discoverURL, discoverErr)
  201. if len(peers) == 0 {
  202. err = fmt.Errorf("%s, the new instance, must register itself to discovery service as required", name)
  203. return
  204. }
  205. log.Debugf("%s is joining peers %v from -peers flag", name, peers)
  206. } else {
  207. log.Debugf("%s is joining a cluster %v via discover service", name, discoverPeers)
  208. peers = discoverPeers
  209. }
  210. }
  211. possiblePeers = peers
  212. if len(possiblePeers) > 0 {
  213. if rejected, ierr := s.startAsFollower(possiblePeers, s.Config.RetryTimes); rejected {
  214. log.Debugf("%s should work as standby for the cluster %v: %v", name, possiblePeers, ierr)
  215. } else if ierr != nil {
  216. log.Warnf("%s cannot connect to existing peers %v: %v", name, possiblePeers, ierr)
  217. err = ierr
  218. } else {
  219. toStart = true
  220. }
  221. return
  222. }
  223. // start as a leader in a new cluster
  224. s.isNewCluster = true
  225. log.Infof("%s is starting a new cluster", s.Config.Name)
  226. toStart = true
  227. return
  228. }
  229. // Start starts the raft server.
  230. // The function assumes that join has been accepted successfully.
  231. func (s *PeerServer) Start(snapshot bool, clusterConfig *ClusterConfig) error {
  232. s.Lock()
  233. defer s.Unlock()
  234. if s.started {
  235. return nil
  236. }
  237. s.started = true
  238. s.removeNotify = make(chan bool)
  239. s.closeChan = make(chan bool)
  240. s.raftServer.Start()
  241. if s.isNewCluster {
  242. s.InitNewCluster(clusterConfig)
  243. s.isNewCluster = false
  244. }
  245. s.startRoutine(s.monitorSync)
  246. s.startRoutine(s.monitorTimeoutThreshold)
  247. s.startRoutine(s.monitorActiveSize)
  248. s.startRoutine(s.monitorPeerActivity)
  249. // open the snapshot
  250. if snapshot {
  251. s.startRoutine(s.monitorSnapshot)
  252. }
  253. return nil
  254. }
  255. // Stop stops the server gracefully.
  256. func (s *PeerServer) Stop() {
  257. s.Lock()
  258. defer s.Unlock()
  259. if !s.started {
  260. return
  261. }
  262. s.started = false
  263. close(s.closeChan)
  264. // TODO(yichengq): it should also call async stop for raft server,
  265. // but this functionality has not been implemented.
  266. s.raftServer.Stop()
  267. s.routineGroup.Wait()
  268. }
  269. // asyncRemove stops the server in peer mode.
  270. // It is called to stop the server internally when it has been removed
  271. // from the cluster.
  272. // The function triggers the stop action first to notice server that it
  273. // should not continue, and wait for its stop in separate goroutine because
  274. // the caller should also exit.
  275. func (s *PeerServer) asyncRemove() {
  276. s.Lock()
  277. if !s.started {
  278. s.Unlock()
  279. return
  280. }
  281. s.started = false
  282. close(s.closeChan)
  283. // TODO(yichengq): it should also call async stop for raft server,
  284. // but this functionality has not been implemented.
  285. go func() {
  286. s.raftServer.Stop()
  287. s.routineGroup.Wait()
  288. close(s.removeNotify)
  289. s.Unlock()
  290. }()
  291. }
  292. // RemoveNotify notifies the server is removed from peer mode due to
  293. // removal from the cluster.
  294. func (s *PeerServer) RemoveNotify() <-chan bool {
  295. return s.removeNotify
  296. }
  297. func (s *PeerServer) HTTPHandler() http.Handler {
  298. router := mux.NewRouter()
  299. // internal commands
  300. router.HandleFunc("/name", s.NameHttpHandler)
  301. router.HandleFunc("/version", s.VersionHttpHandler)
  302. router.HandleFunc("/version/{version:[0-9]+}/check", s.VersionCheckHttpHandler)
  303. router.HandleFunc("/upgrade", s.UpgradeHttpHandler)
  304. router.HandleFunc("/join", s.JoinHttpHandler)
  305. router.HandleFunc("/remove/{name:.+}", s.RemoveHttpHandler)
  306. router.HandleFunc("/vote", s.VoteHttpHandler)
  307. router.HandleFunc("/log", s.GetLogHttpHandler)
  308. router.HandleFunc("/log/append", s.AppendEntriesHttpHandler)
  309. router.HandleFunc("/snapshot", s.SnapshotHttpHandler)
  310. router.HandleFunc("/snapshotRecovery", s.SnapshotRecoveryHttpHandler)
  311. router.HandleFunc("/etcdURL", s.EtcdURLHttpHandler)
  312. router.HandleFunc("/v2/admin/config", s.getClusterConfigHttpHandler).Methods("GET")
  313. router.HandleFunc("/v2/admin/config", s.setClusterConfigHttpHandler).Methods("PUT")
  314. router.HandleFunc("/v2/admin/machines", s.getMachinesHttpHandler).Methods("GET")
  315. router.HandleFunc("/v2/admin/machines/{name}", s.getMachineHttpHandler).Methods("GET")
  316. router.HandleFunc("/v2/admin/machines/{name}", s.RemoveHttpHandler).Methods("DELETE")
  317. return router
  318. }
  319. func (s *PeerServer) SetJoinIndex(joinIndex uint64) {
  320. s.joinIndex = joinIndex
  321. }
  322. // ClusterConfig retrieves the current cluster configuration.
  323. func (s *PeerServer) ClusterConfig() *ClusterConfig {
  324. e, err := s.store.Get(ClusterConfigKey, false, false)
  325. // This is useful for backward compatibility because it doesn't
  326. // set cluster config in older version.
  327. if err != nil {
  328. log.Debugf("failed getting cluster config key: %v", err)
  329. return NewClusterConfig()
  330. }
  331. var c ClusterConfig
  332. if err = json.Unmarshal([]byte(*e.Node.Value), &c); err != nil {
  333. log.Debugf("failed unmarshaling cluster config: %v", err)
  334. return NewClusterConfig()
  335. }
  336. return &c
  337. }
  338. // SetClusterConfig updates the current cluster configuration.
  339. // Adjusting the active size will cause cluster to add or remove machines
  340. // to match the new size.
  341. func (s *PeerServer) SetClusterConfig(c *ClusterConfig) {
  342. // Set minimums.
  343. if c.ActiveSize < MinActiveSize {
  344. c.ActiveSize = MinActiveSize
  345. }
  346. if c.RemoveDelay < MinRemoveDelay {
  347. c.RemoveDelay = MinRemoveDelay
  348. }
  349. if c.SyncInterval < MinSyncInterval {
  350. c.SyncInterval = MinSyncInterval
  351. }
  352. log.Debugf("set cluster config as %v", c)
  353. b, _ := json.Marshal(c)
  354. s.store.Set(ClusterConfigKey, false, string(b), store.Permanent)
  355. }
  356. // Retrieves the underlying Raft server.
  357. func (s *PeerServer) RaftServer() raft.Server {
  358. return s.raftServer
  359. }
  360. // Associates the client server with the peer server.
  361. func (s *PeerServer) SetServer(server *Server) {
  362. s.server = server
  363. }
  364. func (s *PeerServer) InitNewCluster(clusterConfig *ClusterConfig) {
  365. // leader need to join self as a peer
  366. s.doCommand(&JoinCommand{
  367. MinVersion: store.MinVersion(),
  368. MaxVersion: store.MaxVersion(),
  369. Name: s.raftServer.Name(),
  370. RaftURL: s.Config.URL,
  371. EtcdURL: s.server.URL(),
  372. })
  373. log.Debugf("%s start as a leader", s.Config.Name)
  374. s.joinIndex = 1
  375. s.doCommand(&SetClusterConfigCommand{Config: clusterConfig})
  376. log.Debugf("%s sets cluster config as %v", s.Config.Name, clusterConfig)
  377. }
  378. func (s *PeerServer) doCommand(cmd raft.Command) {
  379. for {
  380. if _, err := s.raftServer.Do(cmd); err == nil {
  381. break
  382. }
  383. }
  384. log.Debugf("%s start as a leader", s.Config.Name)
  385. }
  386. func (s *PeerServer) startAsFollower(cluster []string, retryTimes int) (bool, error) {
  387. // start as a follower in a existing cluster
  388. for i := 0; ; i++ {
  389. if rejected, err := s.joinCluster(cluster); rejected {
  390. return true, err
  391. } else if err == nil {
  392. return false, nil
  393. }
  394. if i == retryTimes-1 {
  395. break
  396. }
  397. log.Infof("%v is unable to join the cluster using any of the peers %v at %dth time. Retrying in %.1f seconds", s.Config.Name, cluster, i, s.Config.RetryInterval)
  398. time.Sleep(time.Second * time.Duration(s.Config.RetryInterval))
  399. continue
  400. }
  401. return false, fmt.Errorf("fail joining the cluster via given peers after %x retries", retryTimes)
  402. }
  403. // Upgradable checks whether all peers in a cluster support an upgrade to the next store version.
  404. func (s *PeerServer) Upgradable() error {
  405. nextVersion := s.store.Version() + 1
  406. for _, peerURL := range s.registry.PeerURLs(s.raftServer.Leader(), s.Config.Name) {
  407. u, err := url.Parse(peerURL)
  408. if err != nil {
  409. return fmt.Errorf("PeerServer: Cannot parse URL: '%s' (%s)", peerURL, err)
  410. }
  411. url := (&url.URL{Host: u.Host, Scheme: s.Config.Scheme}).String()
  412. ok, err := s.client.CheckVersion(url, nextVersion)
  413. if err != nil {
  414. return err
  415. }
  416. if !ok {
  417. return fmt.Errorf("PeerServer: Version %d is not compatible with peer: %s", nextVersion, u.Host)
  418. }
  419. }
  420. return nil
  421. }
  422. // checkPeerAddressNonconflict checks whether the peer address has existed with different name.
  423. func (s *PeerServer) checkPeerAddressNonconflict() bool {
  424. // there exists the (name, peer address) pair
  425. if peerURL, ok := s.registry.PeerURL(s.Config.Name); ok {
  426. if peerURL == s.Config.URL {
  427. return true
  428. }
  429. }
  430. // check all existing peer addresses
  431. peerURLs := s.registry.PeerURLs(s.raftServer.Leader(), s.Config.Name)
  432. for _, peerURL := range peerURLs {
  433. if peerURL == s.Config.URL {
  434. return false
  435. }
  436. }
  437. return true
  438. }
  439. // Helper function to do discovery and return results in expected format
  440. func (s *PeerServer) handleDiscovery(discoverURL string) (peers []string, err error) {
  441. peers, err = discovery.Do(discoverURL, s.Config.Name, s.Config.URL, s.closeChan, s.startRoutine)
  442. // Warn about errors coming from discovery, this isn't fatal
  443. // since the user might have provided a peer list elsewhere,
  444. // or there is some log in data dir.
  445. if err != nil {
  446. log.Warnf("Discovery encountered an error: %v", err)
  447. return
  448. }
  449. for i := range peers {
  450. // Strip the scheme off of the peer if it has one
  451. // TODO(bp): clean this up!
  452. purl, err := url.Parse(peers[i])
  453. if err == nil {
  454. peers[i] = purl.Host
  455. }
  456. }
  457. log.Infof("Discovery fetched back peer list: %v", peers)
  458. return
  459. }
  460. // getKnownPeers gets the previous peers from log
  461. func (s *PeerServer) getKnownPeers() []string {
  462. peers := s.registry.PeerURLs(s.raftServer.Leader(), s.Config.Name)
  463. log.Infof("Peer URLs in log: %s / %s (%s)", s.raftServer.Leader(), s.Config.Name, strings.Join(peers, ","))
  464. for i := range peers {
  465. u, err := url.Parse(peers[i])
  466. if err != nil {
  467. log.Debugf("getKnownPeers cannot parse url %v", peers[i])
  468. }
  469. peers[i] = u.Host
  470. }
  471. return peers
  472. }
  473. // removeSelfFromList removes url of the peerServer from the peer list
  474. func (s *PeerServer) removeSelfFromList(peers []string) []string {
  475. // Remove its own peer address from the peer list to join
  476. u, err := url.Parse(s.Config.URL)
  477. if err != nil {
  478. log.Warnf("failed parsing self peer address %v", s.Config.URL)
  479. u = nil
  480. }
  481. newPeers := make([]string, 0)
  482. for _, v := range peers {
  483. if u == nil || v != u.Host {
  484. newPeers = append(newPeers, v)
  485. }
  486. }
  487. return newPeers
  488. }
  489. func (s *PeerServer) joinCluster(cluster []string) (bool, error) {
  490. for _, peer := range cluster {
  491. if len(peer) == 0 {
  492. continue
  493. }
  494. if rejected, err := s.joinByPeer(s.raftServer, peer, s.Config.Scheme); rejected {
  495. return true, fmt.Errorf("rejected by peer %s: %v", peer, err)
  496. } else if err == nil {
  497. log.Infof("%s joined the cluster via peer %s", s.Config.Name, peer)
  498. return false, nil
  499. } else {
  500. log.Infof("%s attempted to join via %s failed: %v", s.Config.Name, peer, err)
  501. }
  502. }
  503. return false, fmt.Errorf("unreachable cluster")
  504. }
  505. // Send join requests to peer.
  506. // The first return tells whether it is rejected by the cluster directly.
  507. func (s *PeerServer) joinByPeer(server raft.Server, peer string, scheme string) (bool, error) {
  508. u := (&url.URL{Host: peer, Scheme: scheme}).String()
  509. // Our version must match the leaders version
  510. version, err := s.client.GetVersion(u)
  511. if err != nil {
  512. return false, fmt.Errorf("fail checking join version: %v", err)
  513. }
  514. if version < store.MinVersion() || version > store.MaxVersion() {
  515. return true, fmt.Errorf("fail passing version compatibility(%d-%d) using %d", store.MinVersion(), store.MaxVersion(), version)
  516. }
  517. // Fetch current peer list
  518. machines, err := s.client.GetMachines(u)
  519. if err != nil {
  520. return false, fmt.Errorf("fail getting machine messages: %v", err)
  521. }
  522. exist := false
  523. for _, machine := range machines {
  524. if machine.Name == server.Name() {
  525. exist = true
  526. break
  527. }
  528. }
  529. // Fetch cluster config to see whether exists some place.
  530. clusterConfig, err := s.client.GetClusterConfig(u)
  531. if err != nil {
  532. return false, fmt.Errorf("fail getting cluster config: %v", err)
  533. }
  534. if !exist && clusterConfig.ActiveSize <= len(machines) {
  535. return true, fmt.Errorf("stop joining because the cluster is full with %d nodes", len(machines))
  536. }
  537. joinIndex, err := s.client.AddMachine(u,
  538. &JoinCommand{
  539. MinVersion: store.MinVersion(),
  540. MaxVersion: store.MaxVersion(),
  541. Name: server.Name(),
  542. RaftURL: s.Config.URL,
  543. EtcdURL: s.server.URL(),
  544. })
  545. if err != nil {
  546. return err.ErrorCode == etcdErr.EcodeNoMorePeer, fmt.Errorf("fail on join request: %v", err)
  547. }
  548. s.joinIndex = joinIndex
  549. return false, nil
  550. }
  551. func (s *PeerServer) Stats() []byte {
  552. s.serverStats.LeaderInfo.Uptime = time.Now().Sub(s.serverStats.LeaderInfo.StartTime).String()
  553. // TODO: register state listener to raft to change this field
  554. // rather than compare the state each time Stats() is called.
  555. if s.RaftServer().State() == raft.Leader {
  556. s.serverStats.LeaderInfo.Name = s.RaftServer().Name()
  557. }
  558. queue := s.serverStats.sendRateQueue
  559. s.serverStats.SendingPkgRate, s.serverStats.SendingBandwidthRate = queue.Rate()
  560. queue = s.serverStats.recvRateQueue
  561. s.serverStats.RecvingPkgRate, s.serverStats.RecvingBandwidthRate = queue.Rate()
  562. b, _ := json.Marshal(s.serverStats)
  563. return b
  564. }
  565. func (s *PeerServer) PeerStats() []byte {
  566. if s.raftServer.State() == raft.Leader {
  567. b, _ := json.Marshal(s.followersStats)
  568. return b
  569. }
  570. return nil
  571. }
  572. // removedEvent handles the case where a machine has been removed from the
  573. // cluster and is notified when it tries to become a candidate.
  574. func (s *PeerServer) removedEvent(event raft.Event) {
  575. // HACK(philips): we need to find a better notification for this.
  576. log.Infof("removed during cluster re-configuration")
  577. s.asyncRemove()
  578. }
  579. // raftEventLogger converts events from the Raft server into log messages.
  580. func (s *PeerServer) raftEventLogger(event raft.Event) {
  581. value := event.Value()
  582. prevValue := event.PrevValue()
  583. if value == nil {
  584. value = "<nil>"
  585. }
  586. if prevValue == nil {
  587. prevValue = "<nil>"
  588. }
  589. switch event.Type() {
  590. case raft.StateChangeEventType:
  591. log.Infof("%s: state changed from '%v' to '%v'.", s.Config.Name, prevValue, value)
  592. case raft.TermChangeEventType:
  593. log.Infof("%s: term #%v started.", s.Config.Name, value)
  594. case raft.LeaderChangeEventType:
  595. log.Infof("%s: leader changed from '%v' to '%v'.", s.Config.Name, prevValue, value)
  596. case raft.AddPeerEventType:
  597. log.Infof("%s: peer added: '%v'", s.Config.Name, value)
  598. case raft.RemovePeerEventType:
  599. log.Infof("%s: peer removed: '%v'", s.Config.Name, value)
  600. case raft.HeartbeatIntervalEventType:
  601. peer, ok := value.(*raft.Peer)
  602. if !ok {
  603. log.Warnf("%s: heatbeat timeout from unknown peer", s.Config.Name)
  604. return
  605. }
  606. s.logHeartbeatTimeout(peer)
  607. case raft.ElectionTimeoutThresholdEventType:
  608. select {
  609. case s.timeoutThresholdChan <- value:
  610. default:
  611. }
  612. }
  613. }
  614. // logHeartbeatTimeout logs about the edge triggered heartbeat timeout event
  615. // only if we haven't warned within a reasonable interval.
  616. func (s *PeerServer) logHeartbeatTimeout(peer *raft.Peer) {
  617. b, ok := s.logBackoffs[peer.Name]
  618. if !ok {
  619. b = &logBackoff{time.Time{}, time.Second, 1}
  620. s.logBackoffs[peer.Name] = b
  621. }
  622. if peer.LastActivity().After(b.next) {
  623. b.next = time.Time{}
  624. b.backoff = time.Second
  625. b.count = 1
  626. }
  627. if b.next.After(time.Now()) {
  628. b.count++
  629. return
  630. }
  631. b.backoff = 2 * b.backoff
  632. if b.backoff > MaxHeartbeatTimeoutBackoff {
  633. b.backoff = MaxHeartbeatTimeoutBackoff
  634. }
  635. b.next = time.Now().Add(b.backoff)
  636. log.Infof("%s: warning: heartbeat time out peer=%q missed=%d backoff=%q", s.Config.Name, peer.Name, b.count, b.backoff)
  637. }
  638. func (s *PeerServer) recordMetricEvent(event raft.Event) {
  639. name := fmt.Sprintf("raft.event.%s", event.Type())
  640. value := event.Value().(time.Duration)
  641. (*s.metrics).Timer(name).Update(value)
  642. }
  643. // logSnapshot logs about the snapshot that was taken.
  644. func (s *PeerServer) logSnapshot(err error, currentIndex, count uint64) {
  645. info := fmt.Sprintf("%s: snapshot of %d events at index %d", s.Config.Name, count, currentIndex)
  646. if err != nil {
  647. log.Infof("%s attempted and failed: %v", info, err)
  648. } else {
  649. log.Infof("%s completed", info)
  650. }
  651. }
  652. func (s *PeerServer) startRoutine(f func()) {
  653. s.routineGroup.Add(1)
  654. go func() {
  655. defer s.routineGroup.Done()
  656. f()
  657. }()
  658. }
  659. func (s *PeerServer) monitorSnapshot() {
  660. for {
  661. timer := time.NewTimer(s.snapConf.checkingInterval)
  662. select {
  663. case <-s.closeChan:
  664. timer.Stop()
  665. return
  666. case <-timer.C:
  667. }
  668. currentIndex := s.RaftServer().CommitIndex()
  669. count := currentIndex - s.snapConf.lastIndex
  670. if uint64(count) > s.snapConf.snapshotThr {
  671. err := s.raftServer.TakeSnapshot()
  672. s.logSnapshot(err, currentIndex, count)
  673. s.snapConf.lastIndex = currentIndex
  674. }
  675. }
  676. }
  677. func (s *PeerServer) monitorSync() {
  678. ticker := time.NewTicker(time.Millisecond * 500)
  679. defer ticker.Stop()
  680. for {
  681. select {
  682. case <-s.closeChan:
  683. return
  684. case now := <-ticker.C:
  685. if s.raftServer.State() == raft.Leader {
  686. s.raftServer.Do(s.store.CommandFactory().CreateSyncCommand(now))
  687. }
  688. }
  689. }
  690. }
  691. // monitorTimeoutThreshold groups timeout threshold events together and prints
  692. // them as a single log line.
  693. func (s *PeerServer) monitorTimeoutThreshold() {
  694. ticker := time.NewTicker(ThresholdMonitorTimeout)
  695. defer ticker.Stop()
  696. for {
  697. select {
  698. case <-s.closeChan:
  699. return
  700. case value := <-s.timeoutThresholdChan:
  701. log.Infof("%s: warning: heartbeat near election timeout: %v", s.Config.Name, value)
  702. }
  703. select {
  704. case <-s.closeChan:
  705. return
  706. case <-ticker.C:
  707. }
  708. }
  709. }
  710. // monitorActiveSize has the leader periodically check the status of cluster
  711. // nodes and swaps them out for standbys as needed.
  712. func (s *PeerServer) monitorActiveSize() {
  713. ticker := time.NewTicker(ActiveMonitorTimeout)
  714. defer ticker.Stop()
  715. for {
  716. select {
  717. case <-s.closeChan:
  718. return
  719. case <-ticker.C:
  720. }
  721. // Ignore while this peer is not a leader.
  722. if s.raftServer.State() != raft.Leader {
  723. continue
  724. }
  725. // Retrieve target active size and actual active size.
  726. activeSize := s.ClusterConfig().ActiveSize
  727. peers := s.registry.Names()
  728. peerCount := len(peers)
  729. if index := sort.SearchStrings(peers, s.Config.Name); index < len(peers) && peers[index] == s.Config.Name {
  730. peers = append(peers[:index], peers[index+1:]...)
  731. }
  732. // If we have more active nodes than we should then remove.
  733. if peerCount > activeSize {
  734. peer := peers[rand.Intn(len(peers))]
  735. log.Infof("%s: removing node: %v; peer number %d > expected size %d", s.Config.Name, peer, peerCount, activeSize)
  736. if _, err := s.raftServer.Do(&RemoveCommand{Name: peer}); err != nil {
  737. log.Infof("%s: warning: remove error: %v", s.Config.Name, err)
  738. }
  739. continue
  740. }
  741. }
  742. }
  743. // monitorPeerActivity has the leader periodically for dead nodes and demotes them.
  744. func (s *PeerServer) monitorPeerActivity() {
  745. ticker := time.NewTicker(PeerActivityMonitorTimeout)
  746. defer ticker.Stop()
  747. for {
  748. select {
  749. case <-s.closeChan:
  750. return
  751. case <-ticker.C:
  752. }
  753. // Ignore while this peer is not a leader.
  754. if s.raftServer.State() != raft.Leader {
  755. continue
  756. }
  757. // Check last activity for all peers.
  758. now := time.Now()
  759. removeDelay := time.Duration(int64(s.ClusterConfig().RemoveDelay * float64(time.Second)))
  760. peers := s.raftServer.Peers()
  761. for _, peer := range peers {
  762. // If the last response from the peer is longer than the remove delay
  763. // then automatically demote the peer.
  764. if !peer.LastActivity().IsZero() && now.Sub(peer.LastActivity()) > removeDelay {
  765. log.Infof("%s: removing node: %v; last activity %v ago", s.Config.Name, peer.Name, now.Sub(peer.LastActivity()))
  766. if _, err := s.raftServer.Do(&RemoveCommand{Name: peer.Name}); err != nil {
  767. log.Infof("%s: warning: autodemotion error: %v", s.Config.Name, err)
  768. }
  769. continue
  770. }
  771. }
  772. }
  773. }