You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1111 lines
34 KiB

  1. /*
  2. Copyright 2017 Google LLC
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package spanner
  14. import (
  15. "container/heap"
  16. "container/list"
  17. "context"
  18. "fmt"
  19. "log"
  20. "math/rand"
  21. "strings"
  22. "sync"
  23. "time"
  24. sppb "google.golang.org/genproto/googleapis/spanner/v1"
  25. "google.golang.org/grpc/codes"
  26. "google.golang.org/grpc/metadata"
  27. )
  28. // sessionHandle is an interface for transactions to access Cloud Spanner sessions safely. It is generated by sessionPool.take().
  29. type sessionHandle struct {
  30. // mu guarantees that the inner session object is returned / destroyed only once.
  31. mu sync.Mutex
  32. // session is a pointer to a session object. Transactions never need to access it directly.
  33. session *session
  34. }
  35. // recycle gives the inner session object back to its home session pool. It is safe to call recycle multiple times but only the first one would take effect.
  36. func (sh *sessionHandle) recycle() {
  37. sh.mu.Lock()
  38. defer sh.mu.Unlock()
  39. if sh.session == nil {
  40. // sessionHandle has already been recycled.
  41. return
  42. }
  43. sh.session.recycle()
  44. sh.session = nil
  45. }
  46. // getID gets the Cloud Spanner session ID from the internal session object. getID returns empty string if the sessionHandle is nil or the inner session
  47. // object has been released by recycle / destroy.
  48. func (sh *sessionHandle) getID() string {
  49. sh.mu.Lock()
  50. defer sh.mu.Unlock()
  51. if sh.session == nil {
  52. // sessionHandle has already been recycled/destroyed.
  53. return ""
  54. }
  55. return sh.session.getID()
  56. }
  57. // getClient gets the Cloud Spanner RPC client associated with the session ID in sessionHandle.
  58. func (sh *sessionHandle) getClient() sppb.SpannerClient {
  59. sh.mu.Lock()
  60. defer sh.mu.Unlock()
  61. if sh.session == nil {
  62. return nil
  63. }
  64. return sh.session.client
  65. }
  66. // getMetadata returns the metadata associated with the session in sessionHandle.
  67. func (sh *sessionHandle) getMetadata() metadata.MD {
  68. sh.mu.Lock()
  69. defer sh.mu.Unlock()
  70. if sh.session == nil {
  71. return nil
  72. }
  73. return sh.session.md
  74. }
  75. // getTransactionID returns the transaction id in the session if available.
  76. func (sh *sessionHandle) getTransactionID() transactionID {
  77. sh.mu.Lock()
  78. defer sh.mu.Unlock()
  79. if sh.session == nil {
  80. return nil
  81. }
  82. return sh.session.tx
  83. }
  84. // destroy destroys the inner session object. It is safe to call destroy multiple times and only the first call would attempt to
  85. // destroy the inner session object.
  86. func (sh *sessionHandle) destroy() {
  87. sh.mu.Lock()
  88. s := sh.session
  89. sh.session = nil
  90. sh.mu.Unlock()
  91. if s == nil {
  92. // sessionHandle has already been destroyed.
  93. return
  94. }
  95. s.destroy(false)
  96. }
  97. // session wraps a Cloud Spanner session ID through which transactions are created and executed.
  98. type session struct {
  99. // client is the RPC channel to Cloud Spanner. It is set only once during session's creation.
  100. client sppb.SpannerClient
  101. // id is the unique id of the session in Cloud Spanner. It is set only once during session's creation.
  102. id string
  103. // pool is the session's home session pool where it was created. It is set only once during session's creation.
  104. pool *sessionPool
  105. // createTime is the timestamp of the session's creation. It is set only once during session's creation.
  106. createTime time.Time
  107. // mu protects the following fields from concurrent access: both healthcheck workers and transactions can modify them.
  108. mu sync.Mutex
  109. // valid marks the validity of a session.
  110. valid bool
  111. // hcIndex is the index of the session inside the global healthcheck queue. If hcIndex < 0, session has been unregistered from the queue.
  112. hcIndex int
  113. // idleList is the linkedlist node which links the session to its home session pool's idle list. If idleList == nil, the
  114. // session is not in idle list.
  115. idleList *list.Element
  116. // nextCheck is the timestamp of next scheduled healthcheck of the session. It is maintained by the global health checker.
  117. nextCheck time.Time
  118. // checkingHelath is true if currently this session is being processed by health checker. Must be modified under health checker lock.
  119. checkingHealth bool
  120. // md is the Metadata to be sent with each request.
  121. md metadata.MD
  122. // tx contains the transaction id if the session has been prepared for write.
  123. tx transactionID
  124. }
  125. // isValid returns true if the session is still valid for use.
  126. func (s *session) isValid() bool {
  127. s.mu.Lock()
  128. defer s.mu.Unlock()
  129. return s.valid
  130. }
  131. // isWritePrepared returns true if the session is prepared for write.
  132. func (s *session) isWritePrepared() bool {
  133. s.mu.Lock()
  134. defer s.mu.Unlock()
  135. return s.tx != nil
  136. }
  137. // String implements fmt.Stringer for session.
  138. func (s *session) String() string {
  139. s.mu.Lock()
  140. defer s.mu.Unlock()
  141. return fmt.Sprintf("<id=%v, hcIdx=%v, idleList=%p, valid=%v, create=%v, nextcheck=%v>",
  142. s.id, s.hcIndex, s.idleList, s.valid, s.createTime, s.nextCheck)
  143. }
  144. // ping verifies if the session is still alive in Cloud Spanner.
  145. func (s *session) ping() error {
  146. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  147. defer cancel()
  148. return runRetryable(ctx, func(ctx context.Context) error {
  149. _, err := s.client.GetSession(contextWithOutgoingMetadata(ctx, s.pool.md), &sppb.GetSessionRequest{Name: s.getID()}) // s.getID is safe even when s is invalid.
  150. return err
  151. })
  152. }
  153. // setHcIndex atomically sets the session's index in the healthcheck queue and returns the old index.
  154. func (s *session) setHcIndex(i int) int {
  155. s.mu.Lock()
  156. defer s.mu.Unlock()
  157. oi := s.hcIndex
  158. s.hcIndex = i
  159. return oi
  160. }
  161. // setIdleList atomically sets the session's idle list link and returns the old link.
  162. func (s *session) setIdleList(le *list.Element) *list.Element {
  163. s.mu.Lock()
  164. defer s.mu.Unlock()
  165. old := s.idleList
  166. s.idleList = le
  167. return old
  168. }
  169. // invalidate marks a session as invalid and returns the old validity.
  170. func (s *session) invalidate() bool {
  171. s.mu.Lock()
  172. defer s.mu.Unlock()
  173. ov := s.valid
  174. s.valid = false
  175. return ov
  176. }
  177. // setNextCheck sets the timestamp for next healthcheck on the session.
  178. func (s *session) setNextCheck(t time.Time) {
  179. s.mu.Lock()
  180. defer s.mu.Unlock()
  181. s.nextCheck = t
  182. }
  183. // setTransactionID sets the transaction id in the session
  184. func (s *session) setTransactionID(tx transactionID) {
  185. s.mu.Lock()
  186. defer s.mu.Unlock()
  187. s.tx = tx
  188. }
  189. // getID returns the session ID which uniquely identifies the session in Cloud Spanner.
  190. func (s *session) getID() string {
  191. s.mu.Lock()
  192. defer s.mu.Unlock()
  193. return s.id
  194. }
  195. // getHcIndex returns the session's index into the global healthcheck priority queue.
  196. func (s *session) getHcIndex() int {
  197. s.mu.Lock()
  198. defer s.mu.Unlock()
  199. return s.hcIndex
  200. }
  201. // getIdleList returns the session's link in its home session pool's idle list.
  202. func (s *session) getIdleList() *list.Element {
  203. s.mu.Lock()
  204. defer s.mu.Unlock()
  205. return s.idleList
  206. }
  207. // getNextCheck returns the timestamp for next healthcheck on the session.
  208. func (s *session) getNextCheck() time.Time {
  209. s.mu.Lock()
  210. defer s.mu.Unlock()
  211. return s.nextCheck
  212. }
  213. // recycle turns the session back to its home session pool.
  214. func (s *session) recycle() {
  215. s.setTransactionID(nil)
  216. if !s.pool.recycle(s) {
  217. // s is rejected by its home session pool because it expired and the session pool currently has enough open sessions.
  218. s.destroy(false)
  219. }
  220. }
  221. // destroy removes the session from its home session pool, healthcheck queue and Cloud Spanner service.
  222. func (s *session) destroy(isExpire bool) bool {
  223. // Remove s from session pool.
  224. if !s.pool.remove(s, isExpire) {
  225. return false
  226. }
  227. // Unregister s from healthcheck queue.
  228. s.pool.hc.unregister(s)
  229. // Remove s from Cloud Spanner service.
  230. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  231. defer cancel()
  232. s.delete(ctx)
  233. return true
  234. }
  235. func (s *session) delete(ctx context.Context) {
  236. // Ignore the error returned by runRetryable because even if we fail to explicitly destroy the session,
  237. // it will be eventually garbage collected by Cloud Spanner.
  238. err := runRetryable(ctx, func(ctx context.Context) error {
  239. _, e := s.client.DeleteSession(ctx, &sppb.DeleteSessionRequest{Name: s.getID()})
  240. return e
  241. })
  242. if err != nil {
  243. log.Printf("Failed to delete session %v. Error: %v", s.getID(), err)
  244. }
  245. }
  246. // prepareForWrite prepares the session for write if it is not already in that state.
  247. func (s *session) prepareForWrite(ctx context.Context) error {
  248. if s.isWritePrepared() {
  249. return nil
  250. }
  251. tx, err := beginTransaction(ctx, s.getID(), s.client)
  252. if err != nil {
  253. return err
  254. }
  255. s.setTransactionID(tx)
  256. return nil
  257. }
  258. // SessionPoolConfig stores configurations of a session pool.
  259. type SessionPoolConfig struct {
  260. // getRPCClient is the caller supplied method for getting a gRPC client to Cloud Spanner, this makes session pool able to use client pooling.
  261. getRPCClient func() (sppb.SpannerClient, error)
  262. // MaxOpened is the maximum number of opened sessions allowed by the session
  263. // pool. Defaults to NumChannels * 100. If the client tries to open a session and
  264. // there are already MaxOpened sessions, it will block until one becomes
  265. // available or the context passed to the client method is canceled or times out.
  266. MaxOpened uint64
  267. // MinOpened is the minimum number of opened sessions that the session pool
  268. // tries to maintain. Session pool won't continue to expire sessions if number
  269. // of opened connections drops below MinOpened. However, if a session is found
  270. // to be broken, it will still be evicted from the session pool, therefore it is
  271. // posssible that the number of opened sessions drops below MinOpened.
  272. MinOpened uint64
  273. // MaxIdle is the maximum number of idle sessions, pool is allowed to keep. Defaults to 0.
  274. MaxIdle uint64
  275. // MaxBurst is the maximum number of concurrent session creation requests. Defaults to 10.
  276. MaxBurst uint64
  277. // WriteSessions is the fraction of sessions we try to keep prepared for write.
  278. WriteSessions float64
  279. // HealthCheckWorkers is number of workers used by health checker for this pool.
  280. HealthCheckWorkers int
  281. // HealthCheckInterval is how often the health checker pings a session. Defaults to 5 min.
  282. HealthCheckInterval time.Duration
  283. // healthCheckSampleInterval is how often the health checker samples live session (for use in maintaining session pool size). Defaults to 1 min.
  284. healthCheckSampleInterval time.Duration
  285. // sessionLabels for the sessions created in the session pool.
  286. sessionLabels map[string]string
  287. }
  288. // errNoRPCGetter returns error for SessionPoolConfig missing getRPCClient method.
  289. func errNoRPCGetter() error {
  290. return spannerErrorf(codes.InvalidArgument, "require SessionPoolConfig.getRPCClient != nil, got nil")
  291. }
  292. // errMinOpenedGTMapOpened returns error for SessionPoolConfig.MaxOpened < SessionPoolConfig.MinOpened when SessionPoolConfig.MaxOpened is set.
  293. func errMinOpenedGTMaxOpened(maxOpened, minOpened uint64) error {
  294. return spannerErrorf(codes.InvalidArgument,
  295. "require SessionPoolConfig.MaxOpened >= SessionPoolConfig.MinOpened, got %v and %v", maxOpened, minOpened)
  296. }
  297. // validate verifies that the SessionPoolConfig is good for use.
  298. func (spc *SessionPoolConfig) validate() error {
  299. if spc.getRPCClient == nil {
  300. return errNoRPCGetter()
  301. }
  302. if spc.MinOpened > spc.MaxOpened && spc.MaxOpened > 0 {
  303. return errMinOpenedGTMaxOpened(spc.MaxOpened, spc.MinOpened)
  304. }
  305. return nil
  306. }
  307. // sessionPool creates and caches Cloud Spanner sessions.
  308. type sessionPool struct {
  309. // mu protects sessionPool from concurrent access.
  310. mu sync.Mutex
  311. // valid marks the validity of the session pool.
  312. valid bool
  313. // db is the database name that all sessions in the pool are associated with.
  314. db string
  315. // idleList caches idle session IDs. Session IDs in this list can be allocated for use.
  316. idleList list.List
  317. // idleWriteList caches idle sessions which have been prepared for write.
  318. idleWriteList list.List
  319. // mayGetSession is for broadcasting that session retrival/creation may proceed.
  320. mayGetSession chan struct{}
  321. // numOpened is the total number of open sessions from the session pool.
  322. numOpened uint64
  323. // createReqs is the number of ongoing session creation requests.
  324. createReqs uint64
  325. // prepareReqs is the number of ongoing session preparation request.
  326. prepareReqs uint64
  327. // configuration of the session pool.
  328. SessionPoolConfig
  329. // Metadata to be sent with each request
  330. md metadata.MD
  331. // hc is the health checker
  332. hc *healthChecker
  333. }
  334. // newSessionPool creates a new session pool.
  335. func newSessionPool(db string, config SessionPoolConfig, md metadata.MD) (*sessionPool, error) {
  336. if err := config.validate(); err != nil {
  337. return nil, err
  338. }
  339. pool := &sessionPool{
  340. db: db,
  341. valid: true,
  342. mayGetSession: make(chan struct{}),
  343. SessionPoolConfig: config,
  344. md: md,
  345. }
  346. if config.HealthCheckWorkers == 0 {
  347. // With 10 workers and assuming average latency of 5 ms for BeginTransaction, we will be able to
  348. // prepare 2000 tx/sec in advance. If the rate of takeWriteSession is more than that, it will
  349. // degrade to doing BeginTransaction inline.
  350. // TODO: consider resizing the worker pool dynamically according to the load.
  351. config.HealthCheckWorkers = 10
  352. }
  353. if config.HealthCheckInterval == 0 {
  354. config.HealthCheckInterval = 5 * time.Minute
  355. }
  356. if config.healthCheckSampleInterval == 0 {
  357. config.healthCheckSampleInterval = time.Minute
  358. }
  359. // On GCE VM, within the same region an healthcheck ping takes on average 10ms to finish, given a 5 minutes interval and
  360. // 10 healthcheck workers, a healthChecker can effectively mantain 100 checks_per_worker/sec * 10 workers * 300 seconds = 300K sessions.
  361. pool.hc = newHealthChecker(config.HealthCheckInterval, config.HealthCheckWorkers, config.healthCheckSampleInterval, pool)
  362. close(pool.hc.ready)
  363. return pool, nil
  364. }
  365. // isValid checks if the session pool is still valid.
  366. func (p *sessionPool) isValid() bool {
  367. if p == nil {
  368. return false
  369. }
  370. p.mu.Lock()
  371. defer p.mu.Unlock()
  372. return p.valid
  373. }
  374. // close marks the session pool as closed.
  375. func (p *sessionPool) close() {
  376. if p == nil {
  377. return
  378. }
  379. p.mu.Lock()
  380. if !p.valid {
  381. p.mu.Unlock()
  382. return
  383. }
  384. p.valid = false
  385. p.mu.Unlock()
  386. p.hc.close()
  387. // destroy all the sessions
  388. p.hc.mu.Lock()
  389. allSessions := make([]*session, len(p.hc.queue.sessions))
  390. copy(allSessions, p.hc.queue.sessions)
  391. p.hc.mu.Unlock()
  392. for _, s := range allSessions {
  393. s.destroy(false)
  394. }
  395. }
  396. // errInvalidSessionPool returns error for using an invalid session pool.
  397. func errInvalidSessionPool() error {
  398. return spannerErrorf(codes.InvalidArgument, "invalid session pool")
  399. }
  400. // errGetSessionTimeout returns error for context timeout during sessionPool.take().
  401. func errGetSessionTimeout() error {
  402. return spannerErrorf(codes.Canceled, "timeout / context canceled during getting session")
  403. }
  404. // shouldPrepareWrite returns true if we should prepare more sessions for write.
  405. func (p *sessionPool) shouldPrepareWrite() bool {
  406. return float64(p.numOpened)*p.WriteSessions > float64(p.idleWriteList.Len()+int(p.prepareReqs))
  407. }
  408. func (p *sessionPool) createSession(ctx context.Context) (*session, error) {
  409. statsPrintf(ctx, nil, "Creating a new session")
  410. doneCreate := func(done bool) {
  411. p.mu.Lock()
  412. if !done {
  413. // Session creation failed, give budget back.
  414. p.numOpened--
  415. recordStat(ctx, OpenSessionCount, int64(p.numOpened))
  416. }
  417. p.createReqs--
  418. // Notify other waiters blocking on session creation.
  419. close(p.mayGetSession)
  420. p.mayGetSession = make(chan struct{})
  421. p.mu.Unlock()
  422. }
  423. sc, err := p.getRPCClient()
  424. if err != nil {
  425. doneCreate(false)
  426. return nil, err
  427. }
  428. s, err := createSession(ctx, sc, p.db, p.sessionLabels, p.md)
  429. if err != nil {
  430. doneCreate(false)
  431. // Should return error directly because of the previous retries on CreateSession RPC.
  432. return nil, err
  433. }
  434. s.pool = p
  435. p.hc.register(s)
  436. doneCreate(true)
  437. return s, nil
  438. }
  439. func createSession(ctx context.Context, sc sppb.SpannerClient, db string, labels map[string]string, md metadata.MD) (*session, error) {
  440. var s *session
  441. err := runRetryable(ctx, func(ctx context.Context) error {
  442. sid, e := sc.CreateSession(ctx, &sppb.CreateSessionRequest{
  443. Database: db,
  444. Session: &sppb.Session{Labels: labels},
  445. })
  446. if e != nil {
  447. return e
  448. }
  449. // If no error, construct the new session.
  450. s = &session{valid: true, client: sc, id: sid.Name, createTime: time.Now(), md: md}
  451. return nil
  452. })
  453. if err != nil {
  454. return nil, err
  455. }
  456. return s, nil
  457. }
  458. func (p *sessionPool) isHealthy(s *session) bool {
  459. if s.getNextCheck().Add(2 * p.hc.getInterval()).Before(time.Now()) {
  460. // TODO: figure out if we need to schedule a new healthcheck worker here.
  461. if err := s.ping(); shouldDropSession(err) {
  462. // The session is already bad, continue to fetch/create a new one.
  463. s.destroy(false)
  464. return false
  465. }
  466. p.hc.scheduledHC(s)
  467. }
  468. return true
  469. }
  470. // take returns a cached session if there are available ones; if there isn't any, it tries to allocate a new one.
  471. // Session returned by take should be used for read operations.
  472. func (p *sessionPool) take(ctx context.Context) (*sessionHandle, error) {
  473. statsPrintf(ctx, nil, "Acquiring a read-only session")
  474. ctx = contextWithOutgoingMetadata(ctx, p.md)
  475. for {
  476. var (
  477. s *session
  478. err error
  479. )
  480. p.mu.Lock()
  481. if !p.valid {
  482. p.mu.Unlock()
  483. return nil, errInvalidSessionPool()
  484. }
  485. if p.idleList.Len() > 0 {
  486. // Idle sessions are available, get one from the top of the idle list.
  487. s = p.idleList.Remove(p.idleList.Front()).(*session)
  488. statsPrintf(ctx, map[string]interface{}{"sessionID": s.getID()},
  489. "Acquired read-only session")
  490. } else if p.idleWriteList.Len() > 0 {
  491. s = p.idleWriteList.Remove(p.idleWriteList.Front()).(*session)
  492. statsPrintf(ctx, map[string]interface{}{"sessionID": s.getID()},
  493. "Acquired read-write session")
  494. }
  495. if s != nil {
  496. s.setIdleList(nil)
  497. p.mu.Unlock()
  498. // From here, session is no longer in idle list, so healthcheck workers won't destroy it.
  499. // If healthcheck workers failed to schedule healthcheck for the session timely, do the check here.
  500. // Because session check is still much cheaper than session creation, they should be reused as much as possible.
  501. if !p.isHealthy(s) {
  502. continue
  503. }
  504. return &sessionHandle{session: s}, nil
  505. }
  506. // Idle list is empty, block if session pool has reached max session creation concurrency or max number of open sessions.
  507. if (p.MaxOpened > 0 && p.numOpened >= p.MaxOpened) || (p.MaxBurst > 0 && p.createReqs >= p.MaxBurst) {
  508. mayGetSession := p.mayGetSession
  509. p.mu.Unlock()
  510. statsPrintf(ctx, nil, "Waiting for read-only session to become available")
  511. select {
  512. case <-ctx.Done():
  513. statsPrintf(ctx, nil, "Context done waiting for session")
  514. return nil, errGetSessionTimeout()
  515. case <-mayGetSession:
  516. }
  517. continue
  518. }
  519. // Take budget before the actual session creation.
  520. p.numOpened++
  521. recordStat(ctx, OpenSessionCount, int64(p.numOpened))
  522. p.createReqs++
  523. p.mu.Unlock()
  524. if s, err = p.createSession(ctx); err != nil {
  525. statsPrintf(ctx, nil, "Error creating session: %v", err)
  526. return nil, toSpannerError(err)
  527. }
  528. statsPrintf(ctx, map[string]interface{}{"sessionID": s.getID()},
  529. "Created session")
  530. return &sessionHandle{session: s}, nil
  531. }
  532. }
  533. // takeWriteSession returns a write prepared cached session if there are available ones; if there isn't any, it tries to allocate a new one.
  534. // Session returned should be used for read write transactions.
  535. func (p *sessionPool) takeWriteSession(ctx context.Context) (*sessionHandle, error) {
  536. statsPrintf(ctx, nil, "Acquiring a read-write session")
  537. ctx = contextWithOutgoingMetadata(ctx, p.md)
  538. for {
  539. var (
  540. s *session
  541. err error
  542. )
  543. p.mu.Lock()
  544. if !p.valid {
  545. p.mu.Unlock()
  546. return nil, errInvalidSessionPool()
  547. }
  548. if p.idleWriteList.Len() > 0 {
  549. // Idle sessions are available, get one from the top of the idle list.
  550. s = p.idleWriteList.Remove(p.idleWriteList.Front()).(*session)
  551. statsPrintf(ctx, map[string]interface{}{"sessionID": s.getID()}, "Acquired read-write session")
  552. } else if p.idleList.Len() > 0 {
  553. s = p.idleList.Remove(p.idleList.Front()).(*session)
  554. statsPrintf(ctx, map[string]interface{}{"sessionID": s.getID()}, "Acquired read-only session")
  555. }
  556. if s != nil {
  557. s.setIdleList(nil)
  558. p.mu.Unlock()
  559. // From here, session is no longer in idle list, so healthcheck workers won't destroy it.
  560. // If healthcheck workers failed to schedule healthcheck for the session timely, do the check here.
  561. // Because session check is still much cheaper than session creation, they should be reused as much as possible.
  562. if !p.isHealthy(s) {
  563. continue
  564. }
  565. } else {
  566. // Idle list is empty, block if session pool has reached max session creation concurrency or max number of open sessions.
  567. if (p.MaxOpened > 0 && p.numOpened >= p.MaxOpened) || (p.MaxBurst > 0 && p.createReqs >= p.MaxBurst) {
  568. mayGetSession := p.mayGetSession
  569. p.mu.Unlock()
  570. statsPrintf(ctx, nil, "Waiting for read-write session to become available")
  571. select {
  572. case <-ctx.Done():
  573. statsPrintf(ctx, nil, "Context done waiting for session")
  574. return nil, errGetSessionTimeout()
  575. case <-mayGetSession:
  576. }
  577. continue
  578. }
  579. // Take budget before the actual session creation.
  580. p.numOpened++
  581. recordStat(ctx, OpenSessionCount, int64(p.numOpened))
  582. p.createReqs++
  583. p.mu.Unlock()
  584. if s, err = p.createSession(ctx); err != nil {
  585. statsPrintf(ctx, nil, "Error creating session: %v", err)
  586. return nil, toSpannerError(err)
  587. }
  588. statsPrintf(ctx, map[string]interface{}{"sessionID": s.getID()},
  589. "Created session")
  590. }
  591. if !s.isWritePrepared() {
  592. if err = s.prepareForWrite(ctx); err != nil {
  593. s.recycle()
  594. statsPrintf(ctx, map[string]interface{}{"sessionID": s.getID()},
  595. "Error preparing session for write")
  596. return nil, toSpannerError(err)
  597. }
  598. }
  599. return &sessionHandle{session: s}, nil
  600. }
  601. }
  602. // recycle puts session s back to the session pool's idle list, it returns true if the session pool successfully recycles session s.
  603. func (p *sessionPool) recycle(s *session) bool {
  604. p.mu.Lock()
  605. defer p.mu.Unlock()
  606. if !s.isValid() || !p.valid {
  607. // Reject the session if session is invalid or pool itself is invalid.
  608. return false
  609. }
  610. // Put session at the back of the list to round robin for load balancing across channels.
  611. if s.isWritePrepared() {
  612. s.setIdleList(p.idleWriteList.PushBack(s))
  613. } else {
  614. s.setIdleList(p.idleList.PushBack(s))
  615. }
  616. // Broadcast that a session has been returned to idle list.
  617. close(p.mayGetSession)
  618. p.mayGetSession = make(chan struct{})
  619. return true
  620. }
  621. // remove atomically removes session s from the session pool and invalidates s.
  622. // If isExpire == true, the removal is triggered by session expiration and in such cases, only idle sessions can be removed.
  623. func (p *sessionPool) remove(s *session, isExpire bool) bool {
  624. p.mu.Lock()
  625. defer p.mu.Unlock()
  626. if isExpire && (p.numOpened <= p.MinOpened || s.getIdleList() == nil) {
  627. // Don't expire session if the session is not in idle list (in use), or if number of open sessions is going below p.MinOpened.
  628. return false
  629. }
  630. ol := s.setIdleList(nil)
  631. // If the session is in the idlelist, remove it.
  632. if ol != nil {
  633. // Remove from whichever list it is in.
  634. p.idleList.Remove(ol)
  635. p.idleWriteList.Remove(ol)
  636. }
  637. if s.invalidate() {
  638. // Decrease the number of opened sessions.
  639. p.numOpened--
  640. recordStat(context.Background(), OpenSessionCount, int64(p.numOpened))
  641. // Broadcast that a session has been destroyed.
  642. close(p.mayGetSession)
  643. p.mayGetSession = make(chan struct{})
  644. return true
  645. }
  646. return false
  647. }
  648. // hcHeap implements heap.Interface. It is used to create the priority queue for session healthchecks.
  649. type hcHeap struct {
  650. sessions []*session
  651. }
  652. // Len impelemnts heap.Interface.Len.
  653. func (h hcHeap) Len() int {
  654. return len(h.sessions)
  655. }
  656. // Less implements heap.Interface.Less.
  657. func (h hcHeap) Less(i, j int) bool {
  658. return h.sessions[i].getNextCheck().Before(h.sessions[j].getNextCheck())
  659. }
  660. // Swap implements heap.Interface.Swap.
  661. func (h hcHeap) Swap(i, j int) {
  662. h.sessions[i], h.sessions[j] = h.sessions[j], h.sessions[i]
  663. h.sessions[i].setHcIndex(i)
  664. h.sessions[j].setHcIndex(j)
  665. }
  666. // Push implements heap.Interface.Push.
  667. func (h *hcHeap) Push(s interface{}) {
  668. ns := s.(*session)
  669. ns.setHcIndex(len(h.sessions))
  670. h.sessions = append(h.sessions, ns)
  671. }
  672. // Pop implements heap.Interface.Pop.
  673. func (h *hcHeap) Pop() interface{} {
  674. old := h.sessions
  675. n := len(old)
  676. s := old[n-1]
  677. h.sessions = old[:n-1]
  678. s.setHcIndex(-1)
  679. return s
  680. }
  681. // healthChecker performs periodical healthchecks on registered sessions.
  682. type healthChecker struct {
  683. // mu protects concurrent access to hcQueue.
  684. mu sync.Mutex
  685. // queue is the priority queue for session healthchecks. Sessions with lower nextCheck rank higher in the queue.
  686. queue hcHeap
  687. // interval is the average interval between two healthchecks on a session.
  688. interval time.Duration
  689. // workers is the number of concurrent healthcheck workers.
  690. workers int
  691. // waitWorkers waits for all healthcheck workers to exit
  692. waitWorkers sync.WaitGroup
  693. // pool is the underlying session pool.
  694. pool *sessionPool
  695. // sampleInterval is the interval of sampling by the maintainer.
  696. sampleInterval time.Duration
  697. // ready is used to signal that maintainer can start running.
  698. ready chan struct{}
  699. // done is used to signal that health checker should be closed.
  700. done chan struct{}
  701. // once is used for closing channel done only once.
  702. once sync.Once
  703. maintainerCancel func()
  704. }
  705. // newHealthChecker initializes new instance of healthChecker.
  706. func newHealthChecker(interval time.Duration, workers int, sampleInterval time.Duration, pool *sessionPool) *healthChecker {
  707. if workers <= 0 {
  708. workers = 1
  709. }
  710. hc := &healthChecker{
  711. interval: interval,
  712. workers: workers,
  713. pool: pool,
  714. sampleInterval: sampleInterval,
  715. ready: make(chan struct{}),
  716. done: make(chan struct{}),
  717. maintainerCancel: func() {},
  718. }
  719. hc.waitWorkers.Add(1)
  720. go hc.maintainer()
  721. for i := 1; i <= hc.workers; i++ {
  722. hc.waitWorkers.Add(1)
  723. go hc.worker(i)
  724. }
  725. return hc
  726. }
  727. // close closes the healthChecker and waits for all healthcheck workers to exit.
  728. func (hc *healthChecker) close() {
  729. hc.mu.Lock()
  730. hc.maintainerCancel()
  731. hc.mu.Unlock()
  732. hc.once.Do(func() { close(hc.done) })
  733. hc.waitWorkers.Wait()
  734. }
  735. // isClosing checks if a healthChecker is already closing.
  736. func (hc *healthChecker) isClosing() bool {
  737. select {
  738. case <-hc.done:
  739. return true
  740. default:
  741. return false
  742. }
  743. }
  744. // getInterval gets the healthcheck interval.
  745. func (hc *healthChecker) getInterval() time.Duration {
  746. hc.mu.Lock()
  747. defer hc.mu.Unlock()
  748. return hc.interval
  749. }
  750. // scheduledHCLocked schedules next healthcheck on session s with the assumption that hc.mu is being held.
  751. func (hc *healthChecker) scheduledHCLocked(s *session) {
  752. // The next healthcheck will be scheduled after [interval*0.5, interval*1.5) nanoseconds.
  753. nsFromNow := rand.Int63n(int64(hc.interval)) + int64(hc.interval)/2
  754. s.setNextCheck(time.Now().Add(time.Duration(nsFromNow)))
  755. if hi := s.getHcIndex(); hi != -1 {
  756. // Session is still being tracked by healthcheck workers.
  757. heap.Fix(&hc.queue, hi)
  758. }
  759. }
  760. // scheduledHC schedules next healthcheck on session s. It is safe to be called concurrently.
  761. func (hc *healthChecker) scheduledHC(s *session) {
  762. hc.mu.Lock()
  763. defer hc.mu.Unlock()
  764. hc.scheduledHCLocked(s)
  765. }
  766. // register registers a session with healthChecker for periodical healthcheck.
  767. func (hc *healthChecker) register(s *session) {
  768. hc.mu.Lock()
  769. defer hc.mu.Unlock()
  770. hc.scheduledHCLocked(s)
  771. heap.Push(&hc.queue, s)
  772. }
  773. // unregister unregisters a session from healthcheck queue.
  774. func (hc *healthChecker) unregister(s *session) {
  775. hc.mu.Lock()
  776. defer hc.mu.Unlock()
  777. oi := s.setHcIndex(-1)
  778. if oi >= 0 {
  779. heap.Remove(&hc.queue, oi)
  780. }
  781. }
  782. // markDone marks that health check for session has been performed.
  783. func (hc *healthChecker) markDone(s *session) {
  784. hc.mu.Lock()
  785. defer hc.mu.Unlock()
  786. s.checkingHealth = false
  787. }
  788. // healthCheck checks the health of the session and pings it if needed.
  789. func (hc *healthChecker) healthCheck(s *session) {
  790. defer hc.markDone(s)
  791. if !s.pool.isValid() {
  792. // Session pool is closed, perform a garbage collection.
  793. s.destroy(false)
  794. return
  795. }
  796. if err := s.ping(); shouldDropSession(err) {
  797. // Ping failed, destroy the session.
  798. s.destroy(false)
  799. }
  800. }
  801. // worker performs the healthcheck on sessions in healthChecker's priority queue.
  802. func (hc *healthChecker) worker(i int) {
  803. // Returns a session which we should ping to keep it alive.
  804. getNextForPing := func() *session {
  805. hc.pool.mu.Lock()
  806. defer hc.pool.mu.Unlock()
  807. hc.mu.Lock()
  808. defer hc.mu.Unlock()
  809. if hc.queue.Len() <= 0 {
  810. // Queue is empty.
  811. return nil
  812. }
  813. s := hc.queue.sessions[0]
  814. if s.getNextCheck().After(time.Now()) && hc.pool.valid {
  815. // All sessions have been checked recently.
  816. return nil
  817. }
  818. hc.scheduledHCLocked(s)
  819. if !s.checkingHealth {
  820. s.checkingHealth = true
  821. return s
  822. }
  823. return nil
  824. }
  825. // Returns a session which we should prepare for write.
  826. getNextForTx := func() *session {
  827. hc.pool.mu.Lock()
  828. defer hc.pool.mu.Unlock()
  829. if hc.pool.shouldPrepareWrite() {
  830. if hc.pool.idleList.Len() > 0 && hc.pool.valid {
  831. hc.mu.Lock()
  832. defer hc.mu.Unlock()
  833. if hc.pool.idleList.Front().Value.(*session).checkingHealth {
  834. return nil
  835. }
  836. session := hc.pool.idleList.Remove(hc.pool.idleList.Front()).(*session)
  837. session.checkingHealth = true
  838. hc.pool.prepareReqs++
  839. return session
  840. }
  841. }
  842. return nil
  843. }
  844. for {
  845. if hc.isClosing() {
  846. // Exit when the pool has been closed and all sessions have been destroyed
  847. // or when health checker has been closed.
  848. hc.waitWorkers.Done()
  849. return
  850. }
  851. ws := getNextForTx()
  852. if ws != nil {
  853. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  854. err := ws.prepareForWrite(contextWithOutgoingMetadata(ctx, hc.pool.md))
  855. cancel()
  856. if err != nil {
  857. // Skip handling prepare error, session can be prepared in next cycle
  858. log.Printf("Failed to prepare session, error: %v", toSpannerError(err))
  859. }
  860. hc.pool.recycle(ws)
  861. hc.pool.mu.Lock()
  862. hc.pool.prepareReqs--
  863. hc.pool.mu.Unlock()
  864. hc.markDone(ws)
  865. }
  866. rs := getNextForPing()
  867. if rs == nil {
  868. if ws == nil {
  869. // No work to be done so sleep to avoid burning cpu
  870. pause := int64(100 * time.Millisecond)
  871. if pause > int64(hc.interval) {
  872. pause = int64(hc.interval)
  873. }
  874. select {
  875. case <-time.After(time.Duration(rand.Int63n(pause) + pause/2)):
  876. case <-hc.done:
  877. }
  878. }
  879. continue
  880. }
  881. hc.healthCheck(rs)
  882. }
  883. }
  884. // maintainer maintains the maxSessionsInUse by a window of kWindowSize * sampleInterval.
  885. // Based on this information, health checker will try to maintain the number of sessions by hc..
  886. func (hc *healthChecker) maintainer() {
  887. // Wait so that pool is ready.
  888. <-hc.ready
  889. var (
  890. windowSize uint64 = 10
  891. iteration uint64
  892. )
  893. for {
  894. if hc.isClosing() {
  895. hc.waitWorkers.Done()
  896. return
  897. }
  898. // maxSessionsInUse is the maximum number of sessions in use concurrently over a period of time.
  899. var maxSessionsInUse uint64
  900. // Updates metrics.
  901. hc.pool.mu.Lock()
  902. currSessionsInUse := hc.pool.numOpened - uint64(hc.pool.idleList.Len()) - uint64(hc.pool.idleWriteList.Len())
  903. currSessionsOpened := hc.pool.numOpened
  904. hc.pool.mu.Unlock()
  905. hc.mu.Lock()
  906. if iteration%windowSize == 0 || maxSessionsInUse < currSessionsInUse {
  907. maxSessionsInUse = currSessionsInUse
  908. }
  909. sessionsToKeep := maxUint64(hc.pool.MinOpened,
  910. minUint64(currSessionsOpened, hc.pool.MaxIdle+maxSessionsInUse))
  911. ctx, cancel := context.WithTimeout(context.Background(), hc.sampleInterval)
  912. hc.maintainerCancel = cancel
  913. hc.mu.Unlock()
  914. // Replenish or Shrink pool if needed.
  915. // Note: we don't need to worry about pending create session requests, we only need to sample the current sessions in use.
  916. // the routines will not try to create extra / delete creating sessions.
  917. if sessionsToKeep > currSessionsOpened {
  918. hc.replenishPool(ctx, sessionsToKeep)
  919. } else {
  920. hc.shrinkPool(ctx, sessionsToKeep)
  921. }
  922. select {
  923. case <-ctx.Done():
  924. case <-hc.done:
  925. cancel()
  926. }
  927. iteration++
  928. }
  929. }
  930. // replenishPool is run if numOpened is less than sessionsToKeep, timeouts on sampleInterval.
  931. func (hc *healthChecker) replenishPool(ctx context.Context, sessionsToKeep uint64) {
  932. for {
  933. if ctx.Err() != nil {
  934. return
  935. }
  936. p := hc.pool
  937. p.mu.Lock()
  938. // Take budget before the actual session creation.
  939. if sessionsToKeep <= p.numOpened {
  940. p.mu.Unlock()
  941. break
  942. }
  943. p.numOpened++
  944. recordStat(ctx, OpenSessionCount, int64(p.numOpened))
  945. p.createReqs++
  946. shouldPrepareWrite := p.shouldPrepareWrite()
  947. p.mu.Unlock()
  948. var (
  949. s *session
  950. err error
  951. )
  952. if s, err = p.createSession(ctx); err != nil {
  953. log.Printf("Failed to create session, error: %v", toSpannerError(err))
  954. continue
  955. }
  956. if shouldPrepareWrite {
  957. if err = s.prepareForWrite(ctx); err != nil {
  958. p.recycle(s)
  959. log.Printf("Failed to prepare session, error: %v", toSpannerError(err))
  960. continue
  961. }
  962. }
  963. p.recycle(s)
  964. }
  965. }
  966. // shrinkPool, scales down the session pool.
  967. func (hc *healthChecker) shrinkPool(ctx context.Context, sessionsToKeep uint64) {
  968. for {
  969. if ctx.Err() != nil {
  970. return
  971. }
  972. p := hc.pool
  973. p.mu.Lock()
  974. if sessionsToKeep >= p.numOpened {
  975. p.mu.Unlock()
  976. break
  977. }
  978. var s *session
  979. if p.idleList.Len() > 0 {
  980. s = p.idleList.Front().Value.(*session)
  981. } else if p.idleWriteList.Len() > 0 {
  982. s = p.idleWriteList.Front().Value.(*session)
  983. }
  984. p.mu.Unlock()
  985. if s != nil {
  986. // destroy session as expire.
  987. s.destroy(true)
  988. } else {
  989. break
  990. }
  991. }
  992. }
  993. // shouldDropSession returns true if a particular error leads to the removal of a session
  994. func shouldDropSession(err error) bool {
  995. if err == nil {
  996. return false
  997. }
  998. // If a Cloud Spanner can no longer locate the session (for example, if session is garbage collected), then caller
  999. // should not try to return the session back into the session pool.
  1000. // TODO: once gRPC can return auxiliary error information, stop parsing the error message.
  1001. if ErrCode(err) == codes.NotFound && strings.Contains(ErrDesc(err), "Session not found") {
  1002. return true
  1003. }
  1004. return false
  1005. }
  1006. // maxUint64 returns the maximum of two uint64
  1007. func maxUint64(a, b uint64) uint64 {
  1008. if a > b {
  1009. return a
  1010. }
  1011. return b
  1012. }
  1013. // minUint64 returns the minimum of two uint64
  1014. func minUint64(a, b uint64) uint64 {
  1015. if a > b {
  1016. return b
  1017. }
  1018. return a
  1019. }