host_source.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. package gocql
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. type nodeState int32
  12. func (n nodeState) String() string {
  13. if n == NodeUp {
  14. return "UP"
  15. } else if n == NodeDown {
  16. return "DOWN"
  17. }
  18. return fmt.Sprintf("UNKNOWN_%d", n)
  19. }
  20. const (
  21. NodeUp nodeState = iota
  22. NodeDown
  23. )
  24. type cassVersion struct {
  25. Major, Minor, Patch int
  26. }
  27. func (c *cassVersion) Set(v string) error {
  28. if v == "" {
  29. return nil
  30. }
  31. return c.UnmarshalCQL(nil, []byte(v))
  32. }
  33. func (c *cassVersion) UnmarshalCQL(info TypeInfo, data []byte) error {
  34. return c.unmarshal(data)
  35. }
  36. func (c *cassVersion) unmarshal(data []byte) error {
  37. version := strings.TrimSuffix(string(data), "-SNAPSHOT")
  38. version = strings.TrimPrefix(version, "v")
  39. v := strings.Split(version, ".")
  40. if len(v) < 2 {
  41. return fmt.Errorf("invalid version string: %s", data)
  42. }
  43. var err error
  44. c.Major, err = strconv.Atoi(v[0])
  45. if err != nil {
  46. return fmt.Errorf("invalid major version %v: %v", v[0], err)
  47. }
  48. c.Minor, err = strconv.Atoi(v[1])
  49. if err != nil {
  50. return fmt.Errorf("invalid minor version %v: %v", v[1], err)
  51. }
  52. if len(v) > 2 {
  53. c.Patch, err = strconv.Atoi(v[2])
  54. if err != nil {
  55. return fmt.Errorf("invalid patch version %v: %v", v[2], err)
  56. }
  57. }
  58. return nil
  59. }
  60. func (c cassVersion) Before(major, minor, patch int) bool {
  61. if c.Major > major {
  62. return true
  63. } else if c.Minor > minor {
  64. return true
  65. } else if c.Patch > patch {
  66. return true
  67. }
  68. return false
  69. }
  70. func (c cassVersion) String() string {
  71. return fmt.Sprintf("v%d.%d.%d", c.Major, c.Minor, c.Patch)
  72. }
  73. func (c cassVersion) nodeUpDelay() time.Duration {
  74. if c.Major >= 2 && c.Minor >= 2 {
  75. // CASSANDRA-8236
  76. return 0
  77. }
  78. return 10 * time.Second
  79. }
  80. type HostInfo struct {
  81. // TODO(zariel): reduce locking maybe, not all values will change, but to ensure
  82. // that we are thread safe use a mutex to access all fields.
  83. mu sync.RWMutex
  84. peer net.IP
  85. broadcastAddress net.IP
  86. listenAddress net.IP
  87. rpcAddress net.IP
  88. preferredIP net.IP
  89. connectAddress net.IP
  90. port int
  91. dataCenter string
  92. rack string
  93. hostId string
  94. workload string
  95. graph bool
  96. dseVersion string
  97. partitioner string
  98. clusterName string
  99. version cassVersion
  100. state nodeState
  101. tokens []string
  102. }
  103. func (h *HostInfo) Equal(host *HostInfo) bool {
  104. h.mu.RLock()
  105. defer h.mu.RUnlock()
  106. //If both hosts pointers are same then lock is required only once because of below reasons:
  107. //Reason 1: There is no point taking lock twice on same mutex variable.
  108. //Reason 2: It may lead to deadlock e.g. if WLock is requested by other routine in between 1st & 2nd RLock
  109. //So WLock will be blocked on 1st RLock and 2nd RLock will be blocked on requested WLock.
  110. if h != host {
  111. host.mu.RLock()
  112. defer host.mu.RUnlock()
  113. }
  114. return h.ConnectAddress().Equal(host.ConnectAddress())
  115. }
  116. func (h *HostInfo) Peer() net.IP {
  117. h.mu.RLock()
  118. defer h.mu.RUnlock()
  119. return h.peer
  120. }
  121. func (h *HostInfo) setPeer(peer net.IP) *HostInfo {
  122. h.mu.Lock()
  123. defer h.mu.Unlock()
  124. h.peer = peer
  125. return h
  126. }
  127. func (h *HostInfo) invalidConnectAddr() bool {
  128. addr := h.ConnectAddress()
  129. return addr == nil || addr.IsUnspecified()
  130. }
  131. // Returns the address that should be used to connect to the host.
  132. // If you wish to override this, use an AddressTranslator or
  133. // use a HostFilter to SetConnectAddress()
  134. func (h *HostInfo) ConnectAddress() net.IP {
  135. h.mu.RLock()
  136. defer h.mu.RUnlock()
  137. if h.connectAddress == nil {
  138. // Use 'rpc_address' if provided and it's not 0.0.0.0
  139. if h.rpcAddress != nil && !h.rpcAddress.IsUnspecified() {
  140. return h.rpcAddress
  141. } else if h.broadcastAddress != nil && !h.broadcastAddress.IsUnspecified() {
  142. return h.broadcastAddress
  143. } else if h.peer != nil {
  144. // Peer should always be set if this from 'system.peer'
  145. return h.peer
  146. }
  147. }
  148. return h.connectAddress
  149. }
  150. func (h *HostInfo) SetConnectAddress(address net.IP) *HostInfo {
  151. h.mu.Lock()
  152. defer h.mu.Unlock()
  153. h.connectAddress = address
  154. return h
  155. }
  156. func (h *HostInfo) BroadcastAddress() net.IP {
  157. h.mu.RLock()
  158. defer h.mu.RUnlock()
  159. return h.broadcastAddress
  160. }
  161. func (h *HostInfo) ListenAddress() net.IP {
  162. h.mu.RLock()
  163. defer h.mu.RUnlock()
  164. return h.listenAddress
  165. }
  166. func (h *HostInfo) RPCAddress() net.IP {
  167. h.mu.RLock()
  168. defer h.mu.RUnlock()
  169. return h.rpcAddress
  170. }
  171. func (h *HostInfo) PreferredIP() net.IP {
  172. h.mu.RLock()
  173. defer h.mu.RUnlock()
  174. return h.preferredIP
  175. }
  176. func (h *HostInfo) DataCenter() string {
  177. h.mu.RLock()
  178. defer h.mu.RUnlock()
  179. return h.dataCenter
  180. }
  181. func (h *HostInfo) setDataCenter(dataCenter string) *HostInfo {
  182. h.mu.Lock()
  183. defer h.mu.Unlock()
  184. h.dataCenter = dataCenter
  185. return h
  186. }
  187. func (h *HostInfo) Rack() string {
  188. h.mu.RLock()
  189. defer h.mu.RUnlock()
  190. return h.rack
  191. }
  192. func (h *HostInfo) setRack(rack string) *HostInfo {
  193. h.mu.Lock()
  194. defer h.mu.Unlock()
  195. h.rack = rack
  196. return h
  197. }
  198. func (h *HostInfo) HostID() string {
  199. h.mu.RLock()
  200. defer h.mu.RUnlock()
  201. return h.hostId
  202. }
  203. func (h *HostInfo) setHostID(hostID string) *HostInfo {
  204. h.mu.Lock()
  205. defer h.mu.Unlock()
  206. h.hostId = hostID
  207. return h
  208. }
  209. func (h *HostInfo) WorkLoad() string {
  210. h.mu.RLock()
  211. defer h.mu.RUnlock()
  212. return h.workload
  213. }
  214. func (h *HostInfo) Graph() bool {
  215. h.mu.RLock()
  216. defer h.mu.RUnlock()
  217. return h.graph
  218. }
  219. func (h *HostInfo) DSEVersion() string {
  220. h.mu.RLock()
  221. defer h.mu.RUnlock()
  222. return h.dseVersion
  223. }
  224. func (h *HostInfo) Partitioner() string {
  225. h.mu.RLock()
  226. defer h.mu.RUnlock()
  227. return h.partitioner
  228. }
  229. func (h *HostInfo) ClusterName() string {
  230. h.mu.RLock()
  231. defer h.mu.RUnlock()
  232. return h.clusterName
  233. }
  234. func (h *HostInfo) Version() cassVersion {
  235. h.mu.RLock()
  236. defer h.mu.RUnlock()
  237. return h.version
  238. }
  239. func (h *HostInfo) setVersion(major, minor, patch int) *HostInfo {
  240. h.mu.Lock()
  241. defer h.mu.Unlock()
  242. h.version = cassVersion{major, minor, patch}
  243. return h
  244. }
  245. func (h *HostInfo) State() nodeState {
  246. h.mu.RLock()
  247. defer h.mu.RUnlock()
  248. return h.state
  249. }
  250. func (h *HostInfo) setState(state nodeState) *HostInfo {
  251. h.mu.Lock()
  252. defer h.mu.Unlock()
  253. h.state = state
  254. return h
  255. }
  256. func (h *HostInfo) Tokens() []string {
  257. h.mu.RLock()
  258. defer h.mu.RUnlock()
  259. return h.tokens
  260. }
  261. func (h *HostInfo) setTokens(tokens []string) *HostInfo {
  262. h.mu.Lock()
  263. defer h.mu.Unlock()
  264. h.tokens = tokens
  265. return h
  266. }
  267. func (h *HostInfo) Port() int {
  268. h.mu.RLock()
  269. defer h.mu.RUnlock()
  270. return h.port
  271. }
  272. func (h *HostInfo) setPort(port int) *HostInfo {
  273. h.mu.Lock()
  274. defer h.mu.Unlock()
  275. h.port = port
  276. return h
  277. }
  278. func (h *HostInfo) update(from *HostInfo) {
  279. h.mu.Lock()
  280. defer h.mu.Unlock()
  281. h.tokens = from.tokens
  282. h.version = from.version
  283. h.hostId = from.hostId
  284. h.dataCenter = from.dataCenter
  285. }
  286. func (h *HostInfo) IsUp() bool {
  287. return h != nil && h.State() == NodeUp
  288. }
  289. func (h *HostInfo) String() string {
  290. h.mu.RLock()
  291. defer h.mu.RUnlock()
  292. return fmt.Sprintf("[HostInfo connectAddress=%q peer=%q rpc_address=%q broadcast_address=%q "+
  293. "port=%d data_centre=%q rack=%q host_id=%q version=%q state=%s num_tokens=%d]",
  294. h.connectAddress, h.peer, h.rpcAddress, h.broadcastAddress,
  295. h.port, h.dataCenter, h.rack, h.hostId, h.version, h.state, len(h.tokens))
  296. }
  297. // Polls system.peers at a specific interval to find new hosts
  298. type ringDescriber struct {
  299. session *Session
  300. mu sync.Mutex
  301. prevHosts []*HostInfo
  302. localHost *HostInfo
  303. prevPartitioner string
  304. }
  305. // Returns true if we are using system_schema.keyspaces instead of system.schema_keyspaces
  306. func checkSystemSchema(control *controlConn) (bool, error) {
  307. iter := control.query("SELECT * FROM system_schema.keyspaces")
  308. if err := iter.err; err != nil {
  309. if errf, ok := err.(*errorFrame); ok {
  310. if errf.code == errSyntax {
  311. return false, nil
  312. }
  313. }
  314. return false, err
  315. }
  316. return true, nil
  317. }
  318. // Given a map that represents a row from either system.local or system.peers
  319. // return as much information as we can in *HostInfo
  320. func (r *ringDescriber) hostInfoFromMap(row map[string]interface{}) (*HostInfo, error) {
  321. const assertErrorMsg = "Assertion failed for %s"
  322. var ok bool
  323. // Default to our connected port if the cluster doesn't have port information
  324. host := HostInfo{
  325. port: r.session.cfg.Port,
  326. }
  327. for key, value := range row {
  328. switch key {
  329. case "data_center":
  330. host.dataCenter, ok = value.(string)
  331. if !ok {
  332. return nil, fmt.Errorf(assertErrorMsg, "data_center")
  333. }
  334. case "rack":
  335. host.rack, ok = value.(string)
  336. if !ok {
  337. return nil, fmt.Errorf(assertErrorMsg, "rack")
  338. }
  339. case "host_id":
  340. hostId, ok := value.(UUID)
  341. if !ok {
  342. return nil, fmt.Errorf(assertErrorMsg, "host_id")
  343. }
  344. host.hostId = hostId.String()
  345. case "release_version":
  346. version, ok := value.(string)
  347. if !ok {
  348. return nil, fmt.Errorf(assertErrorMsg, "release_version")
  349. }
  350. host.version.Set(version)
  351. case "peer":
  352. ip, ok := value.(string)
  353. if !ok {
  354. return nil, fmt.Errorf(assertErrorMsg, "peer")
  355. }
  356. host.peer = net.ParseIP(ip)
  357. case "cluster_name":
  358. host.clusterName, ok = value.(string)
  359. if !ok {
  360. return nil, fmt.Errorf(assertErrorMsg, "cluster_name")
  361. }
  362. case "partitioner":
  363. host.partitioner, ok = value.(string)
  364. if !ok {
  365. return nil, fmt.Errorf(assertErrorMsg, "partitioner")
  366. }
  367. case "broadcast_address":
  368. ip, ok := value.(string)
  369. if !ok {
  370. return nil, fmt.Errorf(assertErrorMsg, "broadcast_address")
  371. }
  372. host.broadcastAddress = net.ParseIP(ip)
  373. case "preferred_ip":
  374. ip, ok := value.(string)
  375. if !ok {
  376. return nil, fmt.Errorf(assertErrorMsg, "preferred_ip")
  377. }
  378. host.preferredIP = net.ParseIP(ip)
  379. case "rpc_address":
  380. ip, ok := value.(string)
  381. if !ok {
  382. return nil, fmt.Errorf(assertErrorMsg, "rpc_address")
  383. }
  384. host.rpcAddress = net.ParseIP(ip)
  385. case "listen_address":
  386. ip, ok := value.(string)
  387. if !ok {
  388. return nil, fmt.Errorf(assertErrorMsg, "listen_address")
  389. }
  390. host.listenAddress = net.ParseIP(ip)
  391. case "workload":
  392. host.workload, ok = value.(string)
  393. if !ok {
  394. return nil, fmt.Errorf(assertErrorMsg, "workload")
  395. }
  396. case "graph":
  397. host.graph, ok = value.(bool)
  398. if !ok {
  399. return nil, fmt.Errorf(assertErrorMsg, "graph")
  400. }
  401. case "tokens":
  402. host.tokens, ok = value.([]string)
  403. if !ok {
  404. return nil, fmt.Errorf(assertErrorMsg, "tokens")
  405. }
  406. case "dse_version":
  407. host.dseVersion, ok = value.(string)
  408. if !ok {
  409. return nil, fmt.Errorf(assertErrorMsg, "dse_version")
  410. }
  411. }
  412. // TODO(thrawn01): Add 'port'? once CASSANDRA-7544 is complete
  413. // Not sure what the port field will be called until the JIRA issue is complete
  414. }
  415. return &host, nil
  416. }
  417. // Ask the control node for it's local host information
  418. func (r *ringDescriber) GetLocalHostInfo() (*HostInfo, error) {
  419. it := r.session.control.query("SELECT * FROM system.local WHERE key='local'")
  420. if it == nil {
  421. return nil, errors.New("Attempted to query 'system.local' on a closed control connection")
  422. }
  423. host, err := r.extractHostInfo(it)
  424. if err != nil {
  425. return nil, err
  426. }
  427. if host.invalidConnectAddr() {
  428. host.SetConnectAddress(r.session.control.GetHostInfo().ConnectAddress())
  429. }
  430. return host, nil
  431. }
  432. // Given an ip address and port, return a peer that matched the ip address
  433. func (r *ringDescriber) GetPeerHostInfo(ip net.IP, port int) (*HostInfo, error) {
  434. it := r.session.control.query("SELECT * FROM system.peers WHERE peer=?", ip)
  435. if it == nil {
  436. return nil, errors.New("Attempted to query 'system.peers' on a closed control connection")
  437. }
  438. return r.extractHostInfo(it)
  439. }
  440. func (r *ringDescriber) extractHostInfo(it *Iter) (*HostInfo, error) {
  441. row := make(map[string]interface{})
  442. // expect only 1 row
  443. it.MapScan(row)
  444. if err := it.Close(); err != nil {
  445. return nil, err
  446. }
  447. // extract all available info about the host
  448. return r.hostInfoFromMap(row)
  449. }
  450. // Ask the control node for host info on all it's known peers
  451. func (r *ringDescriber) GetClusterPeerInfo() ([]*HostInfo, error) {
  452. var hosts []*HostInfo
  453. // Ask the node for a list of it's peers
  454. it := r.session.control.query("SELECT * FROM system.peers")
  455. if it == nil {
  456. return nil, errors.New("Attempted to query 'system.peers' on a closed connection")
  457. }
  458. for {
  459. row := make(map[string]interface{})
  460. if !it.MapScan(row) {
  461. break
  462. }
  463. // extract all available info about the peer
  464. host, err := r.hostInfoFromMap(row)
  465. if err != nil {
  466. return nil, err
  467. }
  468. // If it's not a valid peer
  469. if !r.IsValidPeer(host) {
  470. Logger.Printf("Found invalid peer '%+v' "+
  471. "Likely due to a gossip or snitch issue, this host will be ignored", host)
  472. continue
  473. }
  474. hosts = append(hosts, host)
  475. }
  476. if it.err != nil {
  477. return nil, fmt.Errorf("while scanning 'system.peers' table: %s", it.err)
  478. }
  479. return hosts, nil
  480. }
  481. // Return true if the host is a valid peer
  482. func (r *ringDescriber) IsValidPeer(host *HostInfo) bool {
  483. return !(len(host.RPCAddress()) == 0 ||
  484. host.hostId == "" ||
  485. host.dataCenter == "" ||
  486. host.rack == "" ||
  487. len(host.tokens) == 0)
  488. }
  489. // Return a list of hosts the cluster knows about
  490. func (r *ringDescriber) GetHosts() ([]*HostInfo, string, error) {
  491. r.mu.Lock()
  492. defer r.mu.Unlock()
  493. // Update the localHost info with data from the connected host
  494. localHost, err := r.GetLocalHostInfo()
  495. if err != nil {
  496. return r.prevHosts, r.prevPartitioner, err
  497. } else if localHost.invalidConnectAddr() {
  498. panic(fmt.Sprintf("unable to get localhost connect address: %v", localHost))
  499. }
  500. // Update our list of hosts by querying the cluster
  501. hosts, err := r.GetClusterPeerInfo()
  502. if err != nil {
  503. return r.prevHosts, r.prevPartitioner, err
  504. }
  505. hosts = append(hosts, localHost)
  506. // Filter the hosts if filter is provided
  507. filteredHosts := hosts
  508. if r.session.cfg.HostFilter != nil {
  509. filteredHosts = filteredHosts[:0]
  510. for _, host := range hosts {
  511. if r.session.cfg.HostFilter.Accept(host) {
  512. filteredHosts = append(filteredHosts, host)
  513. }
  514. }
  515. }
  516. r.prevHosts = filteredHosts
  517. r.prevPartitioner = localHost.partitioner
  518. r.localHost = localHost
  519. return filteredHosts, localHost.partitioner, nil
  520. }
  521. // Given an ip/port return HostInfo for the specified ip/port
  522. func (r *ringDescriber) GetHostInfo(ip net.IP, port int) (*HostInfo, error) {
  523. // TODO(thrawn01): Is IgnorePeerAddr still useful now that we have DisableInitialHostLookup?
  524. // TODO(thrawn01): should we also check for DisableInitialHostLookup and return if true?
  525. // Ignore the port and connect address and use the address/port we already have
  526. if r.session.control == nil || r.session.cfg.IgnorePeerAddr {
  527. return &HostInfo{connectAddress: ip, port: port}, nil
  528. }
  529. // Attempt to get the host info for our control connection
  530. controlHost := r.session.control.GetHostInfo()
  531. if controlHost == nil {
  532. return nil, errors.New("invalid control connection")
  533. }
  534. var (
  535. host *HostInfo
  536. err error
  537. )
  538. // If we are asking about the same node our control connection has a connection too
  539. if controlHost.ConnectAddress().Equal(ip) {
  540. host, err = r.GetLocalHostInfo()
  541. } else {
  542. host, err = r.GetPeerHostInfo(ip, port)
  543. }
  544. // No host was found matching this ip/port
  545. if err != nil {
  546. return nil, err
  547. }
  548. if controlHost.ConnectAddress().Equal(ip) {
  549. // Always respect the provided control node address and disregard the ip address
  550. // the cassandra node provides. We do this as we are already connected and have a
  551. // known valid ip address. This insulates gocql from client connection issues stemming
  552. // from node misconfiguration. For instance when a node is run from a container, by
  553. // default the node will report its ip address as 127.0.0.1 which is typically invalid.
  554. host.SetConnectAddress(ip)
  555. }
  556. if host.invalidConnectAddr() {
  557. return nil, fmt.Errorf("host ConnectAddress invalid: %v", host)
  558. }
  559. return host, nil
  560. }
  561. func (r *ringDescriber) refreshRing() error {
  562. // if we have 0 hosts this will return the previous list of hosts to
  563. // attempt to reconnect to the cluster otherwise we would never find
  564. // downed hosts again, could possibly have an optimisation to only
  565. // try to add new hosts if GetHosts didnt error and the hosts didnt change.
  566. hosts, partitioner, err := r.GetHosts()
  567. if err != nil {
  568. return err
  569. }
  570. prevHosts := r.session.ring.currentHosts()
  571. // TODO: move this to session
  572. for _, h := range hosts {
  573. if host, ok := r.session.ring.addHostIfMissing(h); !ok {
  574. r.session.pool.addHost(h)
  575. r.session.policy.AddHost(h)
  576. } else {
  577. host.update(h)
  578. }
  579. delete(prevHosts, h.ConnectAddress().String())
  580. }
  581. // TODO(zariel): it may be worth having a mutex covering the overall ring state
  582. // in a session so that everything sees a consistent state. Becuase as is today
  583. // events can come in and due to ordering an UP host could be removed from the cluster
  584. for _, host := range prevHosts {
  585. r.session.removeHost(host)
  586. }
  587. r.session.metadata.setPartitioner(partitioner)
  588. r.session.policy.SetPartitioner(partitioner)
  589. return nil
  590. }