-
Notifications
You must be signed in to change notification settings - Fork 992
/
connection_pool.rs
1111 lines (1016 loc) · 41.5 KB
/
connection_pool.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use diesel::r2d2::Builder;
use diesel::{connection::SimpleConnection, pg::PgConnection};
use diesel::{
r2d2::{self, event as e, ConnectionManager, HandleEvent, Pool, PooledConnection},
Connection,
};
use diesel::{sql_query, RunQueryDsl};
use graph::cheap_clone::CheapClone;
use graph::constraint_violation;
use graph::prelude::tokio;
use graph::prelude::tokio::time::Instant;
use graph::util::timed_rw_lock::TimedMutex;
use graph::{
prelude::{
anyhow::{self, anyhow, bail},
crit, debug, error, info, o,
tokio::sync::Semaphore,
CancelGuard, CancelHandle, CancelToken as _, CancelableError, Counter, Gauge, Logger,
MetricsRegistry, MovingStats, PoolWaitStats, StoreError,
},
util::security::SafeDisplay,
};
use std::fmt::{self, Write};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use std::{collections::HashMap, sync::RwLock};
use postgres::config::{Config, Host};
use crate::primary::{self, NAMESPACE_PUBLIC};
use crate::{advisory_lock, catalog};
use crate::{Shard, PRIMARY_SHARD};
lazy_static::lazy_static! {
// There is typically no need to configure this. But this can be used to effectivey disable the
// query semaphore by setting it to a high number.
static ref EXTRA_QUERY_PERMITS: usize = {
std::env::var("GRAPH_EXTRA_QUERY_PERMITS")
.ok()
.map(|s| {
usize::from_str(&s).unwrap_or_else(|_| {
panic!("GRAPH_EXTRA_QUERY_PERMITS must be a number, but is `{}`", s)
})
})
.unwrap_or(0)
};
// These environment variables should really be set through the
// configuration file; especially for min_idle and idle_timeout, it's
// likely that they should be configured differently for each pool
static ref CONNECTION_TIMEOUT: Duration = {
std::env::var("GRAPH_STORE_CONNECTION_TIMEOUT").ok().map(|s| Duration::from_millis(u64::from_str(&s).unwrap_or_else(|_| {
panic!("GRAPH_STORE_CONNECTION_TIMEOUT must be a positive number, but is `{}`", s)
}))).unwrap_or(Duration::from_secs(5))
};
static ref MIN_IDLE: Option<u32> = {
std::env::var("GRAPH_STORE_CONNECTION_MIN_IDLE").ok().map(|s| u32::from_str(&s).unwrap_or_else(|_| {
panic!("GRAPH_STORE_CONNECTION_MIN_IDLE must be a positive number but is `{}`", s)
}))
};
static ref IDLE_TIMEOUT: Duration = {
std::env::var("GRAPH_STORE_CONNECTION_IDLE_TIMEOUT").ok().map(|s| Duration::from_secs(u64::from_str(&s).unwrap_or_else(|_| {
panic!("GRAPH_STORE_CONNECTION_IDLE_TIMEOUT must be a positive number, but is `{}`", s)
}))).unwrap_or(Duration::from_secs(600))
};
// A fallback in case the logic to remember database availability goes
// wrong; when this is set, we always try to get a connection and never
// use the availability state we remembered
static ref TRY_ALWAYS: bool = {
std::env::var("GRAPH_STORE_CONNECTION_TRY_ALWAYS").ok().map(|_| true).unwrap_or(false)
};
}
pub struct ForeignServer {
pub name: String,
pub shard: Shard,
pub user: String,
pub password: String,
pub host: String,
pub port: u16,
pub dbname: String,
}
impl ForeignServer {
pub(crate) const PRIMARY_PUBLIC: &'static str = "primary_public";
/// The name of the foreign server under which data for `shard` is
/// accessible
pub fn name(shard: &Shard) -> String {
format!("shard_{}", shard.as_str())
}
/// The name of the schema under which the `subgraphs` schema for `shard`
/// is accessible in shards that are not `shard`
pub fn metadata_schema(shard: &Shard) -> String {
format!("{}_subgraphs", Self::name(shard))
}
pub fn new_from_raw(shard: String, postgres_url: &str) -> Result<Self, anyhow::Error> {
Self::new(Shard::new(shard)?, postgres_url)
}
pub fn new(shard: Shard, postgres_url: &str) -> Result<Self, anyhow::Error> {
let config: Config = match postgres_url.parse() {
Ok(config) => config,
Err(e) => panic!(
"failed to parse Postgres connection string `{}`: {}",
SafeDisplay(postgres_url),
e
),
};
let host = match config.get_hosts().get(0) {
Some(Host::Tcp(host)) => host.to_string(),
_ => bail!("can not find host name in `{}`", SafeDisplay(postgres_url)),
};
let user = config
.get_user()
.ok_or_else(|| anyhow!("could not find user in `{}`", SafeDisplay(postgres_url)))?
.to_string();
let password = String::from_utf8(
config
.get_password()
.ok_or_else(|| anyhow!("could not find user in `{}`", SafeDisplay(postgres_url)))?
.into(),
)?;
let port = config.get_ports().get(0).cloned().unwrap_or(5432u16);
let dbname = config
.get_dbname()
.map(|s| s.to_string())
.ok_or_else(|| anyhow!("could not find user in `{}`", SafeDisplay(postgres_url)))?;
Ok(Self {
name: Self::name(&shard),
shard,
user,
password,
host,
port,
dbname,
})
}
/// Create a new foreign server and user mapping on `conn` for this foreign
/// server
fn create(&self, conn: &PgConnection) -> Result<(), StoreError> {
let query = format!(
"\
create server \"{name}\"
foreign data wrapper postgres_fdw
options (host '{remote_host}', port '{remote_port}', dbname '{remote_db}', updatable 'false');
create user mapping
for current_user server \"{name}\"
options (user '{remote_user}', password '{remote_password}');",
name = self.name,
remote_host = self.host,
remote_port = self.port,
remote_db = self.dbname,
remote_user = self.user,
remote_password = self.password,
);
Ok(conn.batch_execute(&query)?)
}
/// Update an existing user mapping with possibly new details
fn update(&self, conn: &PgConnection) -> Result<(), StoreError> {
let options = catalog::server_options(conn, &self.name)?;
let set_or_add = |option: &str| -> &'static str {
if options.contains_key(option) {
"set"
} else {
"add"
}
};
let query = format!(
"\
alter server \"{name}\"
options (set host '{remote_host}', {set_port} port '{remote_port}', set dbname '{remote_db}');
alter user mapping
for current_user server \"{name}\"
options (set user '{remote_user}', set password '{remote_password}');",
name = self.name,
remote_host = self.host,
set_port = set_or_add("port"),
remote_port = self.port,
remote_db = self.dbname,
remote_user = self.user,
remote_password = self.password,
);
Ok(conn.batch_execute(&query)?)
}
/// Map key tables from the primary into our local schema. If we are the
/// primary, set them up as views.
///
/// We recreate this mapping on every server start so that migrations that
/// change one of the mapped tables actually show up in the imported tables
fn map_primary(conn: &PgConnection, shard: &Shard) -> Result<(), StoreError> {
catalog::recreate_schema(conn, Self::PRIMARY_PUBLIC)?;
let mut query = String::new();
for table_name in ["deployment_schemas", "chains", "active_copies"] {
let create_stmt = if shard == &*PRIMARY_SHARD {
format!(
"create view {nsp}.{table_name} as select * from public.{table_name};",
nsp = Self::PRIMARY_PUBLIC,
table_name = table_name
)
} else {
catalog::create_foreign_table(
conn,
NAMESPACE_PUBLIC,
table_name,
Self::PRIMARY_PUBLIC,
Self::name(&*PRIMARY_SHARD).as_str(),
)?
};
write!(query, "{}", create_stmt)?;
}
conn.batch_execute(&query)?;
Ok(())
}
/// Map the `subgraphs` schema from the foreign server `self` into the
/// database accessible through `conn`
fn map_metadata(&self, conn: &PgConnection) -> Result<(), StoreError> {
let nsp = Self::metadata_schema(&self.shard);
catalog::recreate_schema(conn, &nsp)?;
let mut query = String::new();
for table_name in [
"subgraph_error",
"dynamic_ethereum_contract_data_source",
"table_stats",
"subgraph_deployment_assignment",
"subgraph",
"subgraph_version",
] {
let create_stmt =
catalog::create_foreign_table(conn, "subgraphs", table_name, &nsp, &self.name)?;
write!(query, "{}", create_stmt)?;
}
Ok(conn.batch_execute(&query)?)
}
}
/// How long to keep connections in the `fdw_pool` around before closing
/// them on idle. This is much shorter than the default of 10 minutes.
const FDW_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
/// A pool goes through several states, and this enum tracks what state we
/// are in, together with the `state_tracker` field on `ConnectionPool`.
/// When first created, the pool is in state `Created`; once we successfully
/// called `setup` on it, it moves to state `Ready`. During use, we use the
/// r2d2 callbacks to determine if the database is available or not, and set
/// the `available` field accordingly. Tracking that allows us to fail fast
/// and avoids having to wait for a connection timeout every time we need a
/// database connection. That avoids overall undesirable states like buildup
/// of queries; instead of queueing them until the database is available,
/// they return almost immediately with an error
enum PoolState {
/// A connection pool, and all the servers for which we need to
/// establish fdw mappings when we call `setup` on the pool
Created(Arc<PoolInner>, Arc<Vec<ForeignServer>>),
/// The pool has been successfully set up
Ready(Arc<PoolInner>),
}
#[derive(Clone)]
pub struct ConnectionPool {
inner: Arc<TimedMutex<PoolState>>,
logger: Logger,
pub shard: Shard,
state_tracker: PoolStateTracker,
}
impl fmt::Debug for ConnectionPool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConnectionPool")
.field("shard", &self.shard)
.finish()
}
}
/// The name of the pool, mostly for logging, and what purpose it serves.
/// The main pool will always be called `main`, and can be used for reading
/// and writing. Replica pools can only be used for reading, and don't
/// require any setup (migrations etc.)
pub enum PoolName {
Main,
Replica(String),
}
impl PoolName {
fn as_str(&self) -> &str {
match self {
PoolName::Main => "main",
PoolName::Replica(name) => name,
}
}
fn is_replica(&self) -> bool {
match self {
PoolName::Main => false,
PoolName::Replica(_) => true,
}
}
}
#[derive(Clone)]
struct PoolStateTracker {
available: Arc<AtomicBool>,
}
impl PoolStateTracker {
fn new() -> Self {
Self {
available: Arc::new(AtomicBool::new(true)),
}
}
fn mark_available(&self) {
self.available.store(true, Ordering::Relaxed);
}
fn mark_unavailable(&self) {
self.available.store(false, Ordering::Relaxed);
}
fn is_available(&self) -> bool {
self.available.load(Ordering::Relaxed)
}
}
impl ConnectionPool {
pub fn create(
shard_name: &str,
pool_name: PoolName,
postgres_url: String,
pool_size: u32,
fdw_pool_size: Option<u32>,
logger: &Logger,
registry: Arc<dyn MetricsRegistry>,
servers: Arc<Vec<ForeignServer>>,
) -> ConnectionPool {
let state_tracker = PoolStateTracker::new();
let pool = PoolInner::create(
shard_name,
pool_name.as_str(),
postgres_url,
pool_size,
fdw_pool_size,
logger,
registry,
state_tracker.clone(),
);
let shard = pool.shard.clone();
let pool_state = if pool_name.is_replica() {
PoolState::Ready(Arc::new(pool))
} else {
PoolState::Created(Arc::new(pool), servers)
};
ConnectionPool {
inner: Arc::new(TimedMutex::new(pool_state, format!("pool-{}", shard_name))),
logger: logger.clone(),
shard,
state_tracker,
}
}
/// This is only used for `graphman` to ensure it doesn't run migrations
/// or other setup steps
pub fn skip_setup(&self) {
let mut guard = self.inner.lock(&self.logger);
match &*guard {
PoolState::Created(pool, _) => *guard = PoolState::Ready(pool.clone()),
PoolState::Ready(_) => { /* nothing to do */ }
}
}
/// Return a pool that is ready, i.e., connected to the database. If the
/// pool has not been set up yet, call `setup`. If there are any errors
/// or the pool is marked as unavailable, return
/// `StoreError::DatabaseUnavailable`
fn get_ready(&self) -> Result<Arc<PoolInner>, StoreError> {
let mut guard = self.inner.lock(&self.logger);
if !self.state_tracker.is_available() && !*TRY_ALWAYS {
// We know that trying to use this pool is pointless since the
// database is not available, and will only lead to other
// operations having to wait until the connection timeout is
// reached. `TRY_ALWAYS` allows users to force us to try
// regardless.
return Err(StoreError::DatabaseUnavailable);
}
match &*guard {
PoolState::Created(pool, servers) => {
pool.setup(servers.clone())?;
let pool2 = pool.clone();
*guard = PoolState::Ready(pool.clone());
self.state_tracker.mark_available();
Ok(pool2)
}
PoolState::Ready(pool) => Ok(pool.clone()),
}
}
/// Execute a closure with a connection to the database.
///
/// # API
/// The API of using a closure to bound the usage of the connection serves several
/// purposes:
///
/// * Moves blocking database access out of the `Future::poll`. Within
/// `Future::poll` (which includes all `async` methods) it is illegal to
/// perform a blocking operation. This includes all accesses to the
/// database, acquiring of locks, etc. Calling a blocking operation can
/// cause problems with `Future` combinators (including but not limited
/// to select, timeout, and FuturesUnordered) and problems with
/// executors/runtimes. This method moves the database work onto another
/// thread in a way which does not block `Future::poll`.
///
/// * Limit the total number of connections. Because the supplied closure
/// takes a reference, we know the scope of the usage of all entity
/// connections and can limit their use in a non-blocking way.
///
/// # Cancellation
/// The normal pattern for futures in Rust is drop to cancel. Once we
/// spawn the database work in a thread though, this expectation no longer
/// holds because the spawned task is the independent of this future. So,
/// this method provides a cancel token which indicates that the `Future`
/// has been dropped. This isn't *quite* as good as drop on cancel,
/// because a drop on cancel can do things like cancel http requests that
/// are in flight, but checking for cancel periodically is a significant
/// improvement.
///
/// The implementation of the supplied closure should check for cancel
/// between every operation that is potentially blocking. This includes
/// any method which may interact with the database. The check can be
/// conveniently written as `token.check_cancel()?;`. It is low overhead
/// to check for cancel, so when in doubt it is better to have too many
/// checks than too few.
///
/// # Panics:
/// * This task will panic if the supplied closure panics
/// * This task will panic if the supplied closure returns Err(Cancelled)
/// when the supplied cancel token is not cancelled.
pub(crate) async fn with_conn<T: Send + 'static>(
&self,
f: impl 'static
+ Send
+ FnOnce(
&PooledConnection<ConnectionManager<PgConnection>>,
&CancelHandle,
) -> Result<T, CancelableError<StoreError>>,
) -> Result<T, StoreError> {
let pool = self.get_ready()?;
pool.with_conn(f).await
}
pub fn get(&self) -> Result<PooledConnection<ConnectionManager<PgConnection>>, StoreError> {
self.get_ready()?.get()
}
/// Get a connection from the pool for foreign data wrapper access;
/// since that pool can be very contended, periodically log that we are
/// still waiting for a connection
///
/// The `timeout` is called every time we time out waiting for a
/// connection. If `timeout` returns `true`, `get_fdw` returns with that
/// error, otherwise we try again to get a connection.
pub fn get_fdw<F>(
&self,
logger: &Logger,
timeout: F,
) -> Result<PooledConnection<ConnectionManager<PgConnection>>, StoreError>
where
F: FnMut() -> bool,
{
self.get_ready()?.get_fdw(logger, timeout)
}
pub fn connection_detail(&self) -> Result<ForeignServer, StoreError> {
let pool = self.get_ready()?;
ForeignServer::new(pool.shard.clone(), &pool.postgres_url).map_err(|e| e.into())
}
/// Check that we can connect to the database
pub fn check(&self) -> bool {
true
}
/// Setup the database for this pool. This includes configuring foreign
/// data wrappers for cross-shard communication, and running any pending
/// schema migrations for this database.
///
/// # Panics
///
/// If any errors happen during the migration, the process panics
pub async fn setup(&self) {
let pool = self.clone();
graph::spawn_blocking_allow_panic(move || {
pool.get_ready().ok();
})
.await
// propagate panics
.unwrap();
}
pub(crate) async fn query_permit(&self) -> tokio::sync::OwnedSemaphorePermit {
let pool = match &*self.inner.lock(&self.logger) {
PoolState::Created(pool, _) | PoolState::Ready(pool) => pool.clone(),
};
pool.query_permit().await
}
pub(crate) fn wait_stats(&self) -> PoolWaitStats {
match &*self.inner.lock(&self.logger) {
PoolState::Created(pool, _) | PoolState::Ready(pool) => pool.wait_stats.clone(),
}
}
/// Mirror key tables from the primary into our own schema. We do this
/// by manually inserting or deleting rows through comparing it with the
/// table on the primary. Once we drop support for PG 9.6, we can
/// simplify all this and achieve the same result with logical
/// replication.
pub(crate) async fn mirror_primary_tables(&self) -> Result<(), StoreError> {
let pool = self.get_ready()?;
pool.mirror_primary_tables().await
}
}
fn brief_error_msg(error: &dyn std::error::Error) -> String {
// For 'Connection refused' errors, Postgres includes the IP and
// port number in the error message. We want to suppress that and
// only use the first line from the error message. For more detailed
// analysis, 'Connection refused' manifests as a
// `ConnectionError(BadConnection("could not connect to server:
// Connection refused.."))`
error
.to_string()
.split("\n")
.next()
.unwrap_or("no error details provided")
.to_string()
}
#[derive(Clone)]
struct ErrorHandler {
logger: Logger,
counter: Counter,
state_tracker: PoolStateTracker,
}
impl ErrorHandler {
fn new(logger: Logger, counter: Counter, state_tracker: PoolStateTracker) -> Self {
Self {
logger,
counter,
state_tracker,
}
}
}
impl std::fmt::Debug for ErrorHandler {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
fmt::Result::Ok(())
}
}
impl r2d2::HandleError<r2d2::Error> for ErrorHandler {
fn handle_error(&self, error: r2d2::Error) {
let msg = brief_error_msg(&error);
// Don't count canceling statements for timeouts etc. as a
// connection error. Unfortunately, we only have the textual error
// and need to infer whether the error indicates that the database
// is down or if something else happened. When querying a replica,
// these messages indicate that a query was canceled because it
// conflicted with replication, but does not indicate that there is
// a problem with the database itself.
//
// This check will break if users run Postgres (or even graph-node)
// in a locale other than English. In that case, their database will
// be marked as unavailable even though it is perfectly fine.
if msg.contains("canceling statement")
|| msg.contains("no connection to the server")
|| msg.contains("terminating connection due to conflict with recovery")
{
return;
}
self.counter.inc();
if self.state_tracker.is_available() {
error!(self.logger, "Postgres connection error"; "error" => msg);
}
self.state_tracker.mark_unavailable();
}
}
#[derive(Clone)]
struct EventHandler {
logger: Logger,
count_gauge: Gauge,
wait_gauge: Gauge,
size_gauge: Gauge,
wait_stats: PoolWaitStats,
state_tracker: PoolStateTracker,
}
impl EventHandler {
fn new(
logger: Logger,
registry: Arc<dyn MetricsRegistry>,
wait_stats: PoolWaitStats,
const_labels: HashMap<String, String>,
state_tracker: PoolStateTracker,
) -> Self {
let count_gauge = registry
.global_gauge(
"store_connection_checkout_count",
"The number of Postgres connections currently checked out",
const_labels.clone(),
)
.expect("failed to create `store_connection_checkout_count` counter");
let wait_gauge = registry
.global_gauge(
"store_connection_wait_time_ms",
"Average connection wait time",
const_labels.clone(),
)
.expect("failed to create `store_connection_wait_time_ms` counter");
let size_gauge = registry
.global_gauge(
"store_connection_pool_size_count",
"Overall size of the connection pool",
const_labels.clone(),
)
.expect("failed to create `store_connection_pool_size_count` counter");
EventHandler {
logger,
count_gauge,
wait_gauge,
wait_stats,
size_gauge,
state_tracker,
}
}
fn add_conn_wait_time(&self, duration: Duration) {
self.wait_stats
.write()
.unwrap()
.add_and_register(duration, &self.wait_gauge);
}
}
impl std::fmt::Debug for EventHandler {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
fmt::Result::Ok(())
}
}
impl HandleEvent for EventHandler {
fn handle_acquire(&self, _: e::AcquireEvent) {
self.size_gauge.inc();
self.state_tracker.mark_available();
}
fn handle_release(&self, _: e::ReleaseEvent) {
self.size_gauge.dec();
}
fn handle_checkout(&self, event: e::CheckoutEvent) {
self.count_gauge.inc();
self.add_conn_wait_time(event.duration());
self.state_tracker.mark_available();
}
fn handle_timeout(&self, event: e::TimeoutEvent) {
self.add_conn_wait_time(event.timeout());
if self.state_tracker.is_available() {
error!(self.logger, "Connection checkout timed out";
"wait_ms" => event.timeout().as_millis()
)
}
self.state_tracker.mark_unavailable();
}
fn handle_checkin(&self, _: e::CheckinEvent) {
self.count_gauge.dec();
}
}
#[derive(Clone)]
pub struct PoolInner {
logger: Logger,
shard: Shard,
pool: Pool<ConnectionManager<PgConnection>>,
// A separate pool for connections that will use foreign data wrappers.
// Once such a connection accesses a foreign table, Postgres keeps a
// connection to the foreign server until the connection is closed.
// Normal pooled connections live quite long (up to 10 minutes) and can
// therefore keep a lot of connections into foreign databases open. We
// mitigate this by using a separate small pool with a much shorter
// connection lifetime. Starting with postgres_fdw 1.1 in Postgres 14,
// this will no longer be needed since it will then be possible to
// explicitly close connections to foreign servers when a connection is
// returned to the pool.
fdw_pool: Option<Pool<ConnectionManager<PgConnection>>>,
limiter: Arc<Semaphore>,
postgres_url: String,
pub(crate) wait_stats: PoolWaitStats,
// Limits the number of graphql queries that may execute concurrently. Since one graphql query
// may require multiple DB queries, it is useful to organize the queue at the graphql level so
// that waiting queries consume few resources. Still this is placed here because the semaphore
// is sized acording to the DB connection pool size.
query_semaphore: Arc<tokio::sync::Semaphore>,
semaphore_wait_stats: Arc<RwLock<MovingStats>>,
semaphore_wait_gauge: Box<Gauge>,
}
impl PoolInner {
fn create(
shard_name: &str,
pool_name: &str,
postgres_url: String,
pool_size: u32,
fdw_pool_size: Option<u32>,
logger: &Logger,
registry: Arc<dyn MetricsRegistry>,
state_tracker: PoolStateTracker,
) -> PoolInner {
let logger_store = logger.new(o!("component" => "Store"));
let logger_pool = logger.new(o!("component" => "ConnectionPool"));
let const_labels = {
let mut map = HashMap::new();
map.insert("pool".to_owned(), pool_name.to_owned());
map.insert("shard".to_string(), shard_name.to_owned());
map
};
let error_counter = registry
.global_counter(
"store_connection_error_count",
"The number of Postgres connections errors",
HashMap::new(),
)
.expect("failed to create `store_connection_error_count` counter");
let error_handler = Box::new(ErrorHandler::new(
logger_pool.clone(),
error_counter,
state_tracker.clone(),
));
let wait_stats = Arc::new(RwLock::new(MovingStats::default()));
let event_handler = Box::new(EventHandler::new(
logger_pool.clone(),
registry.cheap_clone(),
wait_stats.clone(),
const_labels.clone(),
state_tracker,
));
// Connect to Postgres
let conn_manager = ConnectionManager::new(postgres_url.clone());
let builder: Builder<ConnectionManager<PgConnection>> = Pool::builder()
.error_handler(error_handler.clone())
.event_handler(event_handler.clone())
.connection_timeout(*CONNECTION_TIMEOUT)
.max_size(pool_size)
.min_idle(*MIN_IDLE)
.idle_timeout(Some(*IDLE_TIMEOUT));
let pool = builder.build_unchecked(conn_manager);
let fdw_pool = fdw_pool_size.map(|pool_size| {
let conn_manager = ConnectionManager::new(postgres_url.clone());
let builder: Builder<ConnectionManager<PgConnection>> = Pool::builder()
.error_handler(error_handler)
.event_handler(event_handler)
.connection_timeout(*CONNECTION_TIMEOUT)
.max_size(pool_size)
.min_idle(Some(1))
.idle_timeout(Some(FDW_IDLE_TIMEOUT));
builder.build_unchecked(conn_manager)
});
let limiter = Arc::new(Semaphore::new(pool_size as usize));
info!(logger_store, "Pool successfully connected to Postgres");
let semaphore_wait_gauge = registry
.new_gauge(
"query_semaphore_wait_ms",
"Moving average of time spent on waiting for postgres query semaphore",
const_labels,
)
.expect("failed to create `query_effort_ms` counter");
let max_concurrent_queries = pool_size as usize + *EXTRA_QUERY_PERMITS;
let query_semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent_queries));
PoolInner {
logger: logger_pool,
shard: Shard::new(shard_name.to_string())
.expect("shard_name is a valid name for a shard"),
postgres_url: postgres_url.clone(),
pool,
fdw_pool,
limiter,
wait_stats,
semaphore_wait_stats: Arc::new(RwLock::new(MovingStats::default())),
query_semaphore,
semaphore_wait_gauge,
}
}
/// Execute a closure with a connection to the database.
///
/// # API
/// The API of using a closure to bound the usage of the connection serves several
/// purposes:
///
/// * Moves blocking database access out of the `Future::poll`. Within
/// `Future::poll` (which includes all `async` methods) it is illegal to
/// perform a blocking operation. This includes all accesses to the
/// database, acquiring of locks, etc. Calling a blocking operation can
/// cause problems with `Future` combinators (including but not limited
/// to select, timeout, and FuturesUnordered) and problems with
/// executors/runtimes. This method moves the database work onto another
/// thread in a way which does not block `Future::poll`.
///
/// * Limit the total number of connections. Because the supplied closure
/// takes a reference, we know the scope of the usage of all entity
/// connections and can limit their use in a non-blocking way.
///
/// # Cancellation
/// The normal pattern for futures in Rust is drop to cancel. Once we
/// spawn the database work in a thread though, this expectation no longer
/// holds because the spawned task is the independent of this future. So,
/// this method provides a cancel token which indicates that the `Future`
/// has been dropped. This isn't *quite* as good as drop on cancel,
/// because a drop on cancel can do things like cancel http requests that
/// are in flight, but checking for cancel periodically is a significant
/// improvement.
///
/// The implementation of the supplied closure should check for cancel
/// between every operation that is potentially blocking. This includes
/// any method which may interact with the database. The check can be
/// conveniently written as `token.check_cancel()?;`. It is low overhead
/// to check for cancel, so when in doubt it is better to have too many
/// checks than too few.
///
/// # Panics:
/// * This task will panic if the supplied closure panics
/// * This task will panic if the supplied closure returns Err(Cancelled)
/// when the supplied cancel token is not cancelled.
pub(crate) async fn with_conn<T: Send + 'static>(
&self,
f: impl 'static
+ Send
+ FnOnce(
&PooledConnection<ConnectionManager<PgConnection>>,
&CancelHandle,
) -> Result<T, CancelableError<StoreError>>,
) -> Result<T, StoreError> {
let _permit = self.limiter.acquire().await;
let pool = self.clone();
let cancel_guard = CancelGuard::new();
let cancel_handle = cancel_guard.handle();
let result = graph::spawn_blocking_allow_panic(move || {
// It is possible time has passed between scheduling on the
// threadpool and being executed. Time to check for cancel.
cancel_handle.check_cancel()?;
// A failure to establish a connection is propagated as though the
// closure failed.
let conn = pool
.get()
.map_err(|_| CancelableError::Error(StoreError::DatabaseUnavailable))?;
// It is possible time has passed while establishing a connection.
// Time to check for cancel.
cancel_handle.check_cancel()?;
f(&conn, &cancel_handle)
})
.await
.unwrap(); // Propagate panics, though there shouldn't be any.
drop(cancel_guard);
// Finding cancel isn't technically unreachable, since there is nothing
// stopping the supplied closure from returning Canceled even if the
// supplied handle wasn't canceled. That would be very unexpected, the
// doc comment for this function says we will panic in this scenario.
match result {
Ok(t) => Ok(t),
Err(CancelableError::Error(e)) => Err(e),
Err(CancelableError::Cancel) => panic!("The closure supplied to with_entity_conn must not return Err(Canceled) unless the supplied token was canceled."),
}
}
pub fn get(&self) -> Result<PooledConnection<ConnectionManager<PgConnection>>, StoreError> {
self.pool.get().map_err(|_| StoreError::DatabaseUnavailable)
}
pub fn get_with_timeout_warning(
&self,
logger: &Logger,
) -> Result<PooledConnection<ConnectionManager<PgConnection>>, StoreError> {
loop {
match self.pool.get_timeout(*CONNECTION_TIMEOUT) {
Ok(conn) => return Ok(conn),
Err(e) => error!(logger, "Error checking out connection, retrying";
"error" => brief_error_msg(&e),
),
}
}
}
/// Get a connection from the pool for foreign data wrapper access;
/// since that pool can be very contended, periodically log that we are
/// still waiting for a connection
///
/// The `timeout` is called every time we time out waiting for a
/// connection. If `timeout` returns `true`, `get_fdw` returns with that
/// error, otherwise we try again to get a connection.
pub fn get_fdw<F>(
&self,
logger: &Logger,
mut timeout: F,
) -> Result<PooledConnection<ConnectionManager<PgConnection>>, StoreError>
where
F: FnMut() -> bool,
{
let pool = match &self.fdw_pool {
Some(pool) => pool,
None => {
const MSG: &str =
"internal error: trying to get fdw connection on a pool that doesn't have any";
error!(logger, "{}", MSG);
return Err(constraint_violation!(MSG));
}
};
loop {
match pool.get() {
Ok(conn) => return Ok(conn),
Err(e) => {
if timeout() {
return Err(e.into());
}
}
}
}
}
pub fn connection_detail(&self) -> Result<ForeignServer, StoreError> {
ForeignServer::new(self.shard.clone(), &self.postgres_url).map_err(|e| e.into())
}
/// Check that we can connect to the database
pub fn check(&self) -> bool {
self.pool
.get()
.ok()
.map(|conn| sql_query("select 1").execute(&conn).is_ok())
.unwrap_or(false)
}
/// Setup the database for this pool. This includes configuring foreign
/// data wrappers for cross-shard communication, and running any pending
/// schema migrations for this database.
///
/// Returns `StoreError::DatabaseUnavailable` if we can't connect to the
/// database. Any other error causes a panic.
///
/// # Panics
///
/// If any errors happen during the migration, the process panics
pub fn setup(&self, servers: Arc<Vec<ForeignServer>>) -> Result<(), StoreError> {
fn die(logger: &Logger, msg: &'static str, err: &dyn std::fmt::Display) -> ! {
crit!(logger, "{}", msg; "error" => err.to_string());
panic!("{}: {}", msg, err);
}
let pool = self.clone();
let conn = self.get().map_err(|_| StoreError::DatabaseUnavailable)?;
advisory_lock::lock_migration(&conn)
.unwrap_or_else(|err| die(&pool.logger, "failed to get migration lock", &err));
let result = pool
.configure_fdw(servers.as_ref())
.and_then(|()| migrate_schema(&pool.logger, &conn))
.and_then(|()| pool.map_primary())
.and_then(|()| pool.map_metadata(servers.as_ref()));
advisory_lock::unlock_migration(&conn).unwrap_or_else(|err| {