forked from apache/horaedb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
578 lines (534 loc) · 19.4 KB
/
lib.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
// Copyright 2023 CeresDB Project Authors. Licensed under Apache-2.0.
//! The proxy module provides features such as forwarding and authentication,
//! adapts to different protocols.
#![feature(trait_alias)]
pub mod context;
pub mod error;
mod error_util;
pub mod forward;
mod grpc;
pub mod handlers;
pub mod hotspot;
mod hotspot_lru;
pub mod http;
pub mod influxdb;
pub mod instance;
pub mod limiter;
pub mod opentsdb;
mod read;
pub mod schema_config_provider;
mod util;
mod write;
pub const FORWARDED_FROM: &str = "forwarded-from";
use std::{
sync::Arc,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use ::http::StatusCode;
use analytic_engine::table_options::{parse_duration, ENABLE_TTL, TTL};
use catalog::{
schema::{
CreateOptions, CreateTableRequest, DropOptions, DropTableRequest, NameRef, SchemaRef,
},
CatalogRef,
};
use ceresdbproto::storage::{
storage_service_client::StorageServiceClient, PrometheusRemoteQueryRequest,
PrometheusRemoteQueryResponse, Route, RouteRequest,
};
use common_types::{request_id::RequestId, table::DEFAULT_SHARD_ID};
use common_util::{error::BoxError, runtime::Runtime};
use datafusion::prelude::{Column, Expr};
use futures::FutureExt;
use influxql_query::logical_optimizer::range_predicate::find_time_range;
use interpreters::{
context::Context as InterpreterContext,
factory::Factory,
interpreter::{InterpreterPtr, Output},
};
use log::{error, info};
use query_engine::executor::Executor as QueryExecutor;
use query_frontend::plan::Plan;
use router::{endpoint::Endpoint, Router};
use snafu::{OptionExt, ResultExt};
use table_engine::{
engine::{EngineRuntimes, TableState},
remote::model::{GetTableInfoRequest, TableIdentifier},
table::{TableId, TableRef},
PARTITION_TABLE_ENGINE_TYPE,
};
use tonic::{transport::Channel, IntoRequest};
use crate::{
error::{ErrNoCause, ErrWithCause, Error, Internal, Result},
forward::{ForwardRequest, ForwardResult, Forwarder, ForwarderRef},
hotspot::HotspotRecorder,
instance::InstanceRef,
schema_config_provider::SchemaConfigProviderRef,
};
pub struct Proxy<Q> {
router: Arc<dyn Router + Send + Sync>,
forwarder: ForwarderRef,
instance: InstanceRef<Q>,
resp_compress_min_length: usize,
auto_create_table: bool,
schema_config_provider: SchemaConfigProviderRef,
hotspot_recorder: Arc<HotspotRecorder>,
engine_runtimes: Arc<EngineRuntimes>,
cluster_with_meta: bool,
}
impl<Q: QueryExecutor + 'static> Proxy<Q> {
#[allow(clippy::too_many_arguments)]
pub fn new(
router: Arc<dyn Router + Send + Sync>,
instance: InstanceRef<Q>,
forward_config: forward::Config,
local_endpoint: Endpoint,
resp_compress_min_length: usize,
auto_create_table: bool,
schema_config_provider: SchemaConfigProviderRef,
hotspot_config: hotspot::Config,
engine_runtimes: Arc<EngineRuntimes>,
cluster_with_meta: bool,
) -> Self {
let forwarder = Arc::new(Forwarder::new(
forward_config,
router.clone(),
local_endpoint,
));
let hotspot_recorder = Arc::new(HotspotRecorder::new(
hotspot_config,
engine_runtimes.default_runtime.clone(),
));
Self {
router,
instance,
forwarder,
resp_compress_min_length,
auto_create_table,
schema_config_provider,
hotspot_recorder,
engine_runtimes,
cluster_with_meta,
}
}
pub fn instance(&self) -> InstanceRef<Q> {
self.instance.clone()
}
fn default_catalog_name(&self) -> NameRef {
self.instance.catalog_manager.default_catalog_name()
}
async fn maybe_forward_prom_remote_query(
&self,
metric: String,
req: PrometheusRemoteQueryRequest,
) -> Result<Option<ForwardResult<PrometheusRemoteQueryResponse, Error>>> {
let req_ctx = req.context.as_ref().unwrap();
let forward_req = ForwardRequest {
schema: req_ctx.database.clone(),
table: metric,
req: req.into_request(),
forwarded_from: None,
};
let do_query = |mut client: StorageServiceClient<Channel>,
request: tonic::Request<PrometheusRemoteQueryRequest>,
_: &Endpoint| {
let query = async move {
client
.prom_remote_query(request)
.await
.map(|resp| resp.into_inner())
.box_err()
.context(ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: "Forwarded sql query failed",
})
}
.boxed();
Box::new(query) as _
};
let forward_result = self.forwarder.forward(forward_req, do_query).await;
Ok(match forward_result {
Ok(forward_res) => Some(forward_res),
Err(e) => {
error!("Failed to forward prom req but the error is ignored, err:{e}");
None
}
})
}
fn valid_ttl_range(
&self,
plan: &Plan,
catalog_name: &str,
schema_name: &str,
table_name: &str,
) -> bool {
if let Plan::Query(query) = &plan {
let tableref = match self.get_table(catalog_name, schema_name, table_name) {
Ok(Some(tableref)) => tableref,
_ => return true,
};
if let Some(value) = tableref.options().get(ENABLE_TTL) {
if value == "false" {
return true;
}
}
let ttl_duration = match tableref.options().get(TTL) {
Some(value) => parse_duration(value),
None => return false,
};
assert!(ttl_duration.is_ok(), "ttl_duration muse be vaild");
let ttl_duration = ttl_duration.unwrap();
// TODO(tanruixiang): use sql's timestamp as nowtime(need sql support)
let nowtime = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(duration) => duration.as_secs() as i64,
Err(_) => {
return false;
}
};
// Because the clock may have errors, choose 1 hour as the error buffer
let buffer_duration = Duration::new(60 * 60, 0);
let ddl = nowtime - ttl_duration.as_secs() as i64 - buffer_duration.as_secs() as i64;
let timestamp_name = &tableref
.schema()
.column(tableref.schema().timestamp_index())
.name
.clone();
let ts_col = Column::from_name(timestamp_name);
let range = find_time_range(&query.df_plan, &ts_col).unwrap();
match range.end {
std::ops::Bound::Included(x) | std::ops::Bound::Excluded(x) => {
if let Expr::Literal(datafusion::scalar::ScalarValue::Int64(Some(x))) = x {
if x <= ddl {
return false;
}
}
}
std::ops::Bound::Unbounded => (),
}
}
true
}
fn get_catalog(&self, catalog_name: &str) -> Result<CatalogRef> {
let catalog = self
.instance
.catalog_manager
.catalog_by_name(catalog_name)
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to find catalog, catalog_name:{catalog_name}"),
})?
.with_context(|| ErrNoCause {
code: StatusCode::BAD_REQUEST,
msg: format!("Catalog not found, catalog_name:{catalog_name}"),
})?;
Ok(catalog)
}
fn get_schema(&self, catalog: &CatalogRef, schema_name: &str) -> Result<SchemaRef> {
// TODO: support create schema if not exist
let schema = catalog
.schema_by_name(schema_name)
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to find schema, schema_name:{schema_name}"),
})?
.context(ErrNoCause {
code: StatusCode::BAD_REQUEST,
msg: format!("Schema not found, schema_name:{schema_name}"),
})?;
Ok(schema)
}
fn get_table(
&self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
) -> Result<Option<TableRef>> {
let catalog = self.get_catalog(catalog_name)?;
let schema = self.get_schema(&catalog, schema_name)?;
let table = schema
.table_by_name(table_name)
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to find table, table_name:{table_name}"),
})?;
Ok(table)
}
async fn maybe_open_partition_table_if_not_exist(
&self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
) -> Result<()> {
let catalog = self
.instance
.catalog_manager
.catalog_by_name(catalog_name)
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to find catalog, catalog_name:{catalog_name}"),
})?
.with_context(|| ErrNoCause {
code: StatusCode::BAD_REQUEST,
msg: format!("Catalog not found, catalog_name:{catalog_name}"),
})?;
// TODO: support create schema if not exist
let schema = catalog
.schema_by_name(schema_name)
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to find schema, schema_name:{schema_name}"),
})?
.context(ErrNoCause {
code: StatusCode::BAD_REQUEST,
msg: format!("Schema not found, schema_name:{schema_name}"),
})?;
let table = schema
.table_by_name(table_name)
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to find table, table_name:{table_name}"),
})?;
let table_info_in_meta = self
.router
.fetch_table_info(schema_name, table_name)
.await?;
if let Some(table_info_in_meta) = &table_info_in_meta {
// No need to handle non-partition table.
if !table_info_in_meta.is_partition_table() {
return Ok(());
}
}
match (table, &table_info_in_meta) {
(Some(table), Some(partition_table_info)) => {
// No need to create partition table when table_id match.
if table.id().as_u64() == partition_table_info.id {
return Ok(());
}
info!("Drop partition table because the id of the table in ceresdb is different from the one in ceresmeta, catalog_name:{catalog_name}, schema_name:{schema_name}, table_name:{table_name}, old_table_id:{}, new_table_id:{}",
table.id().as_u64(), partition_table_info.id);
// Drop partition table because the id of the table in ceresdb is different from
// the one in ceresmeta.
self.drop_partition_table(
schema.clone(),
catalog_name.to_string(),
schema_name.to_string(),
table_name.to_string(),
)
.await?;
}
(Some(table), None) => {
// Drop partition table because it does not exist in ceresmeta but exists in
// ceresdb-server.
if table.partition_info().is_some() {
info!("Drop partition table because it does not exist in ceresmeta but exists in ceresdb-server, catalog_name:{catalog_name}, schema_name:{schema_name}, table_name:{table_name}, table_id:{}",table.id());
self.drop_partition_table(
schema.clone(),
catalog_name.to_string(),
schema_name.to_string(),
table_name.to_string(),
)
.await?;
}
// No need to create non-partition table.
return Ok(());
}
// No need to create partition table when table not exist.
(None, None) => return Ok(()),
// Create partition table in following code.
(None, Some(_)) => (),
}
let partition_table_info = table_info_in_meta.unwrap();
// If table not exists, open it.
// Get table_schema from first sub partition table.
let first_sub_partition_table_name = util::get_sub_partition_name(
&partition_table_info.name,
partition_table_info.partition_info.as_ref().unwrap(),
0usize,
);
let table = self
.instance
.remote_engine_ref
.get_table_info(GetTableInfoRequest {
table: TableIdentifier {
catalog: catalog_name.to_string(),
schema: schema_name.to_string(),
table: first_sub_partition_table_name,
},
})
.await
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: "Failed to get table",
})?;
// Partition table is a virtual table, so we need to create it manually.
// Partition info is stored in ceresmeta, so we need to use create_table_request
// to create it.
let create_table_request = CreateTableRequest {
catalog_name: catalog_name.to_string(),
schema_name: schema_name.to_string(),
table_name: partition_table_info.name,
table_id: Some(TableId::new(partition_table_info.id)),
table_schema: table.table_schema,
engine: table.engine,
options: table.options,
state: TableState::Stable,
shard_id: DEFAULT_SHARD_ID,
partition_info: partition_table_info.partition_info,
};
let create_opts = CreateOptions {
table_engine: self.instance.partition_table_engine.clone(),
create_if_not_exists: true,
};
schema
.create_table(create_table_request.clone(), create_opts)
.await
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to create table, request:{create_table_request:?}"),
})?;
Ok(())
}
async fn drop_partition_table(
&self,
schema: SchemaRef,
catalog_name: String,
schema_name: String,
table_name: String,
) -> Result<()> {
let opts = DropOptions {
table_engine: self.instance.partition_table_engine.clone(),
};
schema
.drop_table(
DropTableRequest {
catalog_name,
schema_name,
table_name: table_name.clone(),
engine: PARTITION_TABLE_ENGINE_TYPE.to_string(),
},
opts,
)
.await
.box_err()
.with_context(|| ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: format!("Failed to drop partition table, table_name:{table_name}"),
})?;
Ok(())
}
pub(crate) async fn route(&self, req: RouteRequest) -> Result<Vec<Route>> {
self.router
.route(req)
.await
.box_err()
.context(ErrWithCause {
code: StatusCode::INTERNAL_SERVER_ERROR,
msg: "fail to route",
})
}
async fn execute_plan(
&self,
request_id: RequestId,
catalog: &str,
schema: &str,
plan: Plan,
deadline: Option<Instant>,
) -> Result<Output> {
self.instance
.limiter
.try_limit(&plan)
.box_err()
.context(Internal {
msg: "Request is blocked",
})?;
let interpreter =
self.build_interpreter(request_id, catalog, schema, plan, deadline, false)?;
Self::interpreter_execute_plan(interpreter, deadline).await
}
async fn execute_plan_involving_partition_table(
&self,
request_id: RequestId,
catalog: &str,
schema: &str,
plan: Plan,
deadline: Option<Instant>,
) -> Result<Output> {
self.instance
.limiter
.try_limit(&plan)
.box_err()
.context(Internal {
msg: "Request is blocked",
})?;
let interpreter =
self.build_interpreter(request_id, catalog, schema, plan, deadline, true)?;
Self::interpreter_execute_plan(interpreter, deadline).await
}
fn build_interpreter(
&self,
request_id: RequestId,
catalog: &str,
schema: &str,
plan: Plan,
deadline: Option<Instant>,
enable_partition_table_access: bool,
) -> Result<InterpreterPtr> {
let interpreter_ctx = InterpreterContext::builder(request_id, deadline)
// Use current ctx's catalog and schema as default catalog and schema
.default_catalog_and_schema(catalog.to_string(), schema.to_string())
.enable_partition_table_access(enable_partition_table_access)
.build();
let interpreter_factory = Factory::new(
self.instance.query_executor.clone(),
self.instance.catalog_manager.clone(),
self.instance.table_engine.clone(),
self.instance.table_manipulator.clone(),
);
interpreter_factory
.create(interpreter_ctx, plan)
.box_err()
.context(Internal {
msg: "Failed to create interpreter",
})
}
async fn interpreter_execute_plan(
interpreter: InterpreterPtr,
deadline: Option<Instant>,
) -> Result<Output> {
if let Some(deadline) = deadline {
tokio::time::timeout_at(
tokio::time::Instant::from_std(deadline),
interpreter.execute(),
)
.await
.box_err()
.context(Internal {
msg: "Plan execution timeout",
})
.and_then(|v| {
v.box_err().context(Internal {
msg: "Failed to execute interpreter",
})
})
} else {
interpreter.execute().await.box_err().context(Internal {
msg: "Failed to execute interpreter",
})
}
}
}
#[derive(Clone)]
pub struct Context {
pub timeout: Option<Duration>,
pub runtime: Arc<Runtime>,
pub enable_partition_table_access: bool,
pub forwarded_from: Option<String>,
}