Line data Source code
1 : //! Periodically collect consumption metrics for all active tenants
2 : //! and push them to a HTTP endpoint.
3 : use crate::context::{DownloadBehavior, RequestContext};
4 : use crate::task_mgr::{self, TaskKind, BACKGROUND_RUNTIME};
5 : use crate::tenant::size::CalculateSyntheticSizeError;
6 : use crate::tenant::tasks::BackgroundLoopKind;
7 : use crate::tenant::{mgr::TenantManager, LogicalSizeCalculationCause, Tenant};
8 : use camino::Utf8PathBuf;
9 : use consumption_metrics::EventType;
10 : use pageserver_api::models::TenantState;
11 : use remote_storage::{GenericRemoteStorage, RemoteStorageConfig};
12 : use reqwest::Url;
13 : use std::collections::HashMap;
14 : use std::sync::Arc;
15 : use std::time::{Duration, SystemTime};
16 : use tokio::time::Instant;
17 : use tokio_util::sync::CancellationToken;
18 : use tracing::*;
19 : use utils::id::NodeId;
20 :
21 : mod metrics;
22 : use crate::consumption_metrics::metrics::MetricsKey;
23 : mod disk_cache;
24 : mod upload;
25 :
26 : const DEFAULT_HTTP_REPORTING_TIMEOUT: Duration = Duration::from_secs(60);
27 :
28 : /// Basically a key-value pair, but usually in a Vec except for [`Cache`].
29 : ///
30 : /// This is as opposed to `consumption_metrics::Event` which is the externally communicated form.
31 : /// Difference is basically the missing idempotency key, which lives only for the duration of
32 : /// upload attempts.
33 : type RawMetric = (MetricsKey, (EventType, u64));
34 :
35 : /// Caches the [`RawMetric`]s
36 : ///
37 : /// In practice, during startup, last sent values are stored here to be used in calculating new
38 : /// ones. After successful uploading, the cached values are updated to cache. This used to be used
39 : /// for deduplication, but that is no longer needed.
40 : type Cache = HashMap<MetricsKey, (EventType, u64)>;
41 :
42 : /// Main thread that serves metrics collection
43 : #[allow(clippy::too_many_arguments)]
44 0 : pub async fn collect_metrics(
45 0 : tenant_manager: Arc<TenantManager>,
46 0 : metric_collection_endpoint: &Url,
47 0 : metric_collection_bucket: &Option<RemoteStorageConfig>,
48 0 : metric_collection_interval: Duration,
49 0 : synthetic_size_calculation_interval: Duration,
50 0 : node_id: NodeId,
51 0 : local_disk_storage: Utf8PathBuf,
52 0 : cancel: CancellationToken,
53 0 : ctx: RequestContext,
54 0 : ) -> anyhow::Result<()> {
55 0 : // spin up background worker that caclulates tenant sizes
56 0 : let worker_ctx =
57 0 : ctx.detached_child(TaskKind::CalculateSyntheticSize, DownloadBehavior::Download);
58 0 : task_mgr::spawn(
59 0 : BACKGROUND_RUNTIME.handle(),
60 0 : TaskKind::CalculateSyntheticSize,
61 0 : None,
62 0 : None,
63 0 : "synthetic size calculation",
64 0 : false,
65 0 : {
66 0 : let tenant_manager = tenant_manager.clone();
67 0 : async move {
68 0 : calculate_synthetic_size_worker(
69 0 : tenant_manager,
70 0 : synthetic_size_calculation_interval,
71 0 : &cancel,
72 0 : &worker_ctx,
73 0 : )
74 0 : .instrument(info_span!("synthetic_size_worker"))
75 0 : .await?;
76 0 : Ok(())
77 0 : }
78 0 : },
79 0 : );
80 0 :
81 0 : let path: Arc<Utf8PathBuf> = Arc::new(local_disk_storage);
82 0 :
83 0 : let cancel = task_mgr::shutdown_token();
84 0 :
85 0 : let restore_and_reschedule = restore_and_reschedule(&path, metric_collection_interval);
86 :
87 0 : let mut cached_metrics = tokio::select! {
88 : _ = cancel.cancelled() => return Ok(()),
89 : ret = restore_and_reschedule => ret,
90 : };
91 :
92 : // define client here to reuse it for all requests
93 0 : let client = reqwest::ClientBuilder::new()
94 0 : .timeout(DEFAULT_HTTP_REPORTING_TIMEOUT)
95 0 : .build()
96 0 : .expect("Failed to create http client with timeout");
97 :
98 0 : let bucket_client = if let Some(bucket_config) = metric_collection_bucket {
99 0 : match GenericRemoteStorage::from_config(bucket_config).await {
100 0 : Ok(client) => Some(client),
101 0 : Err(e) => {
102 0 : // Non-fatal error: if we were given an invalid config, we will proceed
103 0 : // with sending metrics over the network, but not to S3.
104 0 : tracing::warn!("Invalid configuration for metric_collection_bucket: {e}");
105 0 : None
106 : }
107 : }
108 : } else {
109 0 : None
110 : };
111 :
112 0 : let node_id = node_id.to_string();
113 :
114 0 : loop {
115 0 : let started_at = Instant::now();
116 :
117 : // these are point in time, with variable "now"
118 0 : let metrics = metrics::collect_all_metrics(&tenant_manager, &cached_metrics, &ctx).await;
119 :
120 0 : let metrics = Arc::new(metrics);
121 0 :
122 0 : // why not race cancellation here? because we are one of the last tasks, and if we are
123 0 : // already here, better to try to flush the new values.
124 0 :
125 0 : let flush = async {
126 0 : match disk_cache::flush_metrics_to_disk(&metrics, &path).await {
127 : Ok(()) => {
128 0 : tracing::debug!("flushed metrics to disk");
129 : }
130 0 : Err(e) => {
131 0 : // idea here is that if someone creates a directory as our path, then they
132 0 : // might notice it from the logs before shutdown and remove it
133 0 : tracing::error!("failed to persist metrics to {path:?}: {e:#}");
134 : }
135 : }
136 :
137 0 : if let Some(bucket_client) = &bucket_client {
138 0 : let res =
139 0 : upload::upload_metrics_bucket(bucket_client, &cancel, &node_id, &metrics).await;
140 0 : if let Err(e) = res {
141 0 : tracing::error!("failed to upload to S3: {e:#}");
142 0 : }
143 0 : }
144 0 : };
145 :
146 0 : let upload = async {
147 0 : let res = upload::upload_metrics_http(
148 0 : &client,
149 0 : metric_collection_endpoint,
150 0 : &cancel,
151 0 : &node_id,
152 0 : &metrics,
153 0 : &mut cached_metrics,
154 0 : )
155 0 : .await;
156 0 : if let Err(e) = res {
157 : // serialization error which should never happen
158 0 : tracing::error!("failed to upload via HTTP due to {e:#}");
159 0 : }
160 0 : };
161 :
162 : // let these run concurrently
163 : let (_, _) = tokio::join!(flush, upload);
164 :
165 0 : crate::tenant::tasks::warn_when_period_overrun(
166 0 : started_at.elapsed(),
167 0 : metric_collection_interval,
168 0 : BackgroundLoopKind::ConsumptionMetricsCollectMetrics,
169 0 : );
170 :
171 0 : let res = tokio::time::timeout_at(
172 0 : started_at + metric_collection_interval,
173 0 : task_mgr::shutdown_token().cancelled(),
174 0 : )
175 0 : .await;
176 0 : if res.is_ok() {
177 0 : return Ok(());
178 0 : }
179 : }
180 0 : }
181 :
182 : /// Called on the first iteration in an attempt to join the metric uploading schedule from previous
183 : /// pageserver session. Pageserver is supposed to upload at intervals regardless of restarts.
184 : ///
185 : /// Cancellation safe.
186 0 : async fn restore_and_reschedule(
187 0 : path: &Arc<Utf8PathBuf>,
188 0 : metric_collection_interval: Duration,
189 0 : ) -> Cache {
190 0 : let (cached, earlier_metric_at) = match disk_cache::read_metrics_from_disk(path.clone()).await {
191 0 : Ok(found_some) => {
192 0 : // there is no min needed because we write these sequentially in
193 0 : // collect_all_metrics
194 0 : let earlier_metric_at = found_some
195 0 : .iter()
196 0 : .map(|(_, (et, _))| et.recorded_at())
197 0 : .copied()
198 0 : .next();
199 0 :
200 0 : let cached = found_some.into_iter().collect::<Cache>();
201 0 :
202 0 : (cached, earlier_metric_at)
203 : }
204 0 : Err(e) => {
205 0 : use std::io::{Error, ErrorKind};
206 0 :
207 0 : let root = e.root_cause();
208 0 : let maybe_ioerr = root.downcast_ref::<Error>();
209 0 : let is_not_found = maybe_ioerr.is_some_and(|e| e.kind() == ErrorKind::NotFound);
210 0 :
211 0 : if !is_not_found {
212 0 : tracing::info!("failed to read any previous metrics from {path:?}: {e:#}");
213 0 : }
214 :
215 0 : (HashMap::new(), None)
216 : }
217 : };
218 :
219 0 : if let Some(earlier_metric_at) = earlier_metric_at {
220 0 : let earlier_metric_at: SystemTime = earlier_metric_at.into();
221 :
222 0 : let error = reschedule(earlier_metric_at, metric_collection_interval).await;
223 :
224 0 : if let Some(error) = error {
225 0 : if error.as_secs() >= 60 {
226 0 : tracing::info!(
227 0 : error_ms = error.as_millis(),
228 0 : "startup scheduling error due to restart"
229 : )
230 0 : }
231 0 : }
232 0 : }
233 :
234 0 : cached
235 0 : }
236 :
237 0 : async fn reschedule(
238 0 : earlier_metric_at: SystemTime,
239 0 : metric_collection_interval: Duration,
240 0 : ) -> Option<Duration> {
241 0 : let now = SystemTime::now();
242 0 : match now.duration_since(earlier_metric_at) {
243 0 : Ok(from_last_send) if from_last_send < metric_collection_interval => {
244 0 : let sleep_for = metric_collection_interval - from_last_send;
245 0 :
246 0 : let deadline = std::time::Instant::now() + sleep_for;
247 0 :
248 0 : tokio::time::sleep_until(deadline.into()).await;
249 :
250 0 : let now = std::time::Instant::now();
251 0 :
252 0 : // executor threads might be busy, add extra measurements
253 0 : Some(if now < deadline {
254 0 : deadline - now
255 : } else {
256 0 : now - deadline
257 : })
258 : }
259 0 : Ok(from_last_send) => Some(from_last_send.saturating_sub(metric_collection_interval)),
260 : Err(_) => {
261 0 : tracing::warn!(
262 : ?now,
263 : ?earlier_metric_at,
264 0 : "oldest recorded metric is in future; first values will come out with inconsistent timestamps"
265 : );
266 0 : earlier_metric_at.duration_since(now).ok()
267 : }
268 : }
269 0 : }
270 :
271 : /// Caclculate synthetic size for each active tenant
272 0 : async fn calculate_synthetic_size_worker(
273 0 : tenant_manager: Arc<TenantManager>,
274 0 : synthetic_size_calculation_interval: Duration,
275 0 : cancel: &CancellationToken,
276 0 : ctx: &RequestContext,
277 0 : ) -> anyhow::Result<()> {
278 0 : info!("starting calculate_synthetic_size_worker");
279 : scopeguard::defer! {
280 : info!("calculate_synthetic_size_worker stopped");
281 : };
282 :
283 0 : loop {
284 0 : let started_at = Instant::now();
285 :
286 0 : let tenants = match tenant_manager.list_tenants() {
287 0 : Ok(tenants) => tenants,
288 0 : Err(e) => {
289 0 : warn!("cannot get tenant list: {e:#}");
290 0 : continue;
291 : }
292 : };
293 :
294 0 : for (tenant_shard_id, tenant_state, _gen) in tenants {
295 0 : if tenant_state != TenantState::Active {
296 0 : continue;
297 0 : }
298 0 :
299 0 : if !tenant_shard_id.is_shard_zero() {
300 : // We only send consumption metrics from shard 0, so don't waste time calculating
301 : // synthetic size on other shards.
302 0 : continue;
303 0 : }
304 :
305 0 : let Ok(tenant) = tenant_manager.get_attached_tenant_shard(tenant_shard_id) else {
306 0 : continue;
307 : };
308 :
309 0 : if !tenant.is_active() {
310 0 : continue;
311 0 : }
312 0 :
313 0 : // there is never any reason to exit calculate_synthetic_size_worker following any
314 0 : // return value -- we don't need to care about shutdown because no tenant is found when
315 0 : // pageserver is shut down.
316 0 : calculate_and_log(&tenant, cancel, ctx).await;
317 : }
318 :
319 0 : crate::tenant::tasks::warn_when_period_overrun(
320 0 : started_at.elapsed(),
321 0 : synthetic_size_calculation_interval,
322 0 : BackgroundLoopKind::ConsumptionMetricsSyntheticSizeWorker,
323 0 : );
324 :
325 0 : let res = tokio::time::timeout_at(
326 0 : started_at + synthetic_size_calculation_interval,
327 0 : cancel.cancelled(),
328 0 : )
329 0 : .await;
330 0 : if res.is_ok() {
331 0 : return Ok(());
332 0 : }
333 : }
334 0 : }
335 :
336 0 : async fn calculate_and_log(tenant: &Tenant, cancel: &CancellationToken, ctx: &RequestContext) {
337 0 : const CAUSE: LogicalSizeCalculationCause =
338 0 : LogicalSizeCalculationCause::ConsumptionMetricsSyntheticSize;
339 0 :
340 0 : // TODO should we use concurrent_background_tasks_rate_limit() here, like the other background tasks?
341 0 : // We can put in some prioritization for consumption metrics.
342 0 : // Same for the loop that fetches computed metrics.
343 0 : // By using the same limiter, we centralize metrics collection for "start" and "finished" counters,
344 0 : // which turns out is really handy to understand the system.
345 0 : match tenant.calculate_synthetic_size(CAUSE, cancel, ctx).await {
346 0 : Ok(_) => {}
347 0 : Err(CalculateSyntheticSizeError::Cancelled) => {}
348 0 : Err(e) => {
349 0 : let tenant_shard_id = tenant.tenant_shard_id();
350 0 : error!("failed to calculate synthetic size for tenant {tenant_shard_id}: {e:#}");
351 : }
352 : }
353 0 : }
|