Line data Source code
1 : use std::sync::Arc;
2 : use std::{thread, time::Duration};
3 :
4 : use chrono::{DateTime, Utc};
5 : use postgres::{Client, NoTls};
6 : use tracing::{debug, error, info, warn};
7 :
8 : use crate::compute::ComputeNode;
9 : use compute_api::responses::ComputeStatus;
10 : use compute_api::spec::ComputeFeature;
11 :
12 : const MONITOR_CHECK_INTERVAL: Duration = Duration::from_millis(500);
13 :
14 : // Spin in a loop and figure out the last activity time in the Postgres.
15 : // Then update it in the shared state. This function never errors out.
16 : // NB: the only expected panic is at `Mutex` unwrap(), all other errors
17 : // should be handled gracefully.
18 0 : fn watch_compute_activity(compute: &ComputeNode) {
19 0 : // Suppose that `connstr` doesn't change
20 0 : let connstr = compute.connstr.clone();
21 0 : let conf = compute.get_conn_conf(Some("compute_ctl:activity_monitor"));
22 0 :
23 0 : // During startup and configuration we connect to every Postgres database,
24 0 : // but we don't want to count this as some user activity. So wait until
25 0 : // the compute fully started before monitoring activity.
26 0 : wait_for_postgres_start(compute);
27 0 :
28 0 : // Define `client` outside of the loop to reuse existing connection if it's active.
29 0 : let mut client = conf.connect(NoTls);
30 0 :
31 0 : let mut sleep = false;
32 0 : let mut prev_active_time: Option<f64> = None;
33 0 : let mut prev_sessions: Option<i64> = None;
34 0 :
35 0 : if compute.has_feature(ComputeFeature::ActivityMonitorExperimental) {
36 0 : info!("starting experimental activity monitor for {}", connstr);
37 : } else {
38 0 : info!("starting activity monitor for {}", connstr);
39 : }
40 :
41 : loop {
42 : // We use `continue` a lot, so it's more convenient to sleep at the top of the loop.
43 : // But skip the first sleep, so we can connect to Postgres immediately.
44 0 : if sleep {
45 0 : // Should be outside of the mutex lock to allow others to read while we sleep.
46 0 : thread::sleep(MONITOR_CHECK_INTERVAL);
47 0 : } else {
48 0 : sleep = true;
49 0 : }
50 :
51 0 : match &mut client {
52 0 : Ok(cli) => {
53 0 : if cli.is_closed() {
54 0 : info!("connection to Postgres is closed, trying to reconnect");
55 :
56 : // Connection is closed, reconnect and try again.
57 0 : client = conf.connect(NoTls);
58 0 : continue;
59 0 : }
60 0 :
61 0 : // This is a new logic, only enable if the feature flag is set.
62 0 : // TODO: remove this once we are sure that it works OR drop it altogether.
63 0 : if compute.has_feature(ComputeFeature::ActivityMonitorExperimental) {
64 : // First, check if the total active time or sessions across all databases has changed.
65 : // If it did, it means that user executed some queries. In theory, it can even go down if
66 : // some databases were dropped, but it's still a user activity.
67 0 : match get_database_stats(cli) {
68 0 : Ok((active_time, sessions)) => {
69 0 : let mut detected_activity = false;
70 0 :
71 0 : prev_active_time = match prev_active_time {
72 0 : Some(prev_active_time) => {
73 0 : if active_time != prev_active_time {
74 0 : detected_activity = true;
75 0 : }
76 0 : Some(active_time)
77 : }
78 0 : None => Some(active_time),
79 : };
80 0 : prev_sessions = match prev_sessions {
81 0 : Some(prev_sessions) => {
82 0 : if sessions != prev_sessions {
83 0 : detected_activity = true;
84 0 : }
85 0 : Some(sessions)
86 : }
87 0 : None => Some(sessions),
88 : };
89 :
90 0 : if detected_activity {
91 : // Update the last active time and continue, we don't need to
92 : // check backends state change.
93 0 : compute.update_last_active(Some(Utc::now()));
94 0 : continue;
95 0 : }
96 : }
97 0 : Err(e) => {
98 0 : error!("could not get database statistics: {}", e);
99 0 : continue;
100 : }
101 : }
102 0 : }
103 :
104 : // Second, if database statistics is the same, check all backends state change,
105 : // maybe there is some with more recent activity. `get_backends_state_change()`
106 : // can return None or stale timestamp, so it's `compute.update_last_active()`
107 : // responsibility to check if the new timestamp is more recent than the current one.
108 : // This helps us to discover new sessions, that did nothing yet.
109 0 : match get_backends_state_change(cli) {
110 0 : Ok(last_active) => {
111 0 : compute.update_last_active(last_active);
112 0 : }
113 0 : Err(e) => {
114 0 : error!("could not get backends state change: {}", e);
115 : }
116 : }
117 :
118 : // Finally, if there are existing (logical) walsenders, do not suspend.
119 : //
120 : // walproposer doesn't currently show up in pg_stat_replication,
121 : // but protect if it will be
122 0 : let ws_count_query = "select count(*) from pg_stat_replication where application_name != 'walproposer';";
123 0 : match cli.query_one(ws_count_query, &[]) {
124 0 : Ok(r) => match r.try_get::<&str, i64>("count") {
125 0 : Ok(num_ws) => {
126 0 : if num_ws > 0 {
127 0 : compute.update_last_active(Some(Utc::now()));
128 0 : continue;
129 0 : }
130 : }
131 0 : Err(e) => {
132 0 : warn!("failed to parse walsenders count: {:?}", e);
133 0 : continue;
134 : }
135 : },
136 0 : Err(e) => {
137 0 : warn!("failed to get list of walsenders: {:?}", e);
138 0 : continue;
139 : }
140 : }
141 : //
142 : // Don't suspend compute if there is an active logical replication subscription
143 : //
144 : // `where pid is not null` – to filter out read only computes and subscription on branches
145 : //
146 0 : let logical_subscriptions_query =
147 0 : "select count(*) from pg_stat_subscription where pid is not null;";
148 0 : match cli.query_one(logical_subscriptions_query, &[]) {
149 0 : Ok(row) => match row.try_get::<&str, i64>("count") {
150 0 : Ok(num_subscribers) => {
151 0 : if num_subscribers > 0 {
152 0 : compute.update_last_active(Some(Utc::now()));
153 0 : continue;
154 0 : }
155 : }
156 0 : Err(e) => {
157 0 : warn!("failed to parse `pg_stat_subscription` count: {:?}", e);
158 0 : continue;
159 : }
160 : },
161 0 : Err(e) => {
162 0 : warn!(
163 0 : "failed to get list of active logical replication subscriptions: {:?}",
164 : e
165 : );
166 0 : continue;
167 : }
168 : }
169 : //
170 : // Do not suspend compute if autovacuum is running
171 : //
172 0 : let autovacuum_count_query = "select count(*) from pg_stat_activity where backend_type = 'autovacuum worker'";
173 0 : match cli.query_one(autovacuum_count_query, &[]) {
174 0 : Ok(r) => match r.try_get::<&str, i64>("count") {
175 0 : Ok(num_workers) => {
176 0 : if num_workers > 0 {
177 0 : compute.update_last_active(Some(Utc::now()));
178 0 : continue;
179 0 : }
180 : }
181 0 : Err(e) => {
182 0 : warn!("failed to parse autovacuum workers count: {:?}", e);
183 0 : continue;
184 : }
185 : },
186 0 : Err(e) => {
187 0 : warn!("failed to get list of autovacuum workers: {:?}", e);
188 0 : continue;
189 : }
190 : }
191 : }
192 0 : Err(e) => {
193 0 : debug!("could not connect to Postgres: {}, retrying", e);
194 :
195 : // Establish a new connection and try again.
196 0 : client = conf.connect(NoTls);
197 : }
198 : }
199 : }
200 : }
201 :
202 : // Hang on condition variable waiting until the compute status is `Running`.
203 0 : fn wait_for_postgres_start(compute: &ComputeNode) {
204 0 : let mut state = compute.state.lock().unwrap();
205 0 : while state.status != ComputeStatus::Running {
206 0 : info!("compute is not running, waiting before monitoring activity");
207 0 : state = compute.state_changed.wait(state).unwrap();
208 0 :
209 0 : if state.status == ComputeStatus::Running {
210 0 : break;
211 0 : }
212 : }
213 0 : }
214 :
215 : // Figure out the total active time and sessions across all non-system databases.
216 : // Returned tuple is `(active_time, sessions)`.
217 : // It can return `0.0` active time or `0` sessions, which means no user databases exist OR
218 : // it was a start with skipped `pg_catalog` updates and user didn't do any queries
219 : // (or open any sessions) yet.
220 0 : fn get_database_stats(cli: &mut Client) -> anyhow::Result<(f64, i64)> {
221 0 : // Filter out `postgres` database as `compute_ctl` and other monitoring tools
222 0 : // like `postgres_exporter` use it to query Postgres statistics.
223 0 : // Use explicit 8 bytes type casts to match Rust types.
224 0 : let stats = cli.query_one(
225 0 : "SELECT coalesce(sum(active_time), 0.0)::float8 AS total_active_time,
226 0 : coalesce(sum(sessions), 0)::bigint AS total_sessions
227 0 : FROM pg_stat_database
228 0 : WHERE datname NOT IN (
229 0 : 'postgres',
230 0 : 'template0',
231 0 : 'template1'
232 0 : );",
233 0 : &[],
234 0 : );
235 0 : let stats = match stats {
236 0 : Ok(stats) => stats,
237 0 : Err(e) => {
238 0 : return Err(anyhow::anyhow!("could not query active_time: {}", e));
239 : }
240 : };
241 :
242 0 : let active_time: f64 = match stats.try_get("total_active_time") {
243 0 : Ok(active_time) => active_time,
244 0 : Err(e) => return Err(anyhow::anyhow!("could not get total_active_time: {}", e)),
245 : };
246 :
247 0 : let sessions: i64 = match stats.try_get("total_sessions") {
248 0 : Ok(sessions) => sessions,
249 0 : Err(e) => return Err(anyhow::anyhow!("could not get total_sessions: {}", e)),
250 : };
251 :
252 0 : Ok((active_time, sessions))
253 0 : }
254 :
255 : // Figure out the most recent state change time across all client backends.
256 : // If there is currently active backend, timestamp will be `Utc::now()`.
257 : // It can return `None`, which means no client backends exist or we were
258 : // unable to parse the timestamp.
259 0 : fn get_backends_state_change(cli: &mut Client) -> anyhow::Result<Option<DateTime<Utc>>> {
260 0 : let mut last_active: Option<DateTime<Utc>> = None;
261 0 : // Get all running client backends except ourself, use RFC3339 DateTime format.
262 0 : let backends = cli.query(
263 0 : "SELECT state, to_char(state_change, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS state_change
264 0 : FROM pg_stat_activity
265 0 : WHERE backend_type = 'client backend'
266 0 : AND pid != pg_backend_pid()
267 0 : AND usename != 'cloud_admin';", // XXX: find a better way to filter other monitors?
268 0 : &[],
269 0 : );
270 0 :
271 0 : match backends {
272 0 : Ok(backs) => {
273 0 : let mut idle_backs: Vec<DateTime<Utc>> = vec![];
274 :
275 0 : for b in backs.into_iter() {
276 0 : let state: String = match b.try_get("state") {
277 0 : Ok(state) => state,
278 0 : Err(_) => continue,
279 : };
280 :
281 0 : if state == "idle" {
282 0 : let change: String = match b.try_get("state_change") {
283 0 : Ok(state_change) => state_change,
284 0 : Err(_) => continue,
285 : };
286 0 : let change = DateTime::parse_from_rfc3339(&change);
287 0 : match change {
288 0 : Ok(t) => idle_backs.push(t.with_timezone(&Utc)),
289 0 : Err(e) => {
290 0 : info!("cannot parse backend state_change DateTime: {}", e);
291 0 : continue;
292 : }
293 : }
294 : } else {
295 : // Found non-idle backend, so the last activity is NOW.
296 : // Return immediately, no need to check other backends.
297 0 : return Ok(Some(Utc::now()));
298 : }
299 : }
300 :
301 : // Get idle backend `state_change` with the max timestamp.
302 0 : if let Some(last) = idle_backs.iter().max() {
303 0 : last_active = Some(*last);
304 0 : }
305 : }
306 0 : Err(e) => {
307 0 : return Err(anyhow::anyhow!("could not query backends: {}", e));
308 : }
309 : }
310 :
311 0 : Ok(last_active)
312 0 : }
313 :
314 : /// Launch a separate compute monitor thread and return its `JoinHandle`.
315 0 : pub fn launch_monitor(compute: &Arc<ComputeNode>) -> thread::JoinHandle<()> {
316 0 : let compute = Arc::clone(compute);
317 0 :
318 0 : thread::Builder::new()
319 0 : .name("compute-monitor".into())
320 0 : .spawn(move || watch_compute_activity(&compute))
321 0 : .expect("cannot launch compute monitor thread")
322 0 : }
|