host_source.go 16 KB

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