host_source.go 17 KB

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