host_source.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. prevPartitioner string
  312. }
  313. // Returns true if we are using system_schema.keyspaces instead of system.schema_keyspaces
  314. func checkSystemSchema(control *controlConn) (bool, error) {
  315. iter := control.query("SELECT * FROM system_schema.keyspaces")
  316. if err := iter.err; err != nil {
  317. if errf, ok := err.(*errorFrame); ok {
  318. if errf.code == errSyntax {
  319. return false, nil
  320. }
  321. }
  322. return false, err
  323. }
  324. return true, nil
  325. }
  326. // Given a map that represents a row from either system.local or system.peers
  327. // return as much information as we can in *HostInfo
  328. func hostInfoFromMap(row map[string]interface{}, defaultPort int) (*HostInfo, error) {
  329. const assertErrorMsg = "Assertion failed for %s"
  330. var ok bool
  331. // Default to our connected port if the cluster doesn't have port information
  332. host := HostInfo{
  333. port: defaultPort,
  334. }
  335. for key, value := range row {
  336. switch key {
  337. case "data_center":
  338. host.dataCenter, ok = value.(string)
  339. if !ok {
  340. return nil, fmt.Errorf(assertErrorMsg, "data_center")
  341. }
  342. case "rack":
  343. host.rack, ok = value.(string)
  344. if !ok {
  345. return nil, fmt.Errorf(assertErrorMsg, "rack")
  346. }
  347. case "host_id":
  348. hostId, ok := value.(UUID)
  349. if !ok {
  350. return nil, fmt.Errorf(assertErrorMsg, "host_id")
  351. }
  352. host.hostId = hostId.String()
  353. case "release_version":
  354. version, ok := value.(string)
  355. if !ok {
  356. return nil, fmt.Errorf(assertErrorMsg, "release_version")
  357. }
  358. host.version.Set(version)
  359. case "peer":
  360. ip, ok := value.(string)
  361. if !ok {
  362. return nil, fmt.Errorf(assertErrorMsg, "peer")
  363. }
  364. host.peer = net.ParseIP(ip)
  365. case "cluster_name":
  366. host.clusterName, ok = value.(string)
  367. if !ok {
  368. return nil, fmt.Errorf(assertErrorMsg, "cluster_name")
  369. }
  370. case "partitioner":
  371. host.partitioner, ok = value.(string)
  372. if !ok {
  373. return nil, fmt.Errorf(assertErrorMsg, "partitioner")
  374. }
  375. case "broadcast_address":
  376. ip, ok := value.(string)
  377. if !ok {
  378. return nil, fmt.Errorf(assertErrorMsg, "broadcast_address")
  379. }
  380. host.broadcastAddress = net.ParseIP(ip)
  381. case "preferred_ip":
  382. ip, ok := value.(string)
  383. if !ok {
  384. return nil, fmt.Errorf(assertErrorMsg, "preferred_ip")
  385. }
  386. host.preferredIP = net.ParseIP(ip)
  387. case "rpc_address":
  388. ip, ok := value.(string)
  389. if !ok {
  390. return nil, fmt.Errorf(assertErrorMsg, "rpc_address")
  391. }
  392. host.rpcAddress = net.ParseIP(ip)
  393. case "listen_address":
  394. ip, ok := value.(string)
  395. if !ok {
  396. return nil, fmt.Errorf(assertErrorMsg, "listen_address")
  397. }
  398. host.listenAddress = net.ParseIP(ip)
  399. case "workload":
  400. host.workload, ok = value.(string)
  401. if !ok {
  402. return nil, fmt.Errorf(assertErrorMsg, "workload")
  403. }
  404. case "graph":
  405. host.graph, ok = value.(bool)
  406. if !ok {
  407. return nil, fmt.Errorf(assertErrorMsg, "graph")
  408. }
  409. case "tokens":
  410. host.tokens, ok = value.([]string)
  411. if !ok {
  412. return nil, fmt.Errorf(assertErrorMsg, "tokens")
  413. }
  414. case "dse_version":
  415. host.dseVersion, ok = value.(string)
  416. if !ok {
  417. return nil, fmt.Errorf(assertErrorMsg, "dse_version")
  418. }
  419. }
  420. // TODO(thrawn01): Add 'port'? once CASSANDRA-7544 is complete
  421. // Not sure what the port field will be called until the JIRA issue is complete
  422. }
  423. return &host, nil
  424. }
  425. // Ask the control node for host info on all it's known peers
  426. func (r *ringDescriber) getClusterPeerInfo() ([]*HostInfo, error) {
  427. var hosts []*HostInfo
  428. iter := r.session.control.withConnHost(func(ch *connHost) *Iter {
  429. hosts = append(hosts, ch.host)
  430. return ch.conn.query("SELECT * FROM system.peers")
  431. })
  432. if iter == nil {
  433. return nil, errNoControl
  434. }
  435. rows, err := iter.SliceMap()
  436. if err != nil {
  437. // TODO(zariel): make typed error
  438. return nil, fmt.Errorf("unable to fetch peer host info: %s", err)
  439. }
  440. for _, row := range rows {
  441. // extract all available info about the peer
  442. host, err := hostInfoFromMap(row, r.session.cfg.Port)
  443. if err != nil {
  444. return nil, err
  445. } else if !isValidPeer(host) {
  446. // If it's not a valid peer
  447. Logger.Printf("Found invalid peer '%s' "+
  448. "Likely due to a gossip or snitch issue, this host will be ignored", host)
  449. continue
  450. }
  451. hosts = append(hosts, host)
  452. }
  453. return hosts, nil
  454. }
  455. // Return true if the host is a valid peer
  456. func isValidPeer(host *HostInfo) bool {
  457. return !(len(host.RPCAddress()) == 0 ||
  458. host.hostId == "" ||
  459. host.dataCenter == "" ||
  460. host.rack == "" ||
  461. len(host.tokens) == 0)
  462. }
  463. // Return a list of hosts the cluster knows about
  464. func (r *ringDescriber) GetHosts() ([]*HostInfo, string, error) {
  465. r.mu.Lock()
  466. defer r.mu.Unlock()
  467. hosts, err := r.getClusterPeerInfo()
  468. if err != nil {
  469. return r.prevHosts, r.prevPartitioner, err
  470. }
  471. var partitioner string
  472. if len(hosts) > 0 {
  473. partitioner = hosts[0].Partitioner()
  474. }
  475. return hosts, partitioner, nil
  476. }
  477. // Given an ip/port return HostInfo for the specified ip/port
  478. func (r *ringDescriber) getHostInfo(ip net.IP, port int) (*HostInfo, error) {
  479. var host *HostInfo
  480. iter := r.session.control.withConnHost(func(ch *connHost) *Iter {
  481. if ch.host.ConnectAddress().Equal(ip) {
  482. host = ch.host
  483. return nil
  484. }
  485. return ch.conn.query("SELECT * FROM system.peers WHERE peer=?", ip)
  486. })
  487. if iter != nil {
  488. row, err := iter.rowMap()
  489. if err != nil {
  490. return nil, err
  491. }
  492. host, err = hostInfoFromMap(row, port)
  493. if err != nil {
  494. return nil, err
  495. }
  496. } else if host == nil {
  497. return nil, errors.New("unable to fetch host info: invalid control connection")
  498. }
  499. if host.invalidConnectAddr() {
  500. return nil, fmt.Errorf("host ConnectAddress invalid ip=%v: %v", ip, host)
  501. }
  502. return host, nil
  503. }
  504. func (r *ringDescriber) refreshRing() error {
  505. // if we have 0 hosts this will return the previous list of hosts to
  506. // attempt to reconnect to the cluster otherwise we would never find
  507. // downed hosts again, could possibly have an optimisation to only
  508. // try to add new hosts if GetHosts didnt error and the hosts didnt change.
  509. hosts, partitioner, err := r.GetHosts()
  510. if err != nil {
  511. return err
  512. }
  513. prevHosts := r.session.ring.currentHosts()
  514. // TODO: move this to session
  515. for _, h := range hosts {
  516. if filter := r.session.cfg.HostFilter; filter != nil && !filter.Accept(h) {
  517. continue
  518. }
  519. if host, ok := r.session.ring.addHostIfMissing(h); !ok {
  520. r.session.pool.addHost(h)
  521. r.session.policy.AddHost(h)
  522. } else {
  523. host.update(h)
  524. }
  525. delete(prevHosts, h.ConnectAddress().String())
  526. }
  527. // TODO(zariel): it may be worth having a mutex covering the overall ring state
  528. // in a session so that everything sees a consistent state. Becuase as is today
  529. // events can come in and due to ordering an UP host could be removed from the cluster
  530. for _, host := range prevHosts {
  531. r.session.removeHost(host)
  532. }
  533. r.session.metadata.setPartitioner(partitioner)
  534. r.session.policy.SetPartitioner(partitioner)
  535. return nil
  536. }