host_source.go 15 KB

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